diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index 9837ce1323..8bbdd9960d 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -133,7 +133,9 @@ AWS runtime for Apache Spark releases, `emr-spark-8.0.0` on), and runs which replace the application's whole `spark-defaults` classification. From `emr-spark-8.1.0` the two are merged by property instead, the run's winning. `s3://` and `s3a://` paths reach Floci's S3 through S3A, on releases before 7.10.0 too, where `s3://` would otherwise be EMRFS; the entry point and its files can be read from there. - The Glue Data Catalog client is pointed at Floci's Glue. + The Glue Data Catalog client is pointed at Floci's Glue, with the run's account as its + `hive.metastore.glue.catalogid` (from `emr-7.10.0` the client would otherwise ask STS for it), which a + `spark.hadoop.hive.metastore.glue.catalogid` in the `spark-defaults` replaces. * **Driver environment and archives**: a `spark.emr-serverless.driverEnv.` property, from the `spark-defaults` above or a `--conf` in `sparkSubmitParameters`, which wins, is an environment variable of the container, replacing one of Floci's own of that name, such as the user guide's `JAVA_HOME` for diff --git a/docs/services/emr.md b/docs/services/emr.md index d97c54f270..1b4cff97b3 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -279,7 +279,9 @@ but for its bootstrap actions and its storage. applies; a `spark-hive-site` setting wins over the same one in `core-site`, and a `spark.hadoop.` setting in `spark-defaults` over both. `s3://` and `s3a://` paths reach Floci's S3 through S3A, on releases before 7.10.0 too, where `s3://` would otherwise be EMRFS, so the application and its files can be read - from there; the Glue Data Catalog client is pointed at Floci's Glue, and `hdfs://` paths, and those + from there; the Glue Data Catalog client is pointed at Floci's Glue, with the cluster's account as its + `hive.metastore.glue.catalogid` (from `emr-7.10.0` the client would otherwise ask STS for it), which a + `spark-hive-site` one replaces for a Data Catalog in another account; and `hdfs://` paths, and those without a scheme, at the cluster's HDFS. The cluster's `spark-log4j2` properties, which "Change values in Spark's log4j2.properties file", follow the `log4j2.properties` of the folder a `spark-env` export of `SPARK_CONF_DIR` names, else of the image's, in a copy of the step's own, a later key winning, so diff --git a/docs/services/glue.md b/docs/services/glue.md index d83e82c830..46c71bd3c1 100644 --- a/docs/services/glue.md +++ b/docs/services/glue.md @@ -9,6 +9,18 @@ Table and partition column-statistics reads fill omitted required numeric member string, binary, long, double, decimal, date, and boolean statistics. Supplied values and stored records are preserved; optional minimum and maximum values remain absent when omitted. +Table and partition reads (`GetTable`, `GetTables`, `SearchTables`, `GetTableVersion`, `GetTableVersions`, +`GetPartition`, `GetPartitions`, `BatchGetPartition`) return a table's `Retention` as `0`, and a storage +descriptor's `Compressed`, `NumberOfBuckets`, `SortColumns` and `StoredAsSubDirectories` as `false`, `0`, `[]` +and `false`, when they were written without them, as Glue does. A table's `IsRegisteredWithLakeFormation` is +`false`: Floci does not tie a table to a location registered with Lake Formation. The Glue Data Catalog client +that Hive and Spark use on EMR reads each of them. Stored records keep what was written, and a storage +descriptor keeps the `AdditionalLocations`, `BucketColumns`, `SortColumns`, `SkewedInfo` and +`StoredAsSubDirectories` it was given. A `SortColumns` entry that is null, lacks its required `Column` or +`SortOrder`, or has a `SortOrder` other than `0` or `1` fails the whole `CreateTable`, `UpdateTable`, +`CreatePartition`, `UpdatePartition`, `BatchCreatePartition` or `BatchUpdatePartition` with a +`ValidationException`, before anything is stored. + ## Supported Actions ### Data Catalog @@ -43,7 +55,7 @@ records are preserved; optional minimum and maximum values remain absent when om | Action | Description | |--------|-------------| | CreatePartition | Creates a partition for a Data Catalog table. | -| GetPartitions | Lists partitions stored for a Data Catalog table. | +| GetPartitions | Lists partitions stored for a Data Catalog table. With a `Segment`, returns that segment's share of them: each partition is in exactly one of `TotalSegments` (1 to 10) segments; a `Segment` member that is not an integer is a `SerializationException`. | | BatchDeletePartition | Deletes up to 25 partitions, reporting the ones not found in `Errors`. | | CreatePartitionIndex | Registers a partition index on a table. Keys must name partition columns, and a table holds at most 3 indexes. The index reports `CREATING` before `ACTIVE`. | | GetPartitionIndexes | Lists a table's partition indexes, each with its keys resolved to name and type. | diff --git a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java index cf8b5cfc8c..92f4d0960c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunner.java @@ -741,7 +741,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo return escaped.toString(); } - // Floci's Hadoop settings: S3A on Floci's S3, and the Glue Data Catalog client on Floci's Glue. + // Floci's Hadoop settings: S3A on Floci's S3, and the Glue Data Catalog client on Floci's Glue, in the job's + // account. Given none, the client from emr-7.10.0 asks STS for it, through a client no setting points at Floci. private static List hadoopSettings(Job job, String flociEndpoint) { return List.of( new SparkSetting("fs.s3a.endpoint", flociEndpoint), @@ -751,6 +752,7 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo new SparkSetting("fs.s3.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem"), new SparkSetting("fs.AbstractFileSystem.s3.impl", "org.apache.hadoop.fs.s3a.S3A"), new SparkSetting("aws.glue.endpoint", flociEndpoint), + new SparkSetting("hive.metastore.glue.catalogid", job.accountId()), new SparkSetting("aws.region", job.region())); } diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java index e1619dce2b..dff3669c25 100644 --- a/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueJsonHandler.java @@ -114,7 +114,7 @@ public class GlueJsonHandler { String dbName = request.get("DatabaseName").asText(); String tableName = request.get("Name").asText(); Table table = glueService.getTable(dbName, tableName); - yield Response.ok(Map.of("Table", table)).build(); + yield Response.ok(Map.of("Table", GlueService.withReadDefaults(table))).build(); } case "CreatePartitionIndex" -> { String dbName = request.get("DatabaseName").asText(); @@ -142,7 +142,8 @@ public class GlueJsonHandler { } case "GetTables" -> { String dbName = request.get("DatabaseName").asText(); - yield Response.ok(Map.of("TableList", glueService.getTables(dbName))).build(); + List tables = glueService.getTables(dbName).stream().map(GlueService::withReadDefaults).toList(); + yield Response.ok(Map.of("TableList", tables)).build(); } case "UpdateTable" -> { String dbName = request.get("DatabaseName").asText(); @@ -205,7 +206,10 @@ public class GlueJsonHandler { String dbName = request.get("DatabaseName").asText(); String tableName = request.get("TableName").asText(); String expression = request.path("Expression").asText(null); - yield Response.ok(Map.of("Partitions", glueService.getPartitions(dbName, tableName, expression))).build(); + GlueService.Segment segment = request.hasNonNull("Segment") ? segment(request.get("Segment")) : null; + List partitions = glueService.getPartitions(dbName, tableName, expression, segment).stream() + .map(GlueService::withReadDefaults).toList(); + yield Response.ok(Map.of("Partitions", partitions)).build(); } case "DeletePartition" -> handleDeletePartition(request); case "BatchDeletePartition" -> handleBatchDeletePartition(request); @@ -701,13 +705,37 @@ public class GlueJsonHandler { return Response.ok(Map.of("Errors", glueService.batchUpdatePartitions(dbName, tableName, entries))).build(); } + /** + * A Segment that is not a structure of integers is a malformed request, refused with SerializationException + * before its constraints are checked, as the awsJson1_1 protocol refuses a member of the wrong type; the + * message is Floci's. + */ + private static GlueService.Segment segment(JsonNode segment) { + if (!segment.isObject()) { + throw new AwsException("SerializationException", "Segment must be a structure", 400); + } + return new GlueService.Segment( + integerMember(segment, "SegmentNumber"), integerMember(segment, "TotalSegments")); + } + + private static Integer integerMember(JsonNode segment, String member) { + JsonNode value = segment.get(member); + if (value == null || value.isNull()) { + return null; + } + if (!value.isIntegralNumber() || !value.canConvertToInt()) { + throw new AwsException("SerializationException", "Segment." + member + " must be an integer", 400); + } + return value.intValue(); + } + private Response handleGetPartition(JsonNode request) { String dbName = request.get("DatabaseName").asText(); String tableName = request.get("TableName").asText(); List partitionValues = mapper.convertValue(request.get("PartitionValues"), STRING_LIST); return Response.ok(Map.of( "Partition", - glueService.getPartition(dbName, tableName, partitionValues))) + GlueService.withReadDefaults(glueService.getPartition(dbName, tableName, partitionValues)))) .build(); } @@ -718,8 +746,10 @@ public class GlueJsonHandler { List> partitionValues = partitionsToGet.stream() .map(partition -> mapper.convertValue(partition.get("Values"), STRING_LIST)) .toList(); + List partitions = glueService.batchGetPartitions(dbName, tableName, partitionValues).stream() + .map(GlueService::withReadDefaults).toList(); return Response.ok(Map.of( - "Partitions", glueService.batchGetPartitions(dbName, tableName, partitionValues), + "Partitions", partitions, "UnprocessedKeys", List.of())) .build(); } @@ -746,7 +776,8 @@ public class GlueJsonHandler { GlueService.Page
page = glueService.searchTables( request.path("SearchText").asText(null), filters, sortCriteria, readMaxResults(request), readNextToken(request)); - return Response.ok(pageResponse("TableList", page.items(), page.nextToken())).build(); + List
tables = page.items().stream().map(GlueService::withReadDefaults).toList(); + return Response.ok(pageResponse("TableList", tables, page.nextToken())).build(); } private Response handleDeletePartition(JsonNode request) { diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java index ce834aa1ac..9c805fc16c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java +++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueService.java @@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.Base64Url; import io.github.hectorvent.floci.core.common.EpochSeconds; import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.SmithyValidationErrors; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.glue.model.Classifier; @@ -433,6 +434,7 @@ public class GlueService { } public void createTable(String databaseName, Table table) { + requireValidSortColumns(sortColumnViolations("tableInput", table.getStorageDescriptor())); Database database = getDatabase(databaseName); String key = tableKey(databaseName, table.getName()); if (tableStore.get(key).isPresent()) { @@ -658,6 +660,7 @@ public class GlueService { } public synchronized void updateTable(String databaseName, Table table, String versionId, boolean skipArchive) { + requireValidSortColumns(sortColumnViolations("tableInput", table.getStorageDescriptor())); Database database = getDatabase(databaseName); String key = tableKey(databaseName, table.getName()); Table existing = tableStore.get(key) @@ -691,7 +694,7 @@ public class GlueService { .toList()); return versions.stream() .map(table -> Map.of( - "Table", withResolvedSchemaReference(table), + "Table", withReadDefaults(withResolvedSchemaReference(table)), "VersionId", table.getVersionId())) .toList(); } @@ -708,7 +711,7 @@ public class GlueService { .map(this::withResolvedSchemaReference) .orElseThrow(() -> new AwsException("EntityNotFoundException", "Version not found.", 400)); } - return Map.of("Table", version, "VersionId", version.getVersionId()); + return Map.of("Table", withReadDefaults(version), "VersionId", version.getVersionId()); } /** @@ -844,6 +847,7 @@ public class GlueService { } public void createPartition(String databaseName, String tableName, Partition partition) { + requireValidSortColumns(sortColumnViolations("partitionInput", partition.getStorageDescriptor())); Table table = getTable(databaseName, tableName); String key = partitionKey(databaseName, tableName, partition.getValues()); partition.setDatabaseName(table.getDatabaseName()); @@ -858,6 +862,12 @@ public class GlueService { String databaseName, String tableName, List partitions) { + List violations = new ArrayList<>(); + for (int index = 0; index < partitions.size(); index++) { + violations.addAll(sortColumnViolations("partitionInputList." + (index + 1) + ".member", + descriptorOf(partitions.get(index)))); + } + requireValidSortColumns(violations); getTable(databaseName, tableName); List errors = new ArrayList<>(); for (Partition partition : partitions) { @@ -896,6 +906,13 @@ public class GlueService { String databaseName, String tableName, List entries) { + List violations = new ArrayList<>(); + for (int index = 0; index < entries.size(); index++) { + BatchUpdatePartitionEntry entry = entries.get(index); + violations.addAll(sortColumnViolations("entries." + (index + 1) + ".member.partitionInput", + entry == null ? null : descriptorOf(entry.partitionInput()))); + } + requireValidSortColumns(violations); Table table = getTable(databaseName, tableName); List errors = new ArrayList<>(); for (BatchUpdatePartitionEntry entry : entries) { @@ -916,14 +933,57 @@ public class GlueService { } public List getPartitions(String databaseName, String tableName, String expression) { + return getPartitions(databaseName, tableName, expression, null); + } + + /** + * A segment is "a non-overlapping region of a table's partitions, allowing multiple requests to be run in + * parallel", so each partition falls in the one segment its values hash to, which stays the same while other + * partitions come and go between those requests, and a SegmentNumber past the last segment holds none. The + * Glue Data Catalog client for Hive and Spark asks for five. + */ + public List getPartitions(String databaseName, String tableName, String expression, Segment segment) { + validateSegment(segment); Table table = getTable(databaseName, tableName); String prefix = tableKey(databaseName, tableName) + ":"; return partitionStore.scan(k -> k.startsWith(prefix)).stream() + .filter(partition -> segment == null || Math.floorMod(Objects.hashCode(partition.getValues()), + segment.totalSegments()) == segment.segmentNumber()) .filter(partition -> matchesPartitionExpression(table, partition, expression)) .sorted(GlueService::comparePartitionValues) .toList(); } + private static void validateSegment(Segment segment) { + if (segment == null) { + return; + } + List violations = new ArrayList<>(); + if (segment.segmentNumber() == null) { + violations.add(SmithyValidationErrors.notNull("segment.segmentNumber")); + } else if (segment.segmentNumber() < 0) { + violations.add(SmithyValidationErrors.valueTooSmall( + "segment.segmentNumber", segment.segmentNumber().toString(), 0)); + } + if (segment.totalSegments() == null) { + violations.add(SmithyValidationErrors.notNull("segment.totalSegments")); + } else { + String violation = SmithyValidationErrors.outOfRange( + "segment.totalSegments", segment.totalSegments(), 1, 10); + if (violation != null) { + violations.add(violation); + } + } + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + } + + @RegisterForReflection + public record Segment( + @JsonProperty("SegmentNumber") Integer segmentNumber, + @JsonProperty("TotalSegments") Integer totalSegments) {} + /** * Registers a partition index on a table. * @@ -1121,6 +1181,7 @@ public class GlueService { } public void updatePartition(String databaseName, String tableName, List partitionValues, Partition partition) { + requireValidSortColumns(sortColumnViolations("partitionInput", partition.getStorageDescriptor())); Table table = getTable(databaseName, tableName); String key = partitionKey(databaseName, tableName, partitionValues); Partition existing = partitionStore.get(key) @@ -1674,6 +1735,7 @@ public class GlueService { copy.setCreateTime(source.getCreateTime()); copy.setUpdateTime(source.getUpdateTime()); copy.setLastAccessTime(source.getLastAccessTime()); + copy.setRetention(source.getRetention()); copy.setPartitionKeys(copyColumns(source.getPartitionKeys())); copy.setStorageDescriptor(copyStorageDescriptor(source.getStorageDescriptor())); copy.setTableType(source.getTableType()); @@ -1684,6 +1746,98 @@ public class GlueService { return copy; } + /** + * Glue reads back a table's Retention, and a storage descriptor's Compressed, NumberOfBuckets, SortColumns + * and StoredAsSubDirectories, as 0, false, 0, an empty list and false when the writer left them out, and the + * Glue Data Catalog client for Hive and Spark unboxes them without a null check, as it does + * IsRegisteredWithLakeFormation, which is false: Floci ties no table to a location registered with Lake + * Formation. So every table and partition a catalog action returns carries them, while the stored record keeps + * its nulls, which Spectrum reads as a partition taking its table's value. + */ + static Table withReadDefaults(Table table) { + Table copy = copyTable(table); + if (copy.getRetention() == null) { + copy.setRetention(0); + } + copy.setRegisteredWithLakeFormation(false); + fillReadDefaults(copy.getStorageDescriptor()); + return copy; + } + + static Partition withReadDefaults(Partition partition) { + Partition copy = new Partition(); + copy.setValues(copyStrings(partition.getValues())); + copy.setDatabaseName(partition.getDatabaseName()); + copy.setTableName(partition.getTableName()); + copy.setCreationTime(partition.getCreationTime()); + copy.setLastAccessTime(partition.getLastAccessTime()); + copy.setStorageDescriptor(copyStorageDescriptor(partition.getStorageDescriptor())); + copy.setParameters(copyMap(partition.getParameters())); + fillReadDefaults(copy.getStorageDescriptor()); + return copy; + } + + /** + * An Order's Column and SortOrder are required, and SortOrder is 0 or 1 (the model's IntegerFlag); the Glue Data + * Catalog client unboxes SortOrder on read. So a sort column breaking them fails the whole request, a batch's + * included, before anything is stored. + */ + private static List sortColumnViolations(String path, StorageDescriptor descriptor) { + List violations = new ArrayList<>(); + if (descriptor == null || descriptor.getSortColumns() == null) { + return violations; + } + List orders = descriptor.getSortColumns(); + for (int index = 0; index < orders.size(); index++) { + String member = path + ".storageDescriptor.sortColumns." + (index + 1) + ".member"; + StorageDescriptor.Order order = orders.get(index); + if (order == null) { + violations.add(SmithyValidationErrors.notNull(member)); + continue; + } + if (order.getColumn() == null) { + violations.add(SmithyValidationErrors.notNull(member + ".column")); + } + if (order.getSortOrder() == null) { + violations.add(SmithyValidationErrors.notNull(member + ".sortOrder")); + } else { + String violation = SmithyValidationErrors.outOfRange(member + ".sortOrder", order.getSortOrder(), 0, 1); + if (violation != null) { + violations.add(violation); + } + } + } + return violations; + } + + private static StorageDescriptor descriptorOf(Partition partition) { + return partition == null ? null : partition.getStorageDescriptor(); + } + + private static void requireValidSortColumns(List violations) { + if (!violations.isEmpty()) { + throw SmithyValidationErrors.validationException(violations); + } + } + + private static void fillReadDefaults(StorageDescriptor descriptor) { + if (descriptor == null) { + return; + } + if (descriptor.getCompressed() == null) { + descriptor.setCompressed(false); + } + if (descriptor.getNumberOfBuckets() == null) { + descriptor.setNumberOfBuckets(0); + } + if (descriptor.getSortColumns() == null) { + descriptor.setSortColumns(new ArrayList<>()); + } + if (descriptor.getStoredAsSubDirectories() == null) { + descriptor.setStoredAsSubDirectories(false); + } + } + private static String nextVersionId(String versionId) { if (versionId == null) { return "1"; @@ -1707,16 +1861,46 @@ public class GlueService { StorageDescriptor copy = new StorageDescriptor(); copy.setColumns(copyColumns(source.getColumns())); copy.setLocation(source.getLocation()); + copy.setAdditionalLocations(copyStrings(source.getAdditionalLocations())); copy.setInputFormat(source.getInputFormat()); copy.setOutputFormat(source.getOutputFormat()); copy.setCompressed(source.getCompressed()); copy.setNumberOfBuckets(source.getNumberOfBuckets()); copy.setSerdeInfo(copySerDeInfo(source.getSerdeInfo())); + copy.setBucketColumns(copyStrings(source.getBucketColumns())); + copy.setSortColumns(copySortColumns(source.getSortColumns())); copy.setParameters(copyMap(source.getParameters())); + copy.setSkewedInfo(copySkewedInfo(source.getSkewedInfo())); + copy.setStoredAsSubDirectories(source.getStoredAsSubDirectories()); copy.setSchemaReference(copySchemaReference(source.getSchemaReference())); return copy; } + private static List copySortColumns(List source) { + if (source == null) { + return null; + } + List copy = new ArrayList<>(source.size()); + for (StorageDescriptor.Order order : source) { + StorageDescriptor.Order orderCopy = new StorageDescriptor.Order(); + orderCopy.setColumn(order.getColumn()); + orderCopy.setSortOrder(order.getSortOrder()); + copy.add(orderCopy); + } + return copy; + } + + private static StorageDescriptor.SkewedInfo copySkewedInfo(StorageDescriptor.SkewedInfo source) { + if (source == null) { + return null; + } + StorageDescriptor.SkewedInfo copy = new StorageDescriptor.SkewedInfo(); + copy.setSkewedColumnNames(copyStrings(source.getSkewedColumnNames())); + copy.setSkewedColumnValues(copyStrings(source.getSkewedColumnValues())); + copy.setSkewedColumnValueLocationMaps(copyMap(source.getSkewedColumnValueLocationMaps())); + return copy; + } + private static StorageDescriptor.SerDeInfo copySerDeInfo(StorageDescriptor.SerDeInfo source) { if (source == null) { return null; @@ -1763,6 +1947,10 @@ public class GlueService { return source != null ? new LinkedHashMap<>(source) : null; } + private static List copyStrings(List source) { + return source != null ? new ArrayList<>(source) : null; + } + private void validateRequired(String value, String fieldName) { if (value == null || value.isBlank()) { throw new AwsException("InvalidInputException", fieldName + " is required.", 400); diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/StorageDescriptor.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/StorageDescriptor.java index af937047b6..5d4c838456 100644 --- a/src/main/java/io/github/hectorvent/floci/services/glue/model/StorageDescriptor.java +++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/StorageDescriptor.java @@ -12,6 +12,8 @@ public class StorageDescriptor { private List columns; @JsonProperty("Location") private String location; + @JsonProperty("AdditionalLocations") + private List additionalLocations; @JsonProperty("InputFormat") private String inputFormat; @JsonProperty("OutputFormat") @@ -22,8 +24,16 @@ public class StorageDescriptor { private Integer numberOfBuckets; @JsonProperty("SerdeInfo") private SerDeInfo serdeInfo; + @JsonProperty("BucketColumns") + private List bucketColumns; + @JsonProperty("SortColumns") + private List sortColumns; @JsonProperty("Parameters") private Map parameters; + @JsonProperty("SkewedInfo") + private SkewedInfo skewedInfo; + @JsonProperty("StoredAsSubDirectories") + private Boolean storedAsSubDirectories; @JsonProperty("SchemaReference") private SchemaReference schemaReference; @@ -33,6 +43,10 @@ public class StorageDescriptor { public void setColumns(List columns) { this.columns = columns; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } + public List getAdditionalLocations() { return additionalLocations; } + public void setAdditionalLocations(List additionalLocations) { + this.additionalLocations = additionalLocations; + } public String getInputFormat() { return inputFormat; } public void setInputFormat(String inputFormat) { this.inputFormat = inputFormat; } public String getOutputFormat() { return outputFormat; } @@ -43,8 +57,18 @@ public class StorageDescriptor { public void setNumberOfBuckets(Integer numberOfBuckets) { this.numberOfBuckets = numberOfBuckets; } public SerDeInfo getSerdeInfo() { return serdeInfo; } public void setSerdeInfo(SerDeInfo serdeInfo) { this.serdeInfo = serdeInfo; } + public List getBucketColumns() { return bucketColumns; } + public void setBucketColumns(List bucketColumns) { this.bucketColumns = bucketColumns; } + public List getSortColumns() { return sortColumns; } + public void setSortColumns(List sortColumns) { this.sortColumns = sortColumns; } public Map getParameters() { return parameters; } public void setParameters(Map parameters) { this.parameters = parameters; } + public SkewedInfo getSkewedInfo() { return skewedInfo; } + public void setSkewedInfo(SkewedInfo skewedInfo) { this.skewedInfo = skewedInfo; } + public Boolean getStoredAsSubDirectories() { return storedAsSubDirectories; } + public void setStoredAsSubDirectories(Boolean storedAsSubDirectories) { + this.storedAsSubDirectories = storedAsSubDirectories; + } public SchemaReference getSchemaReference() { return schemaReference; } public void setSchemaReference(SchemaReference schemaReference) { this.schemaReference = schemaReference; } @@ -64,4 +88,38 @@ public class StorageDescriptor { public Map getParameters() { return parameters; } public void setParameters(Map parameters) { this.parameters = parameters; } } + + @RegisterForReflection + public static class Order { + @JsonProperty("Column") + private String column; + @JsonProperty("SortOrder") + private Integer sortOrder; + + public String getColumn() { return column; } + public void setColumn(String column) { this.column = column; } + public Integer getSortOrder() { return sortOrder; } + public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; } + } + + @RegisterForReflection + public static class SkewedInfo { + @JsonProperty("SkewedColumnNames") + private List skewedColumnNames; + @JsonProperty("SkewedColumnValues") + private List skewedColumnValues; + @JsonProperty("SkewedColumnValueLocationMaps") + private Map skewedColumnValueLocationMaps; + + public List getSkewedColumnNames() { return skewedColumnNames; } + public void setSkewedColumnNames(List skewedColumnNames) { this.skewedColumnNames = skewedColumnNames; } + public List getSkewedColumnValues() { return skewedColumnValues; } + public void setSkewedColumnValues(List skewedColumnValues) { + this.skewedColumnValues = skewedColumnValues; + } + public Map getSkewedColumnValueLocationMaps() { return skewedColumnValueLocationMaps; } + public void setSkewedColumnValueLocationMaps(Map skewedColumnValueLocationMaps) { + this.skewedColumnValueLocationMaps = skewedColumnValueLocationMaps; + } + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/model/Table.java b/src/main/java/io/github/hectorvent/floci/services/glue/model/Table.java index fcea6717ac..a98e2380e2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/glue/model/Table.java +++ b/src/main/java/io/github/hectorvent/floci/services/glue/model/Table.java @@ -27,6 +27,8 @@ public class Table { @JsonProperty("LastAccessTime") @JsonFormat(shape = JsonFormat.Shape.NUMBER) private Instant lastAccessTime; + @JsonProperty("Retention") + private Integer retention; @JsonProperty("PartitionKeys") private List partitionKeys; @JsonProperty("StorageDescriptor") @@ -41,6 +43,8 @@ public class Table { private String versionId; @JsonProperty("Parameters") private Map parameters; + @JsonProperty("IsRegisteredWithLakeFormation") + private Boolean registeredWithLakeFormation; public Table() {} @@ -58,6 +62,8 @@ public class Table { public void setUpdateTime(Instant updateTime) { this.updateTime = updateTime; } public Instant getLastAccessTime() { return lastAccessTime; } public void setLastAccessTime(Instant lastAccessTime) { this.lastAccessTime = lastAccessTime; } + public Integer getRetention() { return retention; } + public void setRetention(Integer retention) { this.retention = retention; } public List getPartitionKeys() { return partitionKeys; } public void setPartitionKeys(List partitionKeys) { this.partitionKeys = partitionKeys; } public StorageDescriptor getStorageDescriptor() { return storageDescriptor; } @@ -72,4 +78,8 @@ public class Table { public void setVersionId(String versionId) { this.versionId = versionId; } public Map getParameters() { return parameters; } public void setParameters(Map parameters) { this.parameters = parameters; } + public Boolean getRegisteredWithLakeFormation() { return registeredWithLakeFormation; } + public void setRegisteredWithLakeFormation(Boolean registeredWithLakeFormation) { + this.registeredWithLakeFormation = registeredWithLakeFormation; + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java index 537d57e43e..bd24064f9c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/emrserverless/EmrServerlessSparkRunnerTest.java @@ -107,6 +107,7 @@ class EmrServerlessSparkRunnerTest { "--conf", "spark.hadoop.fs.s3.impl=org.apache.hadoop.fs.s3a.S3AFileSystem", "--conf", "spark.hadoop.fs.AbstractFileSystem.s3.impl=org.apache.hadoop.fs.s3a.S3A", "--conf", "spark.hadoop.aws.glue.endpoint=http://floci:4566", + "--conf", "spark.hadoop.hive.metastore.glue.catalogid=123456789012", "--conf", "spark.hadoop.aws.region=eu-west-1", "--conf", "spark.executor.cores=4", "--conf", "spark.sql.shuffle.partitions=8", @@ -115,6 +116,19 @@ class EmrServerlessSparkRunnerTest { "s3://bucket/jobs/report.py", "s3://bucket/input/", "s3://bucket/output/"), arguments); } + @Test + void theGlueCatalogIsTheJobsAccountUnlessTheJobNamesOneInAnotherAccount() { + String own = "spark.hadoop.hive.metastore.glue.catalogid=123456789012"; + String other = "spark.hadoop.hive.metastore.glue.catalogid=111122223333"; + + List arguments = EmrServerlessSparkRunner.sparkSubmitArguments(job(List.of("s3://bucket/jobs/app.jar"), + Map.of("spark.hadoop.hive.metastore.glue.catalogid", "111122223333")), ENDPOINT); + + // The job's own setting comes later, so it wins. + assertTrue(arguments.contains(own)); + assertTrue(arguments.indexOf(other) > arguments.indexOf(own)); + } + @Test void anApplicationWithoutOptionsOrArgumentsFollowsFlocisSettings() { List arguments = EmrServerlessSparkRunner.sparkSubmitArguments( @@ -415,7 +429,7 @@ class EmrServerlessSparkRunnerTest { verify(spec).withNamedVolume(STORAGE.home(), "/home/hadoop"); verify(spec).withNamedVolume(STORAGE.mnt(), "/mnt"); // After Floci's S3 settings, before the cluster's spark-defaults, which win. - assertEquals("spark.hadoop.aws.region=eu-west-1", arguments.get(17)); + assertEquals("spark.hadoop.aws.region=eu-west-1", arguments.get(19)); assertEquals(List.of( "--conf", "spark.hadoop.fs.defaultFS=hdfs:///", "--conf", "spark.hadoop.fs.hdfs.impl=org.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme", @@ -423,7 +437,7 @@ class EmrServerlessSparkRunnerTest { "--conf", "spark.sql.streaming.checkpointFileManagerClass=" + "org.apache.spark.sql.execution.streaming.FileSystemBasedCheckpointFileManager", "--conf", "spark.hadoop.fs.defaultFS=file:///", - "s3://bucket/jobs/report.py"), arguments.subList(18, arguments.size())); + "s3://bucket/jobs/report.py"), arguments.subList(20, arguments.size())); } @Test @@ -573,6 +587,7 @@ class EmrServerlessSparkRunnerTest { "fs.AbstractFileSystem.s3.implorg.apache.hadoop.fs.s3a.S3A" + "", "aws.glue.endpointhttp://floci:4566", + "hive.metastore.glue.catalogid123456789012", "aws.regioneu-west-1", "fs.defaultFShdfs:///", "fs.hdfs.implorg.apache.hadoop.fs.viewfs.ViewFileSystemOverloadScheme" @@ -805,6 +820,7 @@ class EmrServerlessSparkRunnerTest { "spark.hadoop.fs.s3.impl org.apache.hadoop.fs.s3a.S3AFileSystem", "spark.hadoop.fs.AbstractFileSystem.s3.impl org.apache.hadoop.fs.s3a.S3A", "spark.hadoop.aws.glue.endpoint http://floci:4566", + "spark.hadoop.hive.metastore.glue.catalogid 123456789012", "spark.hadoop.aws.region eu-west-1", "spark.sql.shuffle.partitions 8"), EmrServerlessSparkRunner.sparkDefaultsFile( diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueCatalogClientFieldsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueCatalogClientFieldsIntegrationTest.java new file mode 100644 index 0000000000..1289aabe09 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueCatalogClientFieldsIntegrationTest.java @@ -0,0 +1,338 @@ +package io.github.hectorvent.floci.services.glue; + +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import io.restassured.response.ValidatableResponse; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.glue.GlueClient; +import software.amazon.awssdk.services.glue.model.BatchUpdatePartitionRequestEntry; +import software.amazon.awssdk.services.glue.model.Column; +import software.amazon.awssdk.services.glue.model.DatabaseInput; +import software.amazon.awssdk.services.glue.model.EntityNotFoundException; +import software.amazon.awssdk.services.glue.model.GlueException; +import software.amazon.awssdk.services.glue.model.Order; +import software.amazon.awssdk.services.glue.model.Partition; +import software.amazon.awssdk.services.glue.model.PartitionInput; +import software.amazon.awssdk.services.glue.model.PartitionValueList; +import software.amazon.awssdk.services.glue.model.Segment; +import software.amazon.awssdk.services.glue.model.SerDeInfo; +import software.amazon.awssdk.services.glue.model.SkewedInfo; +import software.amazon.awssdk.services.glue.model.StorageDescriptor; +import software.amazon.awssdk.services.glue.model.Table; +import software.amazon.awssdk.services.glue.model.TableInput; +import software.amazon.awssdk.services.glue.model.TableVersion; + +import java.net.URI; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; +import java.util.UUID; +import java.util.stream.IntStream; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The fields the Glue Data Catalog client for Hive and Spark writes and unboxes on read, through every catalog + * action that returns a table or partition, and the partition segments it reads a table's partitions in. + */ +@QuarkusTest +class GlueCatalogClientFieldsIntegrationTest { + + private static final String CONTENT_TYPE = "application/x-amz-json-1.1"; + + private static final StorageDescriptor HIVE_DESCRIPTOR = StorageDescriptor.builder() + .columns(Column.builder().name("id").type("int").build(), + Column.builder().name("name").type("string").build()) + .location("s3://warehouse/bucketed/") + .additionalLocations("s3://warehouse/more/") + .inputFormat("org.apache.hadoop.mapred.TextInputFormat") + .outputFormat("org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat") + .compressed(true) + .numberOfBuckets(4) + .serdeInfo(SerDeInfo.builder() + .serializationLibrary("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe").build()) + .bucketColumns("id") + .sortColumns(Order.builder().column("id").sortOrder(1).build()) + .skewedInfo(SkewedInfo.builder().skewedColumnNames("name").skewedColumnValues("a") + .skewedColumnValueLocationMaps(Map.of("a", "s3://warehouse/bucketed/name=a/")).build()) + .storedAsSubDirectories(true) + .build(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void everyCatalogReadReturnsTheStorageFieldsTheHiveClientWrites() { + String database = "hive_" + UUID.randomUUID().toString().replace("-", ""); + try (GlueClient client = client()) { + client.createDatabase(request -> request.databaseInput(DatabaseInput.builder().name(database).build())); + try { + TableInput input = TableInput.builder().name("bucketed").retention(7).storageDescriptor(HIVE_DESCRIPTOR) + .partitionKeys(Column.builder().name("day").type("string").build()).build(); + Instant accessed = Instant.ofEpochSecond(1_700_000_000L); + write(client, database, input, PartitionInput.builder().values("one").storageDescriptor(HIVE_DESCRIPTOR) + .parameters(Map.of("transient_lastDdlTime", "1700000000")).lastAccessTime(accessed).build()); + + for (Table table : tables(client, database, "bucketed")) { + assertEquals(7, table.retention()); + assertEquals(HIVE_DESCRIPTOR, table.storageDescriptor()); + } + for (Partition partition : partitions(client, database, "bucketed")) { + assertEquals(HIVE_DESCRIPTOR, partition.storageDescriptor()); + assertEquals(List.of("one"), partition.values()); + assertEquals(database, partition.databaseName()); + assertEquals("bucketed", partition.tableName()); + assertEquals(Map.of("transient_lastDdlTime", "1700000000"), partition.parameters()); + assertEquals(accessed, partition.lastAccessTime()); + assertNotNull(partition.creationTime()); + } + } finally { + client.deleteDatabase(request -> request.name(database)); + } + } + } + + @Test + void aTableAndPartitionWrittenWithoutThemReadBackGluesDefaults() { + String database = "plain_" + UUID.randomUUID().toString().replace("-", ""); + try (GlueClient client = client()) { + client.createDatabase(request -> request.databaseInput(DatabaseInput.builder().name(database).build())); + try { + StorageDescriptor descriptor = StorageDescriptor.builder() + .columns(Column.builder().name("id").type("int").build()) + .location("s3://warehouse/plain/").build(); + TableInput input = TableInput.builder().name("plain").storageDescriptor(descriptor) + .partitionKeys(Column.builder().name("day").type("string").build()).build(); + write(client, database, input, PartitionInput.builder().values("one").storageDescriptor( + StorageDescriptor.builder().location("s3://warehouse/plain/day=one/").build()).build()); + + for (Table table : tables(client, database, "plain")) { + assertEquals(0, table.retention()); + assertFalse(table.isRegisteredWithLakeFormation()); + assertGluesDefaults(table.storageDescriptor()); + } + for (Partition partition : partitions(client, database, "plain")) { + assertGluesDefaults(partition.storageDescriptor()); + } + } finally { + client.deleteDatabase(request -> request.name(database)); + } + } + } + + @Test + void theHiveClientsFiveSegmentsSplitATablesPartitionsWithoutOverlap() { + String database = "segments_" + UUID.randomUUID().toString().replace("-", ""); + try (GlueClient client = client()) { + client.createDatabase(request -> request.databaseInput(DatabaseInput.builder().name(database).build())); + try { + TableInput input = TableInput.builder().name("days") + .partitionKeys(Column.builder().name("day").type("string").build()).build(); + client.createTable(request -> request.databaseName(database).tableInput(input)); + List days = IntStream.range(0, 12).mapToObj(day -> "day" + day).toList(); + List partitions = days.stream() + .map(day -> PartitionInput.builder().values(day).build()).toList(); + client.batchCreatePartition(request -> request.databaseName(database).tableName("days") + .partitionInputList(partitions)); + + List segmented = new ArrayList<>(); + for (int number = 0; number < 5; number++) { + segmented.addAll(segment(client, database, number, 5)); + } + assertEquals(new TreeSet<>(days), new TreeSet<>(segmented)); + assertEquals(days.size(), segmented.size()); + assertEquals(new TreeSet<>(days), new TreeSet<>(segment(client, database, 0, 1))); + assertEquals(List.of(), segment(client, database, 5, 5)); + + assertSegmentRefused(client, database, Segment.builder().segmentNumber(0).totalSegments(11).build(), + "Value '11' at 'segment.totalSegments' failed to satisfy constraint: " + + "Member must have value less than or equal to 10"); + assertSegmentRefused(client, database, Segment.builder().segmentNumber(0).totalSegments(0).build(), + "Value '0' at 'segment.totalSegments' failed to satisfy constraint: " + + "Member must have value greater than or equal to 1"); + assertSegmentRefused(client, database, Segment.builder().segmentNumber(-1).totalSegments(5).build(), + "Value '-1' at 'segment.segmentNumber' failed to satisfy constraint: " + + "Member must have value greater than or equal to 0"); + assertSegmentRefused(client, database, Segment.builder().totalSegments(5).build(), + "Value null at 'segment.segmentNumber' failed to satisfy constraint: Member must not be null"); + assertSegmentRefused(client, database, Segment.builder().segmentNumber(0).build(), + "Value null at 'segment.totalSegments' failed to satisfy constraint: Member must not be null"); + + // A member of the wrong type is malformed, refused before any constraint. + for (String malformed : List.of("\"0 of 5\"", "{\"SegmentNumber\": \"bad\", \"TotalSegments\": 5}", + "{\"SegmentNumber\": 1.5, \"TotalSegments\": 5}", + "{\"SegmentNumber\": 0, \"TotalSegments\": true}", + "{\"SegmentNumber\": 4294967296, \"TotalSegments\": 5}")) { + post("GetPartitions", "{\"DatabaseName\": \"" + database + "\", \"TableName\": \"days\", " + + "\"Segment\": " + malformed + "}") + .statusCode(400).body("__type", equalTo("SerializationException")); + } + } finally { + client.deleteDatabase(request -> request.name(database)); + } + } + } + + @Test + void aSortColumnMissingAMemberOrOutOfRangeIsRefusedBeforeAnythingIsStored() { + String database = "sorted_" + UUID.randomUUID().toString().replace("-", ""); + Order noSortOrder = Order.builder().column("id").build(); + String missingSortOrder = ".storageDescriptor.sortColumns.1.member.sortOrder' failed to satisfy constraint: " + + "Member must not be null"; + try (GlueClient client = client()) { + client.createDatabase(request -> request.databaseInput(DatabaseInput.builder().name(database).build())); + try { + assertRefused(() -> client.createTable(request -> request.databaseName(database).tableInput( + sorted("plain", noSortOrder, Order.builder().sortOrder(0).build(), + Order.builder().column("id").sortOrder(2).build()))), + "3 validation errors detected: Value null at 'tableInput" + missingSortOrder + "; " + + "Value null at 'tableInput.storageDescriptor.sortColumns.2.member.column' failed to " + + "satisfy constraint: Member must not be null; Value '2' at " + + "'tableInput.storageDescriptor.sortColumns.3.member.sortOrder' failed to satisfy " + + "constraint: Member must have value less than or equal to 1"); + assertThrows(EntityNotFoundException.class, + () -> client.getTable(request -> request.databaseName(database).name("plain"))); + post("CreateTable", "{\"DatabaseName\": \"" + database + "\", \"TableInput\": {\"Name\": \"plain\", " + + "\"StorageDescriptor\": {\"SortColumns\": [null]}}}") + .statusCode(400).body("__type", equalTo("ValidationException")) + .body("message", equalTo("1 validation error detected: Value null at " + + "'tableInput.storageDescriptor.sortColumns.1.member' failed to satisfy constraint: " + + "Member must not be null")); + + client.createTable(request -> request.databaseName(database).tableInput(sorted("days"))); + assertRefused(() -> client.updateTable(request -> request.databaseName(database) + .tableInput(sorted("days", noSortOrder))), + "1 validation error detected: Value null at 'tableInput" + missingSortOrder); + assertEquals("0", client.getTable(request -> request.databaseName(database).name("days")).table() + .versionId()); + + PartitionInput bad = PartitionInput.builder().values("two") + .storageDescriptor(StorageDescriptor.builder().sortColumns(noSortOrder).build()).build(); + assertRefused(() -> client.createPartition(request -> request.databaseName(database).tableName("days") + .partitionInput(bad)), + "1 validation error detected: Value null at 'partitionInput" + missingSortOrder); + assertRefused(() -> client.batchCreatePartition(request -> request.databaseName(database) + .tableName("days").partitionInputList(PartitionInput.builder().values("one").build(), bad)), + "1 validation error detected: Value null at 'partitionInputList.2.member" + missingSortOrder); + assertEquals(List.of(), client.getPartitions(request -> request.databaseName(database) + .tableName("days")).partitions()); + + client.createPartition(request -> request.databaseName(database).tableName("days") + .partitionInput(PartitionInput.builder().values("one").build())); + assertRefused(() -> client.updatePartition(request -> request.databaseName(database).tableName("days") + .partitionValueList("one").partitionInput(bad)), + "1 validation error detected: Value null at 'partitionInput" + missingSortOrder); + assertRefused(() -> client.batchUpdatePartition(request -> request.databaseName(database) + .tableName("days").entries(BatchUpdatePartitionRequestEntry.builder() + .partitionValueList("one").partitionInput(bad).build())), + "1 validation error detected: Value null at 'entries.1.member.partitionInput" + + missingSortOrder); + assertEquals(List.of(List.of("one")), client.getPartitions(request -> request.databaseName(database) + .tableName("days")).partitions().stream().map(Partition::values).toList()); + } finally { + client.deleteDatabase(request -> request.name(database)); + } + } + } + + private static TableInput sorted(String name, Order... orders) { + return TableInput.builder().name(name).partitionKeys(Column.builder().name("day").type("string").build()) + .storageDescriptor(StorageDescriptor.builder().columns(Column.builder().name("id").type("int").build()) + .sortColumns(orders).build()) + .build(); + } + + private static void assertSegmentRefused(GlueClient client, String database, Segment segment, String violation) { + assertRefused(() -> client.getPartitions(request -> request.databaseName(database).tableName("days") + .segment(segment)), "1 validation error detected: " + violation); + } + + private static void assertRefused(Executable request, String message) { + GlueException error = assertThrows(GlueException.class, request); + assertEquals(400, error.statusCode()); + assertEquals("ValidationException", error.awsErrorDetails().errorCode()); + assertEquals(message, error.awsErrorDetails().errorMessage()); + } + + private static ValidatableResponse post(String target, String body) { + return given().contentType(CONTENT_TYPE).header("X-Amz-Target", "AWSGlue." + target).body(body) + .when().post("/").then(); + } + + private static List segment(GlueClient client, String database, int number, int total) { + return client.getPartitions(request -> request.databaseName(database).tableName("days") + .segment(Segment.builder().segmentNumber(number).totalSegments(total).build())) + .partitions().stream().map(partition -> partition.values().get(0)).toList(); + } + + private static void assertGluesDefaults(StorageDescriptor descriptor) { + assertFalse(descriptor.compressed()); + assertEquals(0, descriptor.numberOfBuckets()); + assertTrue(descriptor.hasSortColumns()); + assertEquals(List.of(), descriptor.sortColumns()); + assertFalse(descriptor.storedAsSubDirectories()); + assertFalse(descriptor.hasBucketColumns()); + assertNull(descriptor.skewedInfo()); + } + + /** Creates the table, then updates it with the same input, so that version 0 is archived and 1 is current. */ + private static void write(GlueClient client, String database, TableInput input, PartitionInput partition) { + client.createTable(request -> request.databaseName(database).tableInput(input)); + client.updateTable(request -> request.databaseName(database).tableInput(input)); + client.createPartition(request -> request.databaseName(database).tableName(input.name()) + .partitionInput(partition)); + } + + private static List
tables(GlueClient client, String database, String name) { + List
tables = new ArrayList<>(); + tables.add(client.getTable(request -> request.databaseName(database).name(name)).table()); + tables.addAll(client.getTables(request -> request.databaseName(database)).tableList()); + tables.addAll(client.searchTables(request -> request.searchText(database)).tableList().stream() + .filter(table -> database.equals(table.databaseName())).toList()); + client.getTableVersions(request -> request.databaseName(database).tableName(name)).tableVersions().stream() + .map(TableVersion::table).forEach(tables::add); + tables.add(client.getTableVersion(request -> request.databaseName(database).tableName(name).versionId("0")) + .tableVersion().table()); + assertEquals(6, tables.size()); + return tables; + } + + private static List partitions(GlueClient client, String database, String table) { + List partitions = new ArrayList<>(); + partitions.add(client.getPartition(request -> request.databaseName(database).tableName(table) + .partitionValues("one")).partition()); + partitions.addAll(client.getPartitions(request -> request.databaseName(database).tableName(table)) + .partitions()); + partitions.addAll(client.batchGetPartition(request -> request.databaseName(database).tableName(table) + .partitionsToGet(PartitionValueList.builder().values("one").build())).partitions()); + assertEquals(3, partitions.size()); + return partitions; + } + + private static GlueClient client() { + return GlueClient.builder() + .endpointOverride(URI.create("http://localhost:" + RestAssured.port)) + .httpClientBuilder(UrlConnectionHttpClient.builder()).region(Region.US_EAST_1) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create("741579900001", "test"))) + .build(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java index d0177d0569..e54cdb5362 100644 --- a/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueServiceTest.java @@ -507,6 +507,45 @@ class GlueServiceTest { .toList()); } + @Test + void readDefaultsFillACopyAndLeaveTheStoredTableAndPartitionAsWritten() { + StorageDescriptor descriptor = new StorageDescriptor(); + descriptor.setLocation("s3://warehouse/plain/"); + Table table = new Table(); + table.setName("plain"); + table.setStorageDescriptor(descriptor); + glueService.createTable("db1", table); + Partition partition = new Partition(); + partition.setValues(List.of("one")); + partition.setStorageDescriptor(new StorageDescriptor()); + glueService.createPartition("db1", "plain", partition); + + Table read = GlueService.withReadDefaults(glueService.getTable("db1", "plain")); + Partition readPartition = + GlueService.withReadDefaults(glueService.getPartition("db1", "plain", List.of("one"))); + + assertEquals(0, read.getRetention()); + assertEquals(false, read.getRegisteredWithLakeFormation()); + assertEquals(List.of("one"), readPartition.getValues()); + for (StorageDescriptor filled : List.of(read.getStorageDescriptor(), readPartition.getStorageDescriptor())) { + assertEquals(false, filled.getCompressed()); + assertEquals(0, filled.getNumberOfBuckets()); + assertEquals(List.of(), filled.getSortColumns()); + assertEquals(false, filled.getStoredAsSubDirectories()); + } + // Spectrum reads a partition's missing Compressed as its table's, so the stored records keep their nulls. + Table stored = glueService.getTable("db1", "plain"); + assertNull(stored.getRetention()); + assertNull(stored.getRegisteredWithLakeFormation()); + StorageDescriptor storedPartition = glueService.getPartitions("db1", "plain").get(0).getStorageDescriptor(); + for (StorageDescriptor kept : List.of(stored.getStorageDescriptor(), storedPartition)) { + assertNull(kept.getCompressed()); + assertNull(kept.getNumberOfBuckets()); + assertNull(kept.getSortColumns()); + assertNull(kept.getStoredAsSubDirectories()); + } + } + @Test void partitionKeysDoNotCollideForCommaSeparatedValues() { Table table = new Table();