From 9f7ac3b6a56bca9b41b407eedb44c03f3ca0bbc6 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:44:58 -0400 Subject: [PATCH] feat(glue): serve Glue catalogs and the federated S3 Tables catalog (#8503) --- docs/services/glue.md | 10 + docs/services/index.md | 2 +- .../aws/services/glue/GlueCatalogService.java | 481 ++++++++++++++++++ .../aws/services/glue/GlueJsonHandler.java | 56 +- .../floci/aws/services/glue/GlueService.java | 1 + .../glue/iceberg/GlueIcebergCatalog.java | 62 +-- .../glue/iceberg/IcebergGlueTables.java | 85 ++++ .../aws/services/glue/model/GlueCatalog.java | 79 +++ .../floci/aws/services/glue/model/Table.java | 6 + .../glue/GlueJsonHandlerEmptyListTest.java | 3 +- .../services/glue/GlueJsonHandlerTest.java | 3 +- .../GlueS3TablesCatalogIntegrationTest.java | 230 +++++++++ 12 files changed, 962 insertions(+), 56 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/glue/GlueCatalogService.java create mode 100644 src/main/java/io/floci/aws/services/glue/iceberg/IcebergGlueTables.java create mode 100644 src/main/java/io/floci/aws/services/glue/model/GlueCatalog.java create mode 100644 src/test/java/io/floci/aws/services/glue/GlueS3TablesCatalogIntegrationTest.java diff --git a/docs/services/glue.md b/docs/services/glue.md index 391510f400..8d5d272788 100644 --- a/docs/services/glue.md +++ b/docs/services/glue.md @@ -353,6 +353,16 @@ The operations are the twelve AWS lists: `GetConfig`, `ListNamespaces`, `CreateN Not yet: IAM policies are not checked on this endpoint, so under IAM enforcement it answers only the account's root credentials and Floci's own query engine, and refuses IAM principals (`ForbiddenException`, 403) rather than let them through unchecked. Other accounts' catalogs and nested catalogs (`s3tablescatalog/`) are not served. DuckDB signs SigV4 catalog requests only over HTTPS, so DuckDB attaches this endpoint with SigV4 only when Floci serves TLS (`floci.tls.enabled`). +## Catalogs and Amazon S3 Tables + +`CreateCatalog`, `GetCatalog`, `GetCatalogs`, `UpdateCatalog` and `DeleteCatalog` manage catalogs beside the account's default one. Integrating table buckets with AWS analytics services creates the federated catalog `s3tablescatalog`: + +```bash +aws glue create-catalog --cli-input-json '{"Name":"s3tablescatalog","CatalogInput":{"FederatedCatalog":{"Identifier":"arn:aws:s3tables:us-east-1:000000000000:bucket/*","ConnectionName":"aws:s3tables"},"AllowFullTableExternalDataAccess":"True"}}' +``` + +Each table bucket of the account is then a child catalog, `s3tablescatalog/` (or `:s3tablescatalog/`), listed by `GetCatalogs` with `ParentCatalogId` `s3tablescatalog`, whose `FederatedCatalog.Identifier` is the bucket's ARN. With that `CatalogId`, `GetDatabases` and `GetDatabase` answer the bucket's namespaces, and `GetTables` and `GetTable` its tables, read from S3 Tables: Iceberg tables whose `metadata_location` and columns come from the table's current metadata file. A table without metadata yet has neither. Catalog ids answer as `:[/]`. Writing through a federated catalog (`CreateDatabase`, `CreateTable` with its `CatalogId`), a federated catalog's IAM resources, and the Iceberg REST endpoint's federated catalogs are not served yet. + ## Configuration | Variable | Default | Description | diff --git a/docs/services/index.md b/docs/services/index.md index cd6a2ab772..92686d19c8 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -75,7 +75,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Amazon MQ](amazonmq.md) | `/v1/brokers/...` + RabbitMQ broker | REST JSON + AMQP | 5 | | [MWAA](mwaa.md) | `/` REST paths for environments + CLI/web proxy | REST JSON | 10 | | [Athena](athena.md) | `POST /` + `X-Amz-Target: AmazonAthena.*` | JSON 1.1 | 27 | -| [Glue](glue.md) | `POST /` + `X-Amz-Target: AWSGlue.*` | JSON 1.1 | 135 | +| [Glue](glue.md) | `POST /` + `X-Amz-Target: AWSGlue.*` | JSON 1.1 | 140 | | [Lake Formation](lakeformation.md) | `POST /` | REST JSON | 16 | | [Neptune](neptune.md) | `POST /` with `Action=` param + Gremlin TCP proxy | Query + WebSocket | 14 | | [DocumentDB](docdb.md) | `POST /` with `Action=` param + MongoDB container | Query + MongoDB wire | 17 | diff --git a/src/main/java/io/floci/aws/services/glue/GlueCatalogService.java b/src/main/java/io/floci/aws/services/glue/GlueCatalogService.java new file mode 100644 index 0000000000..b0f29760cd --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/GlueCatalogService.java @@ -0,0 +1,481 @@ +package io.floci.aws.services.glue; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.PaginatedResult; +import io.floci.aws.core.common.Pagination; +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.storage.RegionScopedStorage; +import io.floci.aws.core.storage.StorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.glue.iceberg.IcebergGlueTables; +import io.floci.aws.services.glue.model.Database; +import io.floci.aws.services.glue.model.GlueCatalog; +import io.floci.aws.services.glue.model.StorageDescriptor; +import io.floci.aws.services.glue.model.Table; +import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService; +import io.floci.aws.services.s3.S3Service; +import io.floci.aws.services.s3tables.S3TablesService; +import io.floci.aws.services.s3tables.model.Namespace; +import io.floci.aws.services.s3tables.model.S3Table; +import io.floci.aws.services.s3tables.model.TableBucket; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.time.Instant; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Pattern; + +/** + * The catalogs of the Glue Data Catalog beside an account's default one ({@code CreateCatalog}, {@code GetCatalog}, + * {@code GetCatalogs}, {@code UpdateCatalog}, {@code DeleteCatalog}), and the catalogs federated from Amazon S3 + * Tables. Integrating table buckets with AWS analytics services creates the federated catalog + * {@code s3tablescatalog} (connection {@code aws:s3tables}); each table bucket of the account is then a child + * catalog, {@code s3tablescatalog/}, whose databases are the bucket's namespaces and whose tables are its + * tables, read from S3 Tables. A catalog id may name the account in front: {@code :s3tablescatalog/}. + */ +@ApplicationScoped +public class GlueCatalogService { + + private static final Logger LOG = Logger.getLogger(GlueCatalogService.class); + + /** The connection that federates a catalog from Amazon S3 Tables. */ + static final String S3_TABLES_CONNECTION = "aws:s3tables"; + private static final Pattern ACCOUNT_ID = Pattern.compile("^\\d{12}$"); + private static final Pattern ACCOUNT_QUALIFIER = Pattern.compile("^\\d{12}:"); + private static final Pattern CATALOG_NAME = Pattern.compile("^(?!(.*[./\\\\]|aws:)).{1,64}$"); + private static final int DEFAULT_PAGE_SIZE = 100; + private static final int MAX_PAGE_SIZE = 1000; + + private final StorageBackend catalogStore; + private final S3TablesService s3Tables; + private final S3Service s3; + private final RegionResolver regionResolver; + private final ResourceGroupsTaggingService tagging; + private final ObjectMapper mapper; + + @Inject + public GlueCatalogService(StorageFactory storageFactory, S3TablesService s3Tables, S3Service s3, + RegionResolver regionResolver, ResourceGroupsTaggingService tagging, + ObjectMapper mapper) { + this(new RegionScopedStorage<>(storageFactory, regionResolver, "glue", "catalogs.json", + new TypeReference<>() {}), s3Tables, s3, regionResolver, tagging, mapper); + } + + GlueCatalogService(StorageBackend catalogStore, S3TablesService s3Tables, S3Service s3, + RegionResolver regionResolver, ResourceGroupsTaggingService tagging, ObjectMapper mapper) { + this.catalogStore = catalogStore; + this.s3Tables = s3Tables; + this.s3 = s3; + this.regionResolver = regionResolver; + this.tagging = tagging; + this.mapper = mapper; + } + + // ─── Catalogs ───────────────────────────────────────────────────────────────── + + public synchronized void createCatalog(String name, JsonNode input, Map tags, String region) { + if (name == null || !CATALOG_NAME.matcher(name).matches()) { + throw invalid("Catalog name must be 1 to 64 characters with no '.', '/' or '\\\\' and must not start " + + "with 'aws:': " + name); + } + if (ACCOUNT_ID.matcher(name).matches() || ACCOUNT_QUALIFIER.matcher(name).lookingAt()) { + // A catalog id names the account this way, so such a name could never be read back. + throw invalid("Catalog name must not be an account id or start with one followed by ':': " + name); + } + requireInput(input); + if (catalogStore.get(name).isPresent()) { + throw new AwsException("AlreadyExistsException", "Catalog already exists: " + name, 400); + } + GlueCatalog catalog = new GlueCatalog(); + catalog.setName(name); + catalog.setCatalogId(qualified(name)); + catalog.setResourceArn(arn(region, name)); + Instant now = Instant.now(); + catalog.setCreateTime(now); + catalog.setUpdateTime(now); + apply(catalog, input, region); + catalogStore.put(name, catalog); + if (tags != null && !tags.isEmpty()) { + try { + tagging.tagResources(List.of(catalog.getResourceArn()), tags, region); + } catch (RuntimeException e) { + catalogStore.delete(name); + throw e; + } + } + LOG.debugv("Created Glue catalog {0}", name); + } + + public GlueCatalog getCatalog(String catalogId, String region) { + CatalogPath path = path(catalogId); + if (path.isDefault()) { + throw notFound(catalogId); + } + GlueCatalog parent = catalogStore.get(path.name()).orElseThrow(() -> notFound(catalogId)); + if (path.child() == null) { + return parent; + } + return bucketCatalog(parent, bucket(parent, path.child(), region).orElseThrow(() -> notFound(catalogId)), + region); + } + + /** + * The catalogs beneath {@code parentCatalogId} (the default catalog when null): the catalogs created in the + * account, or a federated S3 Tables catalog's table buckets; with {@code recursive}, the catalogs beneath those + * too, and with {@code includeRoot} the parent itself first. + */ + public GlueService.Page getCatalogs(String parentCatalogId, boolean recursive, boolean includeRoot, + Integer maxResults, String nextToken, String region) { + List catalogs = new ArrayList<>(); + CatalogPath parent = path(parentCatalogId); + if (parent.isDefault()) { + List created = catalogStore.scan(key -> true).stream() + .sorted(Comparator.comparing(GlueCatalog::getName)).toList(); + for (GlueCatalog catalog : created) { + catalogs.add(catalog); + if (recursive) { + catalogs.addAll(children(catalog, region)); + } + } + } else { + GlueCatalog catalog = getCatalog(parentCatalogId, region); + if (includeRoot) { + catalogs.add(catalog); + } + if (parent.child() == null) { + catalogs.addAll(children(catalog, region)); + } + } + PaginatedResult page = Pagination.paginate(catalogs, GlueCatalog::getCatalogId, maxResults, + nextToken, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, "InvalidInputException", "NextToken"); + return new GlueService.Page<>(page.items(), page.nextToken()); + } + + public synchronized void updateCatalog(String catalogId, JsonNode input, String region) { + requireInput(input); + // Applied to a copy, so a refused input leaves the stored catalog as it was. + GlueCatalog catalog = mapper.convertValue(createdCatalog(catalogId), GlueCatalog.class); + apply(catalog, input, region); + catalog.setUpdateTime(Instant.now()); + catalogStore.put(catalog.getName(), catalog); + } + + public synchronized void deleteCatalog(String catalogId, String region) { + GlueCatalog catalog = createdCatalog(catalogId); + catalogStore.delete(catalog.getName()); + tagging.deleteResources(List.of(catalog.getResourceArn()), region); + } + + // ─── Databases and tables of a federated catalog ──────────────────────────── + + /** + * Whether {@code catalogId} names the account's default catalog: none at all, the account id, or the default + * catalog of the account named in front of nothing else. A catalog that is neither the default nor a table bucket + * of a federated S3 Tables catalog is answered as one that holds no databases. + */ + public boolean isDefaultCatalog(String catalogId) { + return path(catalogId).isDefault(); + } + + public GlueService.Page getDatabases(String catalogId, Integer maxResults, String nextToken, + String region) { + Optional federated = federated(catalogId, region); + List databases = new ArrayList<>(); + federated.ifPresent(found -> s3Tables.listNamespaces(found.bucket().getArn(), null, region).stream() + .sorted(Comparator.comparing(Namespace::getName)) + .forEach(namespace -> databases.add(database(found.catalogId(), namespace)))); + PaginatedResult page = Pagination.paginate(databases, Database::getName, maxResults, nextToken, + DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, "InvalidInputException", "NextToken"); + return new GlueService.Page<>(page.items(), page.nextToken()); + } + + public Database getDatabase(String catalogId, String name, String region) { + Federated federated = requireFederated(catalogId, name, region); + return database(federated.catalogId(), requireNamespace(federated, name, region)); + } + + public GlueService.Page getTables(String catalogId, String databaseName, Integer maxResults, + String nextToken, String region) { + Federated federated = requireFederated(catalogId, databaseName, region); + requireNamespace(federated, databaseName, region); + List s3TableList = s3Tables.listTables(federated.bucket().getArn(), databaseName, null, region) + .stream().sorted(Comparator.comparing(S3Table::getName)).toList(); + // Paged before any metadata file is read, so a page reads only its own tables'. + PaginatedResult page = Pagination.paginate(s3TableList, S3Table::getName, maxResults, nextToken, + DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, "InvalidInputException", "NextToken"); + return new GlueService.Page<>(page.items().stream() + .map(table -> table(federated.catalogId(), databaseName, table)).toList(), page.nextToken()); + } + + public Table getTable(String catalogId, String databaseName, String name, String region) { + Federated federated = requireFederated(catalogId, databaseName, region); + requireNamespace(federated, databaseName, region); + S3Table table; + try { + table = s3Tables.getTable(federated.bucket().getArn(), databaseName, name, region); + } catch (AwsException e) { + throw new AwsException("EntityNotFoundException", "Table " + name + " not found.", 400); + } + return table(federated.catalogId(), databaseName, table); + } + + // ─── Helpers ────────────────────────────────────────────────────────────────── + + /** A catalog id split into the catalog it names and, for a child, the child's name. */ + private record CatalogPath(String name, String child) { + boolean isDefault() { + return name == null; + } + } + + /** + * The catalog {@code catalogId} names: {@code [:][/]}. An account other than the + * caller's names a catalog the caller cannot see here. + */ + private CatalogPath path(String catalogId) { + if (catalogId == null || catalogId.isBlank()) { + return new CatalogPath(null, null); + } + String id = catalogId; + int colon = id.indexOf(':'); + if (colon > 0 && ACCOUNT_ID.matcher(id.substring(0, colon)).matches()) { + if (!id.substring(0, colon).equals(regionResolver.getAccountId())) { + throw notFound(catalogId); + } + id = id.substring(colon + 1); + } + if (id.isEmpty() || id.equals(regionResolver.getAccountId())) { + return new CatalogPath(null, null); + } + int slash = id.indexOf('/'); + return slash < 0 ? new CatalogPath(id, null) : new CatalogPath(id.substring(0, slash), id.substring(slash + 1)); + } + + private GlueCatalog createdCatalog(String catalogId) { + CatalogPath path = path(catalogId); + if (path.isDefault() || path.child() != null) { + throw invalid("Only a catalog created with CreateCatalog can be changed or deleted: " + catalogId); + } + return catalogStore.get(path.name()).orElseThrow(() -> notFound(catalogId)); + } + + private static boolean federatesS3Tables(GlueCatalog catalog) { + return catalog.getFederatedCatalog() != null + && S3_TABLES_CONNECTION.equals(catalog.getFederatedCatalog().get("ConnectionName")); + } + + private List children(GlueCatalog catalog, String region) { + return federatedBuckets(catalog, region).stream() + .sorted(Comparator.comparing(TableBucket::getName)) + .map(bucket -> bucketCatalog(catalog, bucket, region)) + .toList(); + } + + private Optional bucket(GlueCatalog parent, String bucketName, String region) { + return federatedBuckets(parent, region).stream() + .filter(bucket -> bucket.getName().equals(bucketName)) + .findFirst(); + } + + /** + * The table buckets a catalog federates: every bucket of the account in the Region for the identifier + * {@code arn:aws:s3tables:::bucket/*}, or the one bucket its ARN names. + */ + private List federatedBuckets(GlueCatalog catalog, String region) { + if (!federatesS3Tables(catalog)) { + return List.of(); + } + String identifier = String.valueOf(catalog.getFederatedCatalog().get("Identifier")); + return s3Tables.listTableBuckets(null, region).stream() + .filter(bucket -> identifier.endsWith(":bucket/*") + ? bucket.getArn().startsWith(identifier.substring(0, identifier.length() - 1)) + : bucket.getArn().equals(identifier)) + .toList(); + } + + /** + * A federated S3 Tables catalog's identifier: all the account's table buckets in the Region + * ({@code arn:aws:s3tables:::bucket/*}) or one of them, by its ARN. + */ + private void validateS3TablesIdentifier(Map federatedCatalog, String region) { + Object identifier = federatedCatalog.get("Identifier"); + String prefix = AwsArnUtils.Arn.of("s3tables", region, regionResolver.getAccountId(), "bucket/").toString(); + if (!(identifier instanceof String value) || !value.startsWith(prefix) || value.length() == prefix.length() + || (value.endsWith("*") && !value.equals(prefix + "*"))) { + throw invalid("FederatedCatalog.Identifier for the aws:s3tables connection must be " + prefix + + "* or a table bucket ARN of this account and Region: " + identifier); + } + } + + /** A table bucket a federated catalog id names, and the catalog's id as catalogs answer it. */ + private record Federated(TableBucket bucket, String catalogId) { + } + + /** The table bucket a federated catalog id names; empty for the default catalog or any other catalog. */ + private Optional federated(String catalogId, String region) { + CatalogPath path = path(catalogId); + if (path.isDefault() || path.child() == null) { + return Optional.empty(); + } + return catalogStore.get(path.name()).flatMap(parent -> bucket(parent, path.child(), region)) + .map(bucket -> new Federated(bucket, qualified(path.name() + "/" + path.child()))); + } + + private Federated requireFederated(String catalogId, String databaseName, String region) { + return federated(catalogId, region).orElseThrow(() -> new AwsException("EntityNotFoundException", + "Database " + databaseName + " not found.", 400)); + } + + private GlueCatalog bucketCatalog(GlueCatalog parent, TableBucket bucket, String region) { + String path = parent.getName() + "/" + bucket.getName(); + GlueCatalog catalog = new GlueCatalog(); + catalog.setName(bucket.getName()); + catalog.setCatalogId(qualified(path)); + catalog.setResourceArn(arn(region, path)); + catalog.setFederatedCatalog(Map.of("Identifier", bucket.getArn(), + "ConnectionName", S3_TABLES_CONNECTION)); + catalog.setCreateTime(instant(bucket.getCreatedAt())); + catalog.setUpdateTime(instant(bucket.getCreatedAt())); + return catalog; + } + + private Namespace requireNamespace(Federated federated, String name, String region) { + try { + return s3Tables.getNamespace(federated.bucket().getArn(), name, region); + } catch (AwsException e) { + throw new AwsException("EntityNotFoundException", "Database " + name + " not found.", 400); + } + } + + private static Database database(String catalogId, Namespace namespace) { + Database database = new Database(namespace.getName()); + database.setCatalogId(catalogId); + database.setCreateTime(instant(namespace.getCreatedAt())); + return database; + } + + /** + * An S3 table as Glue shows it: an Iceberg table whose {@code metadata_location} and columns come from its current + * metadata file, or a table with only its location while S3 Tables holds no metadata for it yet. + */ + private Table table(String catalogId, String databaseName, S3Table s3Table) { + String metadataLocation = s3Table.getMetadataLocation(); + Table table = null; + if (metadataLocation != null && !metadataLocation.isBlank()) { + try { + table = IcebergGlueTables.glueTable(s3Table.getName(), + IcebergGlueTables.readMetadata(s3, mapper, metadataLocation), metadataLocation); + } catch (IOException | RuntimeException e) { + // One unreadable metadata file should not fail a whole listing: the table keeps its location. + LOG.warnv("Cannot read metadata {0} of S3 table {1}; its columns are left out: {2}", + metadataLocation, s3Table.getName(), e.getMessage()); + } + } + if (table == null) { + table = new Table(); + table.setName(s3Table.getName()); + table.setTableType("EXTERNAL_TABLE"); + Map parameters = new HashMap<>(Map.of("table_type", "ICEBERG")); + if (metadataLocation != null && !metadataLocation.isBlank()) { + parameters.put("metadata_location", metadataLocation); + } + table.setParameters(parameters); + StorageDescriptor descriptor = new StorageDescriptor(); + descriptor.setLocation(s3Table.getWarehouseLocation()); + table.setStorageDescriptor(descriptor); + } + table.setDatabaseName(databaseName); + table.setCatalogId(catalogId); + table.setCreateTime(instant(s3Table.getCreatedAt())); + table.setUpdateTime(instant(s3Table.getModifiedAt())); + return table; + } + + private static void requireInput(JsonNode input) { + if (input == null || input.isNull() || !input.isObject()) { + throw invalid("CatalogInput is required."); + } + } + + /** Applies a {@code CatalogInput}, after checking all of it, so a refused one changes nothing. */ + private void apply(GlueCatalog catalog, JsonNode input, String region) { + String allowFullTableExternalDataAccess = null; + if (input.has("AllowFullTableExternalDataAccess")) { + allowFullTableExternalDataAccess = input.get("AllowFullTableExternalDataAccess").asText(); + if (!allowFullTableExternalDataAccess.equals("True") && !allowFullTableExternalDataAccess.equals("False")) { + throw invalid("AllowFullTableExternalDataAccess must be True or False: " + + allowFullTableExternalDataAccess); + } + } + Map federatedCatalog = input.has("FederatedCatalog") + ? mapper.convertValue(input.get("FederatedCatalog"), new TypeReference<>() {}) + : catalog.getFederatedCatalog(); + if (federatedCatalog != null && S3_TABLES_CONNECTION.equals(federatedCatalog.get("ConnectionName"))) { + validateS3TablesIdentifier(federatedCatalog, region); + } + if (allowFullTableExternalDataAccess != null) { + catalog.setAllowFullTableExternalDataAccess(allowFullTableExternalDataAccess); + } + if (input.has("Description")) { + catalog.setDescription(input.get("Description").asText(null)); + } + if (input.has("Parameters")) { + catalog.setParameters(mapper.convertValue(input.get("Parameters"), new TypeReference<>() {})); + } + catalog.setFederatedCatalog(federatedCatalog); + if (input.has("TargetRedshiftCatalog")) { + catalog.setTargetRedshiftCatalog(mapper.convertValue(input.get("TargetRedshiftCatalog"), + new TypeReference<>() {})); + } + if (input.has("CatalogProperties")) { + catalog.setCatalogProperties(mapper.convertValue(input.get("CatalogProperties"), new TypeReference<>() {})); + } + if (input.has("CreateTableDefaultPermissions")) { + catalog.setCreateTableDefaultPermissions(mapper.convertValue(input.get("CreateTableDefaultPermissions"), + new TypeReference<>() {})); + } + if (input.has("CreateDatabaseDefaultPermissions")) { + catalog.setCreateDatabaseDefaultPermissions(mapper.convertValue( + input.get("CreateDatabaseDefaultPermissions"), new TypeReference<>() {})); + } + } + + private String qualified(String path) { + return regionResolver.getAccountId() + ":" + path; + } + + private String arn(String region, String path) { + return AwsArnUtils.Arn.of("glue", region, regionResolver.getAccountId(), "catalog/" + path).toString(); + } + + private static Instant instant(String timestamp) { + if (timestamp == null || timestamp.isBlank()) { + return null; + } + try { + return Instant.parse(timestamp); + } catch (DateTimeParseException e) { + return null; + } + } + + private static AwsException notFound(String catalogId) { + return new AwsException("EntityNotFoundException", "Catalog not found: " + catalogId, 400); + } + + private static AwsException invalid(String message) { + return new AwsException("InvalidInputException", message, 400); + } +} diff --git a/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java b/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java index f323c7dafa..b96c51f601 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java +++ b/src/main/java/io/floci/aws/services/glue/GlueJsonHandler.java @@ -47,6 +47,7 @@ public class GlueJsonHandler { private final GlueCrawlerRunService crawlerRunService; private final GlueTriggerService triggerService; private final GlueSchemaRegistryService schemaRegistryService; + private final GlueCatalogService catalogService; private final ObjectMapper mapper; @Inject @@ -55,12 +56,14 @@ public class GlueJsonHandler { GlueCrawlerRunService crawlerRunService, GlueTriggerService triggerService, GlueSchemaRegistryService schemaRegistryService, + GlueCatalogService catalogService, ObjectMapper mapper) { this.glueService = glueService; this.jobRunService = jobRunService; this.crawlerRunService = crawlerRunService; this.triggerService = triggerService; this.schemaRegistryService = schemaRegistryService; + this.catalogService = catalogService; this.mapper = mapper; } @@ -86,12 +89,39 @@ public class GlueJsonHandler { glueService.createDatabase(db, tags, region); yield Response.ok().build(); } + case "CreateCatalog" -> { + catalogService.createCatalog(request.path("Name").asText(null), request.get("CatalogInput"), + request.has("Tags") ? mapper.convertValue(request.get("Tags"), STRING_MAP) : null, region); + yield Response.ok(Map.of()).build(); + } + case "GetCatalog" -> Response.ok(Map.of("Catalog", + catalogService.getCatalog(request.path("CatalogId").asText(null), region))).build(); + case "GetCatalogs" -> { + GlueService.Page page = catalogService.getCatalogs( + request.path("ParentCatalogId").asText(null), request.path("Recursive").asBoolean(false), + request.path("IncludeRoot").asBoolean(false), + Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException"), + Pagination.parseNextToken(request, "NextToken", "InvalidInputException"), region); + yield Response.ok(pageResponse("CatalogList", page.items(), page.nextToken())).build(); + } + case "UpdateCatalog" -> { + catalogService.updateCatalog(request.path("CatalogId").asText(null), request.get("CatalogInput"), + region); + yield Response.ok(Map.of()).build(); + } + case "DeleteCatalog" -> { + catalogService.deleteCatalog(request.path("CatalogId").asText(null), region); + yield Response.ok(Map.of()).build(); + } case "GetDatabase" -> { String name = request.get("Name").asText(); - Database db = glueService.getDatabase(name); + String catalogId = request.path("CatalogId").asText(null); + Database db = catalogService.isDefaultCatalog(catalogId) + ? glueService.getDatabase(name) + : catalogService.getDatabase(catalogId, name, region); yield Response.ok(Map.of("Database", db)).build(); } - case "GetDatabases" -> handleGetDatabases(request); + case "GetDatabases" -> handleGetDatabases(request, region); case "DeleteDatabase" -> { String name = request.get("Name").asText(); glueService.deleteDatabase(name, region); @@ -112,7 +142,10 @@ public class GlueJsonHandler { case "GetTable" -> { String dbName = request.get("DatabaseName").asText(); String tableName = request.get("Name").asText(); - Table table = glueService.getTable(dbName, tableName); + String catalogId = request.path("CatalogId").asText(null); + Table table = catalogService.isDefaultCatalog(catalogId) + ? glueService.getTable(dbName, tableName) + : catalogService.getTable(catalogId, dbName, tableName, region); yield Response.ok(Map.of("Table", GlueService.withReadDefaults(table))).build(); } case "CreatePartitionIndex" -> { @@ -143,8 +176,10 @@ public class GlueJsonHandler { Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException"); String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException"); String dbName = request.get("DatabaseName").asText(); - GlueService.Page
page = glueService.getTables( - dbName, maxResults, nextToken); + String catalogId = request.path("CatalogId").asText(null); + GlueService.Page
page = catalogService.isDefaultCatalog(catalogId) + ? glueService.getTables(dbName, maxResults, nextToken) + : catalogService.getTables(catalogId, dbName, maxResults, nextToken, region); List
tables = page.items().stream().map(GlueService::withReadDefaults).toList(); yield Response.ok(pageResponse("TableList", tables, page.nextToken())).build(); } @@ -1112,10 +1147,13 @@ public class GlueJsonHandler { return vn.asLong(); } - private Response handleGetDatabases(JsonNode request) { - GlueService.Page page = glueService.getDatabases( - Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException"), - Pagination.parseNextToken(request, "NextToken", "InvalidInputException")); + private Response handleGetDatabases(JsonNode request, String region) { + Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException"); + String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException"); + String catalogId = request.path("CatalogId").asText(null); + GlueService.Page page = catalogService.isDefaultCatalog(catalogId) + ? glueService.getDatabases(maxResults, nextToken) + : catalogService.getDatabases(catalogId, maxResults, nextToken, region); return Response.ok(pageResponse("DatabaseList", page.items(), page.nextToken())).build(); } diff --git a/src/main/java/io/floci/aws/services/glue/GlueService.java b/src/main/java/io/floci/aws/services/glue/GlueService.java index be726d7957..b93e38da43 100644 --- a/src/main/java/io/floci/aws/services/glue/GlueService.java +++ b/src/main/java/io/floci/aws/services/glue/GlueService.java @@ -1805,6 +1805,7 @@ public class GlueService { Table copy = new Table(); copy.setName(source.getName()); copy.setDatabaseName(source.getDatabaseName()); + copy.setCatalogId(source.getCatalogId()); copy.setDescription(source.getDescription()); copy.setOwner(source.getOwner()); copy.setCreateTime(source.getCreateTime()); 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 index 8b7ba58184..421c8111f7 100644 --- a/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalog.java +++ b/src/main/java/io/floci/aws/services/glue/iceberg/GlueIcebergCatalog.java @@ -8,9 +8,7 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; 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; @@ -18,7 +16,6 @@ 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; @@ -47,11 +44,10 @@ 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_TABLE_TYPE = IcebergGlueTables.PARAM_TABLE_TYPE; + private static final String PARAM_METADATA_LOCATION = IcebergGlueTables.PARAM_METADATA_LOCATION; private static final String PARAM_PREVIOUS_METADATA_LOCATION = "previous_metadata_location"; - private static final String ICEBERG = "ICEBERG"; - private static final Pattern S3_LOCATION = Pattern.compile("^s3[an]?://([^/]+)/?(.*)$"); + private static final String ICEBERG = IcebergGlueTables.ICEBERG; 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( @@ -453,43 +449,24 @@ public class GlueIcebergCatalog { * {@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<>(); + Table table = IcebergGlueTables.glueTable(name, metadata, metadataLocation); if (existing != null) { table.setDescription(existing.getDescription()); table.setOwner(existing.getOwner()); if (existing.getParameters() != null) { - parameters.putAll(existing.getParameters()); + Map parameters = new HashMap<>(existing.getParameters()); + parameters.putAll(table.getParameters()); + table.setParameters(parameters); } } - 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); + try { + return (ObjectNode) IcebergGlueTables.readMetadata(s3, mapper, metadataLocation); + } catch (IllegalArgumentException e) { + throw IcebergRestException.badRequest(e.getMessage()); } catch (AwsException e) { throw IcebergRestException.badRequest("Cannot read table metadata " + metadataLocation + ": " + e.getMessage()); @@ -503,7 +480,7 @@ public class GlueIcebergCatalog { 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); + IcebergGlueTables.S3Location location = s3Location(metadataLocation); try { s3.putObject(location.bucket(), location.key(), mapper.writeValueAsString(metadata).getBytes(StandardCharsets.UTF_8), "application/json", null); @@ -519,7 +496,7 @@ public class GlueIcebergCatalog { /** 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); + IcebergGlueTables.S3Location location = s3Location(metadataLocation); try { s3.deleteObject(location.bucket(), location.key()); } catch (RuntimeException e) { @@ -546,12 +523,12 @@ public class GlueIcebergCatalog { 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); + private static IcebergGlueTables.S3Location s3Location(String location) { + try { + return IcebergGlueTables.s3Location(location); + } catch (IllegalArgumentException e) { + throw IcebergRestException.badRequest(e.getMessage()); } - return new S3Location(matcher.group(1), matcher.group(2)); } private static IcebergRestException translated(AwsException e, String database, String table) { @@ -562,7 +539,4 @@ public class GlueIcebergCatalog { default -> IcebergRestException.badRequest(e.getMessage()); }; } - - private record S3Location(String bucket, String key) { - } } diff --git a/src/main/java/io/floci/aws/services/glue/iceberg/IcebergGlueTables.java b/src/main/java/io/floci/aws/services/glue/iceberg/IcebergGlueTables.java new file mode 100644 index 0000000000..831b3fcba2 --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/iceberg/IcebergGlueTables.java @@ -0,0 +1,85 @@ +package io.floci.aws.services.glue.iceberg; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.glue.model.Column; +import io.floci.aws.services.glue.model.StorageDescriptor; +import io.floci.aws.services.glue.model.Table; +import io.floci.aws.services.s3.S3Service; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** The Glue table AWS Glue shows for an Iceberg table, built from the table's metadata file. */ +public final class IcebergGlueTables { + + static final String PARAM_TABLE_TYPE = "table_type"; + static final String PARAM_METADATA_LOCATION = "metadata_location"; + static final String ICEBERG = "ICEBERG"; + private static final Pattern S3_LOCATION = Pattern.compile("^s3[an]?://([^/]+)/?(.*)$"); + + private IcebergGlueTables() { + } + + /** + * 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, with their Hive types and Iceberg field ids, in its storage + * descriptor, as AWS Glue keeps one. + */ + public static Table glueTable(String name, JsonNode metadata, String metadataLocation) { + Table table = new Table(); + table.setName(name); + table.setTableType("EXTERNAL_TABLE"); + Map parameters = new HashMap<>(); + 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; + } + + /** + * Reads the metadata file at {@code metadataLocation}, an {@code s3://} object. + * + * @throws IllegalArgumentException when the location is not an S3 object + */ + public static JsonNode readMetadata(S3Service s3, ObjectMapper mapper, String metadataLocation) throws IOException { + S3Location location = s3Location(metadataLocation); + try (InputStream stream = s3.openObjectStream(location.bucket(), location.key(), null)) { + return mapper.readTree(stream); + } + } + + /** The bucket and key an {@code s3://} (or {@code s3a://}, {@code s3n://}) object location names. */ + static S3Location s3Location(String location) { + Matcher matcher = S3_LOCATION.matcher(location == null ? "" : location); + if (!matcher.matches() || matcher.group(2).isEmpty()) { + throw new IllegalArgumentException("Not an S3 object location: " + location); + } + return new S3Location(matcher.group(1), matcher.group(2)); + } + + record S3Location(String bucket, String key) { + } +} diff --git a/src/main/java/io/floci/aws/services/glue/model/GlueCatalog.java b/src/main/java/io/floci/aws/services/glue/model/GlueCatalog.java new file mode 100644 index 0000000000..4a1868d491 --- /dev/null +++ b/src/main/java/io/floci/aws/services/glue/model/GlueCatalog.java @@ -0,0 +1,79 @@ +package io.floci.aws.services.glue.model; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +/** A Glue Data Catalog catalog ({@code Catalog}): a federated catalog such as {@code s3tablescatalog}, or one of its children. */ +@RegisterForReflection +@JsonInclude(JsonInclude.Include.NON_NULL) +public class GlueCatalog { + @JsonProperty("CatalogId") + private String catalogId; + @JsonProperty("Name") + private String name; + @JsonProperty("ResourceArn") + private String resourceArn; + @JsonProperty("Description") + private String description; + @JsonProperty("Parameters") + private Map parameters; + @JsonProperty("CreateTime") + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant createTime; + @JsonProperty("UpdateTime") + @JsonFormat(shape = JsonFormat.Shape.NUMBER) + private Instant updateTime; + @JsonProperty("TargetRedshiftCatalog") + private Map targetRedshiftCatalog; + @JsonProperty("FederatedCatalog") + private Map federatedCatalog; + @JsonProperty("CatalogProperties") + private Map catalogProperties; + @JsonProperty("CreateTableDefaultPermissions") + private List> createTableDefaultPermissions; + @JsonProperty("CreateDatabaseDefaultPermissions") + private List> createDatabaseDefaultPermissions; + @JsonProperty("AllowFullTableExternalDataAccess") + private String allowFullTableExternalDataAccess; + + public GlueCatalog() {} + + public String getCatalogId() { return catalogId; } + public void setCatalogId(String catalogId) { this.catalogId = catalogId; } + public String getName() { return name; } + public void setName(String name) { this.name = name; } + public String getResourceArn() { return resourceArn; } + public void setResourceArn(String resourceArn) { this.resourceArn = resourceArn; } + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + public Map getParameters() { return parameters; } + public void setParameters(Map parameters) { this.parameters = parameters; } + public Instant getCreateTime() { return createTime; } + public void setCreateTime(Instant createTime) { this.createTime = createTime; } + public Instant getUpdateTime() { return updateTime; } + public void setUpdateTime(Instant updateTime) { this.updateTime = updateTime; } + public Map getTargetRedshiftCatalog() { return targetRedshiftCatalog; } + public void setTargetRedshiftCatalog(Map targetRedshiftCatalog) { + this.targetRedshiftCatalog = targetRedshiftCatalog; + } + public Map getFederatedCatalog() { return federatedCatalog; } + public void setFederatedCatalog(Map federatedCatalog) { this.federatedCatalog = federatedCatalog; } + public Map getCatalogProperties() { return catalogProperties; } + public void setCatalogProperties(Map catalogProperties) { this.catalogProperties = catalogProperties; } + public List> getCreateTableDefaultPermissions() { return createTableDefaultPermissions; } + public void setCreateTableDefaultPermissions(List> permissions) { + this.createTableDefaultPermissions = permissions; + } + public List> getCreateDatabaseDefaultPermissions() { return createDatabaseDefaultPermissions; } + public void setCreateDatabaseDefaultPermissions(List> permissions) { + this.createDatabaseDefaultPermissions = permissions; + } + public String getAllowFullTableExternalDataAccess() { return allowFullTableExternalDataAccess; } + public void setAllowFullTableExternalDataAccess(String value) { this.allowFullTableExternalDataAccess = value; } +} diff --git a/src/main/java/io/floci/aws/services/glue/model/Table.java b/src/main/java/io/floci/aws/services/glue/model/Table.java index 384d2a38ec..c959f55ebc 100644 --- a/src/main/java/io/floci/aws/services/glue/model/Table.java +++ b/src/main/java/io/floci/aws/services/glue/model/Table.java @@ -1,6 +1,7 @@ package io.floci.aws.services.glue.model; import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.runtime.annotations.RegisterForReflection; @@ -14,6 +15,9 @@ public class Table { private String name; @JsonProperty("DatabaseName") private String databaseName; + @JsonProperty("CatalogId") + @JsonInclude(JsonInclude.Include.NON_NULL) + private String catalogId; @JsonProperty("Description") private String description; @JsonProperty("Owner") @@ -52,6 +56,8 @@ public class Table { public void setName(String name) { this.name = name; } public String getDatabaseName() { return databaseName; } public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } + public String getCatalogId() { return catalogId; } + public void setCatalogId(String catalogId) { this.catalogId = catalogId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getOwner() { return owner; } diff --git a/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerEmptyListTest.java b/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerEmptyListTest.java index 5dffd38a48..058261469d 100644 --- a/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerEmptyListTest.java +++ b/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerEmptyListTest.java @@ -51,7 +51,8 @@ class GlueJsonHandlerEmptyListTest { handler = new GlueJsonHandler(glueService, jobRunService, crawlerRunService, new GlueTriggerService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), glueService, jobRunService, crawlerRunService), - schemaRegistryService, mapper); + schemaRegistryService, new GlueCatalogService(new InMemoryStorage<>(), null, null, + new RegionResolver("us-east-1", "000000000000"), null, mapper), mapper); } @Test diff --git a/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerTest.java b/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerTest.java index 9b6010633c..32daf3cb54 100644 --- a/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerTest.java +++ b/src/test/java/io/floci/aws/services/glue/GlueJsonHandlerTest.java @@ -55,7 +55,8 @@ class GlueJsonHandlerTest { handler = new GlueJsonHandler(glueService, jobRunService, crawlerRunService, new GlueTriggerService(new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), glueService, jobRunService, crawlerRunService), - schemaRegistryService, mapper); + schemaRegistryService, new GlueCatalogService(new InMemoryStorage<>(), null, null, + new RegionResolver("us-east-1", "000000000000"), null, mapper), mapper); } @Test diff --git a/src/test/java/io/floci/aws/services/glue/GlueS3TablesCatalogIntegrationTest.java b/src/test/java/io/floci/aws/services/glue/GlueS3TablesCatalogIntegrationTest.java new file mode 100644 index 0000000000..fff16c529e --- /dev/null +++ b/src/test/java/io/floci/aws/services/glue/GlueS3TablesCatalogIntegrationTest.java @@ -0,0 +1,230 @@ +package io.floci.aws.services.glue; + +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService; +import io.floci.aws.services.s3.S3Service; +import io.floci.aws.services.s3tables.S3TablesService; +import io.floci.aws.services.s3tables.model.S3Table; +import io.floci.aws.services.s3tables.model.TableBucket; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +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; + +/** + * Amazon S3 Tables federated into the Glue Data Catalog: once the account creates the {@code s3tablescatalog} + * catalog on the {@code aws:s3tables} connection, each table bucket is a child catalog whose databases are its + * namespaces and whose tables are its tables, Iceberg tables with their current metadata location and columns. + */ +@QuarkusTest +class GlueS3TablesCatalogIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + private static final String ACCOUNT = "000000000000"; + private static final String REGION = "us-east-1"; + private static final String METADATA = """ + {"format-version":2,"table-uuid":"11111111-2222-3333-4444-555555555555","location":"%s", + "last-sequence-number":0,"last-updated-ms":1,"last-column-id":2,"current-schema-id":0, + "schemas":[{"type":"struct","schema-id":0,"fields":[ + {"id":1,"name":"id","required":true,"type":"long"}, + {"id":2,"name":"name","required":false,"type":"string","doc":"who"}]}], + "default-spec-id":0,"partition-specs":[{"spec-id":0,"fields":[]}],"last-partition-id":999, + "default-sort-order-id":0,"sort-orders":[{"order-id":0,"fields":[]}],"properties":{}, + "current-snapshot-id":-1,"snapshots":[],"snapshot-log":[],"metadata-log":[]}"""; + + @Inject + S3TablesService s3Tables; + + @Inject + S3Service s3; + + @Inject + ResourceGroupsTaggingService tagging; + + private TableBucket bucket; + private String metadataLocation; + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void createTableBucket() { + String name = "lake-" + System.nanoTime(); + RequestScopes.runAs(ACCOUNT, REGION, () -> { + bucket = s3Tables.createTableBucket(name, null, null, Map.of(), REGION); + s3Tables.createNamespace(bucket.getArn(), List.of("sales"), REGION); + S3Table table = s3Tables.createTable(bucket.getArn(), "sales", "orders", "ICEBERG", null, null, null, + Map.of(), REGION); + String warehouse = table.getWarehouseLocation().replaceAll("/$", ""); + metadataLocation = warehouse + "/metadata/00000-a.metadata.json"; + String warehouseBucket = warehouse.substring("s3://".length()).split("/", 2)[0]; + String keyPrefix = warehouse.substring(("s3://" + warehouseBucket).length()).replaceAll("^/", ""); + s3.putObject(warehouseBucket, (keyPrefix.isEmpty() ? "" : keyPrefix + "/") + "metadata/00000-a.metadata.json", + METADATA.formatted(warehouse).getBytes(StandardCharsets.UTF_8), "application/json", null); + s3Tables.updateTableMetadataLocation(bucket.getArn(), "sales", "orders", metadataLocation, + table.getVersionToken(), REGION); + }); + } + + @AfterEach + void deleteCatalogAndBucket() { + glue("DeleteCatalog", "{\"CatalogId\":\"s3tablescatalog\"}"); + RequestScopes.runAs(ACCOUNT, REGION, () -> { + s3Tables.deleteTable(bucket.getArn(), "sales", "orders", REGION); + s3Tables.deleteNamespace(bucket.getArn(), "sales", REGION); + s3Tables.deleteTableBucket(bucket.getArn(), REGION); + }); + } + + private ValidatableResponse glue(String action, String body) { + return given().contentType(CONTENT_TYPE).header("X-Amz-Target", "AWSGlue." + action).body(body) + .post("/").then(); + } + + private void integrate() { + glue("CreateCatalog", """ + {"Name":"s3tablescatalog","CatalogInput":{"FederatedCatalog":{ + "Identifier":"arn:aws:s3tables:us-east-1:000000000000:bucket/*","ConnectionName":"aws:s3tables"}, + "AllowFullTableExternalDataAccess":"True"}}""").statusCode(200); + } + + @Test + void eachTableBucketIsAChildCatalogOfTheFederatedS3TablesCatalog() { + String child = "000000000000:s3tablescatalog/" + bucket.getName(); + glue("GetCatalog", "{\"CatalogId\":\"s3tablescatalog/" + bucket.getName() + "\"}").statusCode(400) + .body("__type", equalTo("EntityNotFoundException")); + + integrate(); + + glue("GetCatalog", "{\"CatalogId\":\"s3tablescatalog\"}").statusCode(200) + .body("Catalog.Name", equalTo("s3tablescatalog")) + .body("Catalog.FederatedCatalog.ConnectionName", equalTo("aws:s3tables")) + .body("Catalog.AllowFullTableExternalDataAccess", equalTo("True")); + glue("GetCatalogs", "{\"ParentCatalogId\":\"s3tablescatalog\"}").statusCode(200) + .body("CatalogList.CatalogId", hasItem(child)); + glue("GetCatalog", "{\"CatalogId\":\"" + child + "\"}").statusCode(200) + .body("Catalog.Name", equalTo(bucket.getName())) + .body("Catalog.ResourceArn", equalTo("arn:aws:glue:us-east-1:000000000000:catalog/s3tablescatalog/" + + bucket.getName())) + .body("Catalog.FederatedCatalog.Identifier", equalTo(bucket.getArn())); + glue("GetCatalog", "{\"CatalogId\":\"111122223333:s3tablescatalog/" + bucket.getName() + "\"}") + .statusCode(400).body("__type", equalTo("EntityNotFoundException")); + glue("GetCatalog", "{\"CatalogId\":\"s3tablescatalog/no-such-bucket\"}").statusCode(400) + .body("__type", equalTo("EntityNotFoundException")); + } + + @Test + void aTableBucketsNamespacesAndTablesAreItsCatalogsDatabasesAndIcebergTables() { + integrate(); + String catalogId = "s3tablescatalog/" + bucket.getName(); + + String qualified = ACCOUNT + ":" + catalogId; + glue("GetDatabases", "{\"CatalogId\":\"" + catalogId + "\"}").statusCode(200) + .body("DatabaseList.Name", equalTo(List.of("sales"))) + .body("DatabaseList[0].CatalogId", equalTo(qualified)); + glue("GetDatabase", "{\"CatalogId\":\"" + catalogId + "\",\"Name\":\"sales\"}").statusCode(200) + .body("Database.Name", equalTo("sales")); + glue("GetTables", "{\"CatalogId\":\"" + catalogId + "\",\"DatabaseName\":\"sales\"}").statusCode(200) + .body("TableList.Name", equalTo(List.of("orders"))); + glue("GetTable", "{\"CatalogId\":\"" + catalogId + "\",\"DatabaseName\":\"sales\",\"Name\":\"orders\"}") + .statusCode(200) + .body("Table.CatalogId", equalTo(qualified)) + .body("Table.DatabaseName", equalTo("sales")) + .body("Table.Parameters.table_type", equalTo("ICEBERG")) + .body("Table.Parameters.metadata_location", equalTo(metadataLocation)) + .body("Table.StorageDescriptor.Columns.Name", equalTo(List.of("id", "name"))) + .body("Table.StorageDescriptor.Columns.Type", equalTo(List.of("bigint", "string"))) + .body("Table.StorageDescriptor.Columns[1].Comment", equalTo("who")); + glue("GetTable", "{\"CatalogId\":\"" + catalogId + "\",\"DatabaseName\":\"sales\",\"Name\":\"missing\"}") + .statusCode(400).body("__type", equalTo("EntityNotFoundException")); + glue("GetDatabases", "{}").statusCode(200).body("DatabaseList.Name", not(hasItem("sales"))); + glue("GetDatabases", "{\"CatalogId\":\"" + ACCOUNT + "\"}").statusCode(200) + .body("DatabaseList.Name", not(hasItem("sales"))); + } + + @Test + void aTableWithoutMetadataYetKeepsItsWarehouseLocation() { + integrate(); + S3Table fresh = RequestScopes.callAs(ACCOUNT, REGION, () -> s3Tables.createTable(bucket.getArn(), "sales", + "fresh", "ICEBERG", null, null, null, Map.of(), REGION)); + try { + glue("GetTable", "{\"CatalogId\":\"s3tablescatalog/" + bucket.getName() + + "\",\"DatabaseName\":\"sales\",\"Name\":\"fresh\"}").statusCode(200) + .body("Table.StorageDescriptor.Location", equalTo(fresh.getWarehouseLocation())) + .body("Table.Parameters.table_type", equalTo("ICEBERG")) + .body("Table.Parameters.metadata_location", nullValue()); + } finally { + RequestScopes.runAs(ACCOUNT, REGION, () -> s3Tables.deleteTable(bucket.getArn(), "sales", "fresh", REGION)); + } + } + + @Test + void aFederationIdentifierNamingOneBucketFederatesOnlyThatBucket() { + glue("CreateCatalog", "{\"Name\":\"s3tablescatalog\",\"CatalogInput\":{\"FederatedCatalog\":{" + + "\"Identifier\":\"" + bucket.getArn() + "\",\"ConnectionName\":\"aws:s3tables\"}}}") + .statusCode(200); + glue("GetCatalogs", "{\"ParentCatalogId\":\"s3tablescatalog\"}").statusCode(200) + .body("CatalogList.Name", equalTo(List.of(bucket.getName()))); + glue("UpdateCatalog", "{\"CatalogId\":\"s3tablescatalog\",\"CatalogInput\":{\"FederatedCatalog\":{" + + "\"Identifier\":\"arn:aws:s3tables:eu-west-1:000000000000:bucket/*\"," + + "\"ConnectionName\":\"aws:s3tables\"}}}").statusCode(400) + .body("__type", equalTo("InvalidInputException")); + } + + @Test + void aRefusedInputChangesNothingAndADeletedCatalogTakesItsTagsAlong() { + glue("CreateCatalog", "{\"Name\":\"s3tablescatalog\",\"CatalogInput\":{\"Description\":\"first\"," + + "\"FederatedCatalog\":{\"Identifier\":\"arn:aws:s3tables:us-east-1:000000000000:bucket/*\"," + + "\"ConnectionName\":\"aws:s3tables\"}},\"Tags\":{\"team\":\"data\"}}").statusCode(200); + glue("UpdateCatalog", "{\"CatalogId\":\"s3tablescatalog\",\"CatalogInput\":{\"Description\":\"second\"," + + "\"AllowFullTableExternalDataAccess\":\"Maybe\"}}").statusCode(400) + .body("__type", equalTo("InvalidInputException")); + glue("GetCatalog", "{\"CatalogId\":\"s3tablescatalog\"}").statusCode(200) + .body("Catalog.Description", equalTo("first")); + glue("UpdateCatalog", "{\"CatalogId\":\"s3tablescatalog\"}").statusCode(400) + .body("__type", equalTo("InvalidInputException")); + String arn = "arn:aws:glue:us-east-1:000000000000:catalog/s3tablescatalog"; + assertEquals(Map.of("team", "data"), tagging.getTagsForResource(REGION, arn)); + + glue("DeleteCatalog", "{\"CatalogId\":\"s3tablescatalog\"}").statusCode(200); + + assertTrue(tagging.getTagsForResource(REGION, arn).isEmpty()); + } + + @Test + void aCatalogIsCreatedOnceAndOnlyACreatedCatalogIsChangedOrDeleted() { + integrate(); + glue("CreateCatalog", "{\"Name\":\"s3tablescatalog\",\"CatalogInput\":{}}").statusCode(400) + .body("__type", equalTo("AlreadyExistsException")); + for (String badName : List.of("bad/name", "000000000000", "111122223333:other")) { + glue("CreateCatalog", "{\"Name\":\"" + badName + "\",\"CatalogInput\":{}}").statusCode(400) + .body("__type", equalTo("InvalidInputException")); + } + glue("CreateCatalog", "{\"Name\":\"no-input\"}").statusCode(400) + .body("__type", equalTo("InvalidInputException")); + glue("UpdateCatalog", "{\"CatalogId\":\"s3tablescatalog\",\"CatalogInput\":{\"Description\":\"tables\"}}") + .statusCode(200); + glue("GetCatalog", "{\"CatalogId\":\"s3tablescatalog\"}").statusCode(200) + .body("Catalog.Description", equalTo("tables")); + glue("DeleteCatalog", "{\"CatalogId\":\"s3tablescatalog/" + bucket.getName() + "\"}").statusCode(400) + .body("__type", equalTo("InvalidInputException")); + } +}