mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 17:33:03 -05:00
feat(athena): run Iceberg CREATE TABLE, DML and VACUUM through Glue's Iceberg REST catalog (#8488)
This commit is contained in:
1 parent
dbfe6e0769
commit
8206115dc8
27 files changed
+2063
-177
No files matched your search
@@ -26,7 +26,8 @@ class AthenaHiveDdlExecutorTest {
|
||||
table.setName("events");
|
||||
when(glue.getTable("lake", "events")).thenReturn(table);
|
||||
doThrow(new AwsException("EntityNotFoundException", "Table not found", 400)).when(glue).deleteTable("lake", "events");
|
||||
AthenaHiveDdlExecutor executor = new AthenaHiveDdlExecutor(glue, Mockito.mock(S3Service.class));
|
||||
AthenaHiveDdlExecutor executor = new AthenaHiveDdlExecutor(glue, Mockito.mock(S3Service.class),
|
||||
Mockito.mock(AthenaIcebergStatements.class));
|
||||
|
||||
assertDoesNotThrow(() -> executor.execute(AthenaHiveDdl.parse("DROP TABLE IF EXISTS events"), "lake"));
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.glue.iceberg.IcebergSchemas;
|
||||
import io.floci.aws.services.glue.model.Column;
|
||||
import io.floci.aws.services.glue.model.StorageDescriptor;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
@@ -109,15 +110,60 @@ class AthenaHiveDdlTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableWithoutExternalIsLeftToIcebergAndCtasOrRefused() {
|
||||
assertNull(AthenaHiveDdl.parse("CREATE TABLE t (a int) LOCATION 's3://b/t/' TBLPROPERTIES ('table_type'='ICEBERG')"));
|
||||
void createTableWithoutExternalIsIcebergOrLeftToCtasOrRefused() {
|
||||
assertInstanceOf(AthenaHiveDdl.CreateIcebergTable.class, AthenaHiveDdl.parse(
|
||||
"CREATE TABLE t (a int) LOCATION 's3://b/t/' TBLPROPERTIES ('table_type'='ICEBERG')"));
|
||||
assertNull(AthenaHiveDdl.parse("CREATE TABLE t WITH (format = 'PARQUET') AS SELECT 1 AS a"));
|
||||
assertNull(AthenaHiveDdl.parse("CREATE TABLE t WITH (table_type = 'ICEBERG') AS SELECT 1 AS a"));
|
||||
assertNull(AthenaHiveDdl.parse("CREATE TABLE t AS SELECT 1 AS a"));
|
||||
AwsException hive = assertThrows(AwsException.class,
|
||||
() -> AthenaHiveDdl.parse("CREATE TABLE t (a int) STORED AS PARQUET LOCATION 's3://b/t/'"));
|
||||
assertTrue(hive.getMessage().contains("EXTERNAL"), hive.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIcebergCreateTableKeepsItsColumnsPartitionTransformsLocationAndProperties() {
|
||||
AthenaHiveDdl.CreateIcebergTable create = assertInstanceOf(AthenaHiveDdl.CreateIcebergTable.class,
|
||||
AthenaHiveDdl.parse("""
|
||||
CREATE TABLE IF NOT EXISTS Lake.events (
|
||||
id bigint COMMENT 'the id',
|
||||
category string,
|
||||
ts timestamp,
|
||||
name string)
|
||||
PARTITIONED BY (category, bucket(16, id), day(ts), truncate(4, name))
|
||||
LOCATION 's3://lake/events/'
|
||||
TBLPROPERTIES ('table_type'='ICEBERG', 'format'='parquet', 'vacuum_min_snapshots_to_keep'='3');
|
||||
"""));
|
||||
|
||||
assertTrue(create.ifNotExists());
|
||||
assertEquals(new AthenaHiveDdl.TableRef("lake", "events"), create.ref());
|
||||
assertEquals(List.of("id:bigint", "category:string", "ts:timestamp", "name:string"), create.columns().stream()
|
||||
.map(column -> column.getName() + ":" + column.getType()).toList());
|
||||
assertEquals("the id", create.columns().getFirst().getComment());
|
||||
assertEquals(List.of(new IcebergSchemas.PartitionField("identity", null, "category"),
|
||||
new IcebergSchemas.PartitionField("bucket", 16, "id"),
|
||||
new IcebergSchemas.PartitionField("day", null, "ts"),
|
||||
new IcebergSchemas.PartitionField("truncate", 4, "name")), create.partitioning());
|
||||
assertEquals("s3://lake/events/", create.location());
|
||||
assertEquals(Map.of("format", "parquet", "vacuum_min_snapshots_to_keep", "3"), create.properties());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedIcebergPartitionTransformSaysWhatIsWrong() {
|
||||
AwsException e = assertThrows(AwsException.class, () -> AthenaHiveDdl.parse(
|
||||
"CREATE TABLE t (id int) PARTITIONED BY (bucket(id, 16)) TBLPROPERTIES ('table_type'='ICEBERG')"));
|
||||
|
||||
assertEquals("InvalidRequestException", e.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumNamesItsTable() {
|
||||
assertEquals(new AthenaHiveDdl.TableRef("lake", "events"), assertInstanceOf(AthenaHiveDdl.Vacuum.class,
|
||||
AthenaHiveDdl.parse("VACUUM lake.events;")).ref());
|
||||
assertEquals(new AthenaHiveDdl.TableRef(null, "_events"), assertInstanceOf(AthenaHiveDdl.Vacuum.class,
|
||||
AthenaHiveDdl.parse("vacuum `_events`")).ref());
|
||||
}
|
||||
|
||||
@Test
|
||||
void dropRepairAndShowNameTheirTable() {
|
||||
AthenaHiveDdl.DropTable drop = assertInstanceOf(AthenaHiveDdl.DropTable.class,
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
import io.floci.aws.services.athena.model.QueryExecution;
|
||||
import io.floci.aws.services.athena.model.QueryExecutionContext;
|
||||
import io.floci.aws.services.athena.model.QueryExecutionState;
|
||||
import io.floci.aws.services.athena.model.ResultConfiguration;
|
||||
import io.floci.aws.services.floci.duck.FlociDuckClient;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.iceberg.GlueIcebergCatalog;
|
||||
import io.floci.aws.services.glue.model.Database;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import io.floci.aws.testing.SidecarContainersProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.vertx.core.Vertx;
|
||||
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.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Athena's Iceberg statements run end to end through the real floci-duck sidecar: {@code CREATE TABLE} makes a Glue
|
||||
* Iceberg table, {@code INSERT}, {@code UPDATE}, {@code DELETE} and {@code MERGE} write it through the sidecar's
|
||||
* attachment of Glue's Iceberg REST endpoint, each commit moving the Glue table's {@code metadata_location}, and
|
||||
* {@code VACUUM} expires old snapshots and removes files nothing references.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SidecarContainersProfile.class)
|
||||
class AthenaIcebergSidecarIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Inject
|
||||
StorageFactory storageFactory;
|
||||
|
||||
@Inject
|
||||
FlociDuckClient duck;
|
||||
|
||||
@Inject
|
||||
GlueService glue;
|
||||
|
||||
@Inject
|
||||
S3Service s3;
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
@Inject
|
||||
GlueViewDdlBuilder ddlBuilder;
|
||||
|
||||
@Inject
|
||||
RegionResolver regionResolver;
|
||||
|
||||
@Inject
|
||||
AthenaIcebergStatements icebergStatements;
|
||||
|
||||
@Inject
|
||||
GlueIcebergCatalog catalog;
|
||||
|
||||
private AthenaService athena;
|
||||
private String bucket;
|
||||
private String database;
|
||||
|
||||
@BeforeAll
|
||||
static void requireDocker() {
|
||||
SidecarContainersProfile.requireDocker();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void createDatabase() {
|
||||
athena = new AthenaService(storageFactory, duck, glue, s3, AthenaTestConfigs.realQueries(), vertx, ddlBuilder, regionResolver,
|
||||
icebergStatements);
|
||||
long suffix = System.nanoTime();
|
||||
bucket = "athena-iceberg-" + suffix;
|
||||
database = "lake_" + suffix;
|
||||
s3.createBucket(bucket, REGION);
|
||||
Database lake = new Database(database);
|
||||
lake.setLocationUri("s3://" + bucket + "/lake");
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> glue.createDatabase(lake));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void dropDatabase() {
|
||||
RequestScopes.runAs(ACCOUNT, REGION, () -> {
|
||||
for (Table table : glue.getTables(database)) {
|
||||
glue.deleteTable(database, table.getName());
|
||||
}
|
||||
glue.deleteDatabase(database);
|
||||
});
|
||||
TableLocation.of("s3://" + bucket + "/").forEachObject(s3, object -> s3.deleteObject(bucket, object.getKey()));
|
||||
s3.deleteBucket(bucket);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIcebergTableIsCreatedThenWrittenByEachDmlStatementAndReadBack() {
|
||||
run("CREATE TABLE events (id bigint, name string, category string) LOCATION 's3://" + bucket
|
||||
+ "/lake/events/' TBLPROPERTIES ('table_type'='ICEBERG')");
|
||||
|
||||
committed("INSERT INTO events VALUES (1, 'a', 'x'), (2, 'b', 'y')");
|
||||
committed("UPDATE " + database + ".events SET name = 'bb' WHERE id = 2");
|
||||
committed("DELETE FROM awsdatacatalog." + database + ".events WHERE id = 1");
|
||||
committed("""
|
||||
MERGE INTO events t
|
||||
USING (SELECT 3 AS id, 'c' AS name, 'x' AS category UNION ALL SELECT 2, 'b2', 'y') s
|
||||
ON t.id = s.id
|
||||
WHEN MATCHED THEN UPDATE SET name = s.name
|
||||
WHEN NOT MATCHED THEN INSERT VALUES (s.id, s.name, s.category)""");
|
||||
|
||||
assertEquals(List.of(row("id", "2", "name", "b2", "category", "y"), row("id", "3", "name", "c", "category", "x")),
|
||||
rows("SELECT id, name, category FROM events ORDER BY id"));
|
||||
assertEquals("2", loadTable("events").path("metadata").path("properties").path("format-version").asText());
|
||||
}
|
||||
|
||||
/** Runs a write and checks its commit landed on the Glue table, moving its {@code metadata_location}. */
|
||||
private void committed(String sql) {
|
||||
String before = metadataLocation("events");
|
||||
run(sql);
|
||||
assertNotEquals(before, metadataLocation("events"), sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartitionedIcebergTableIsWrittenByItsSpec() {
|
||||
run("CREATE TABLE events (id bigint, category string) PARTITIONED BY (category, bucket(4, id)) LOCATION 's3://"
|
||||
+ bucket + "/lake/events/' TBLPROPERTIES ('table_type'='ICEBERG')");
|
||||
JsonNode spec = loadTable("events").path("metadata").path("partition-specs").get(0).path("fields");
|
||||
assertEquals("category", spec.get(0).path("name").asText());
|
||||
assertEquals("bucket[4]", spec.get(1).path("transform").asText());
|
||||
|
||||
run("INSERT INTO events VALUES (1, 'x'), (2, 'y'), (3, 'x')");
|
||||
|
||||
assertEquals(List.of(row("category", "x", "n", "2"), row("category", "y", "n", "1")),
|
||||
rows("SELECT category, count(*) AS n FROM events GROUP BY category ORDER BY category"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumExpiresSnapshotsOlderThanTheTablesMaximumAgeAndRemovesOrphans() {
|
||||
run("CREATE TABLE events (id bigint) LOCATION 's3://" + bucket + "/lake/events/' "
|
||||
+ "TBLPROPERTIES ('table_type'='ICEBERG', 'vacuum_max_snapshot_age_seconds'='1')");
|
||||
run("INSERT INTO events VALUES (1)");
|
||||
run("INSERT INTO events VALUES (2)");
|
||||
run("INSERT INTO events VALUES (3)");
|
||||
assertEquals(3, loadTable("events").path("metadata").path("snapshots").size());
|
||||
String orphan = "lake/events/data/orphan.parquet";
|
||||
s3.putObject(bucket, orphan, "not table data".getBytes(StandardCharsets.UTF_8), "application/octet-stream",
|
||||
null);
|
||||
|
||||
// The snapshots and the orphan become older than the table's one-second maximum age.
|
||||
await().atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofSeconds(1)).untilAsserted(() -> {
|
||||
run("VACUUM events");
|
||||
assertEquals(1, loadTable("events").path("metadata").path("snapshots").size());
|
||||
assertTrue(s3.listObjects(bucket, orphan, null, 10).isEmpty(), "the orphan file is removed");
|
||||
});
|
||||
|
||||
assertEquals(List.of(row("id", "1"), row("id", "2"), row("id", "3")),
|
||||
rows("SELECT id FROM events ORDER BY id"));
|
||||
}
|
||||
|
||||
private void run(String sql) {
|
||||
QueryExecutionContext context = new QueryExecutionContext();
|
||||
context.setDatabase(database);
|
||||
String id = RequestScopes.callAs(ACCOUNT, REGION, () -> athena.startQueryExecution(sql, "primary", context,
|
||||
new ResultConfiguration("s3://" + bucket + "/results/")));
|
||||
QueryExecution execution = await().atMost(Duration.ofSeconds(60)).pollInterval(Duration.ofMillis(100))
|
||||
.until(() -> RequestScopes.callAs(ACCOUNT, REGION, () -> athena.getQueryExecution(id)),
|
||||
found -> found.getStatus().getState() != QueryExecutionState.RUNNING
|
||||
&& found.getStatus().getState() != QueryExecutionState.QUEUED);
|
||||
if (execution.getStatus().getState() != QueryExecutionState.SUCCEEDED) {
|
||||
fail(sql + " -> " + execution.getStatus().getState() + ": " + execution.getStatus().getStateChangeReason());
|
||||
}
|
||||
}
|
||||
|
||||
private List<Map<String, String>> rows(String sql) {
|
||||
return RequestScopes.callAs(ACCOUNT, REGION, () -> duck.query(TrinoSqlCompatibility.translate(sql),
|
||||
TrinoSqlCompatibility.FUNCTION_MACROS + ddlBuilder.build(database, sql), ACCOUNT)).stream()
|
||||
.map(found -> {
|
||||
Map<String, String> row = new TreeMap<>();
|
||||
found.forEach((column, value) -> row.put(column, String.valueOf(value)));
|
||||
return row;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
private static Map<String, String> row(String... columnsAndValues) {
|
||||
Map<String, String> row = new TreeMap<>();
|
||||
for (int i = 0; i < columnsAndValues.length; i += 2) {
|
||||
row.put(columnsAndValues[i], columnsAndValues[i + 1]);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
private String metadataLocation(String table) {
|
||||
return RequestScopes.callAs(ACCOUNT, REGION,
|
||||
() -> glue.getTable(database, table).getParameters().get("metadata_location"));
|
||||
}
|
||||
|
||||
private JsonNode loadTable(String table) {
|
||||
return RequestScopes.callAs(ACCOUNT, REGION, () -> catalog.loadTable(":", database, table, null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerReachableEndpoint;
|
||||
import io.floci.aws.services.floci.duck.FlociDuckClient;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.iceberg.GlueIcebergCatalog;
|
||||
import io.floci.aws.services.glue.iceberg.GlueIcebergTokens;
|
||||
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 io.floci.aws.services.s3.model.S3Object;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Which statements write an Iceberg table and how they are pointed at the attached catalog, which Iceberg tables
|
||||
* {@code CREATE TABLE} accepts, and which snapshots and files {@code VACUUM} keeps.
|
||||
*/
|
||||
class AthenaIcebergStatementsTest {
|
||||
|
||||
private static final long NOW = 1_000_000_000L;
|
||||
private static final long DAY = Duration.ofDays(1).toMillis();
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private GlueIcebergCatalog catalog;
|
||||
private GlueService glue;
|
||||
private S3Service s3;
|
||||
private GlueIcebergTokens tokens;
|
||||
private FlociDuckClient duck;
|
||||
private AthenaIcebergStatements statements;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
catalog = Mockito.mock(GlueIcebergCatalog.class);
|
||||
glue = Mockito.mock(GlueService.class);
|
||||
s3 = Mockito.mock(S3Service.class);
|
||||
tokens = Mockito.mock(GlueIcebergTokens.class);
|
||||
duck = Mockito.mock(FlociDuckClient.class);
|
||||
ContainerReachableEndpoint endpoint = Mockito.mock(ContainerReachableEndpoint.class);
|
||||
when(endpoint.baseUrl()).thenReturn("http://floci:4566");
|
||||
statements = new AthenaIcebergStatements(catalog, glue, s3, tokens, endpoint, duck,
|
||||
new RegionResolver("eu-west-1", "111122223333"), mapper,
|
||||
Clock.fixed(Instant.ofEpochMilli(NOW), ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
private void glueTable(String database, String name, boolean iceberg) {
|
||||
Table table = new Table();
|
||||
table.setName(name);
|
||||
Map<String, String> parameters = new HashMap<>();
|
||||
if (iceberg) {
|
||||
parameters.put("table_type", "ICEBERG");
|
||||
parameters.put("metadata_location", "s3://lake/" + name + "/metadata/00000-a.metadata.json");
|
||||
}
|
||||
table.setParameters(parameters);
|
||||
when(glue.getTable(database, name)).thenReturn(table);
|
||||
}
|
||||
|
||||
// ─── Writes ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void theTargetOfEachWritingStatementIsFoundPastCommentsAndQuoting() {
|
||||
String insert = "-- load\n/* batch */ insert into Lake . \"Ev\"\"ents\" (a) SELECT 1";
|
||||
AthenaIcebergStatements.Target target = AthenaIcebergStatements.target(insert);
|
||||
assertEquals("lake", target.database());
|
||||
assertEquals("ev\"ents", target.table());
|
||||
assertEquals("Lake . \"Ev\"\"ents\"", insert.substring(target.start(), target.end()));
|
||||
|
||||
assertEquals(new AthenaIcebergStatements.Target(null, "events", 12, 18),
|
||||
AthenaIcebergStatements.target("DELETE FROM events WHERE id = 1"));
|
||||
AthenaIcebergStatements.Target merge = AthenaIcebergStatements.target(
|
||||
"MERGE INTO awsdatacatalog.lake.events AS t USING src s ON t.id = s.id WHEN MATCHED THEN DELETE");
|
||||
assertEquals("lake", merge.database());
|
||||
assertEquals("events", merge.table());
|
||||
assertEquals("events", AthenaIcebergStatements.target("UPDATE events SET a = 1").table());
|
||||
|
||||
assertNull(AthenaIcebergStatements.target("UPDATE other_catalog.lake.events SET a = 1"));
|
||||
assertNull(AthenaIcebergStatements.target("SELECT * FROM events"));
|
||||
assertNull(AthenaIcebergStatements.target("INSERT INTO"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteToAnIcebergTableGoesThroughTheAttachedCatalogWithATokenForTheCallingAccount() {
|
||||
glueTable("lake", "events", true);
|
||||
when(tokens.mint(eq("111122223333"), eq("eu-west-1"), any())).thenReturn("tok'en");
|
||||
|
||||
AthenaIcebergStatements.IcebergWrite write = statements.write(
|
||||
"INSERT INTO events SELECT * FROM staging", "lake");
|
||||
|
||||
assertEquals("INSERT INTO glue_iceberg.\"lake\".\"events\" SELECT * FROM staging", write.query());
|
||||
assertEquals("""
|
||||
INSTALL iceberg; LOAD iceberg;
|
||||
ATTACH '111122223333' AS glue_iceberg (TYPE iceberg, ENDPOINT 'http://floci:4566/iceberg', \
|
||||
AUTHORIZATION_TYPE 'oauth2', TOKEN 'tok''en', ACCESS_DELEGATION_MODE 'none');
|
||||
""", write.setupSql());
|
||||
statements.finished(write);
|
||||
verify(tokens).revoke("tok'en");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWriteToAHiveTableOrAMissingOneIsLeftAlone() {
|
||||
glueTable("lake", "hive_events", false);
|
||||
when(glue.getTable("lake", "missing")).thenThrow(new AwsException("EntityNotFoundException", "missing", 400));
|
||||
|
||||
assertNull(statements.write("INSERT INTO lake.hive_events VALUES (1)", "default"));
|
||||
assertNull(statements.write("INSERT INTO missing VALUES (1)", "lake"));
|
||||
assertNull(statements.write("SELECT 1", "lake"));
|
||||
verify(tokens, never()).mint(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
// ─── CREATE TABLE ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static AthenaHiveDdl.CreateIcebergTable create(boolean ifNotExists, Map<String, String> properties) {
|
||||
return new AthenaHiveDdl.CreateIcebergTable(new AthenaHiveDdl.TableRef(null, "events"), ifNotExists,
|
||||
List.of(new Column("id", "bigint")), List.of(), "s3://lake/events/", properties);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableAsksTheCatalogForAVersion2TableWithItsProperties() {
|
||||
when(glue.getTable("lake", "events")).thenThrow(new AwsException("EntityNotFoundException", "missing", 400));
|
||||
|
||||
statements.createTable("lake", create(false, Map.of("Format", "parquet",
|
||||
"vacuum_max_snapshot_age_seconds", "60")));
|
||||
|
||||
ArgumentCaptor<JsonNode> request = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(catalog).createTable(eq(":"), eq("lake"), request.capture());
|
||||
assertEquals("events", request.getValue().path("name").asText());
|
||||
assertEquals("s3://lake/events/", request.getValue().path("location").asText());
|
||||
assertEquals(Map.of("format", "parquet", "vacuum_max_snapshot_age_seconds", "60", "format-version", "2"),
|
||||
mapper.convertValue(request.getValue().path("properties"), Map.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableRefusesPropertiesAthenaDoesNotAllowAndFormatsFlociCannotWrite() {
|
||||
AwsException unknown = assertThrows(AwsException.class,
|
||||
() -> statements.createTable("lake", create(false, Map.of("write.format.default", "parquet"))));
|
||||
assertTrue(unknown.getMessage().contains("write.format.default"), unknown.getMessage());
|
||||
|
||||
AwsException orc = assertThrows(AwsException.class,
|
||||
() -> statements.createTable("lake", create(false, Map.of("format", "orc"))));
|
||||
assertEquals("InvalidRequestException", orc.getErrorCode());
|
||||
verify(catalog, never()).createTable(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTableIfNotExistsLeavesAnExistingTableAlone() {
|
||||
glueTable("lake", "events", true);
|
||||
|
||||
statements.createTable("lake", create(true, Map.of()));
|
||||
|
||||
verify(catalog, never()).createTable(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
// ─── VACUUM ───────────────────────────────────────────────────────────────────
|
||||
|
||||
private static String snapshot(long id, Long parent, long timestamp) {
|
||||
return "{\"snapshot-id\":" + id + (parent == null ? "" : ",\"parent-snapshot-id\":" + parent)
|
||||
+ ",\"timestamp-ms\":" + timestamp + ",\"manifest-list\":\"s3://lake/events/metadata/snap-" + id
|
||||
+ ".avro\"}";
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumKeepsTagsTheNewestSnapshotsOfEachBranchAndAnythingNewerThanTheCutoff() throws Exception {
|
||||
JsonNode metadata = mapper.readTree("{\"snapshots\":[" + String.join(",",
|
||||
snapshot(1, null, 100), snapshot(2, 1L, 200), snapshot(3, 2L, 300), snapshot(4, null, 50),
|
||||
snapshot(5, null, 400)) + "],\"refs\":{\"main\":{\"snapshot-id\":3,\"type\":\"branch\"},"
|
||||
+ "\"v1\":{\"snapshot-id\":1,\"type\":\"tag\"}}}");
|
||||
|
||||
assertEquals(Set.of(3L, 1L, 5L), AthenaIcebergStatements.retainedSnapshots(metadata, 250, 1));
|
||||
assertEquals(Set.of(3L, 2L, 1L, 5L), AthenaIcebergStatements.retainedSnapshots(metadata, 250, 2));
|
||||
assertEquals(Set.of(1L, 2L, 3L, 4L, 5L), AthenaIcebergStatements.retainedSnapshots(metadata, 0, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumExpiresOldSnapshotsAndDeletesOnlyFilesNothingRetainedReferences() throws Exception {
|
||||
glueTable("lake", "events", true);
|
||||
long old = NOW - 10 * DAY;
|
||||
String base = "s3://lake/events/metadata/";
|
||||
ObjectNode before = (ObjectNode) mapper.readTree("{\"table-uuid\":\"u\",\"location\":\"s3://lake/events\","
|
||||
+ "\"properties\":{},\"snapshots\":[" + snapshot(1, null, old) + "," + snapshot(2, 1L, old + 1)
|
||||
+ "],\"refs\":{\"main\":{\"snapshot-id\":2,\"type\":\"branch\"}},\"metadata-log\":[]}");
|
||||
ObjectNode after = before.deepCopy();
|
||||
after.withArray("snapshots").remove(0);
|
||||
// A retained manifest list and a statistics file named with the other S3 schemes are still referenced.
|
||||
((ObjectNode) after.withArray("snapshots").get(0)).put("manifest-list",
|
||||
"s3a://lake/events/metadata/snap-2.avro");
|
||||
after.withArray("statistics").addObject().put("snapshot-id", 2)
|
||||
.put("statistics-path", "s3n://lake/events/metadata/stats-2.puffin");
|
||||
after.withArray("metadata-log").addObject().put("metadata-file", base + "00001-b.metadata.json");
|
||||
when(catalog.loadTable(":", "lake", "events", null)).thenReturn(loaded(base + "00001-b.metadata.json",
|
||||
before));
|
||||
when(catalog.commitTable(eq(":"), eq("lake"), eq("events"), any()))
|
||||
.thenReturn(loaded(base + "00002-c.metadata.json", after));
|
||||
when(s3.getBucketOwnerAccountId("lake")).thenReturn("111122223333");
|
||||
when(duck.query(anyString(), anyString(), eq("111122223333"))).thenReturn(List.of(Map.of(
|
||||
"manifest_path", "s3a://lake/events/metadata/m2.avro",
|
||||
"file_path", "s3://lake/events/data/kept.parquet")));
|
||||
when(s3.listObjectsWithPrefixes(eq("lake"), eq("events/"), isNull(), anyInt(), isNull(), isNull()))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(
|
||||
object("events/metadata/00000-a.metadata.json", old),
|
||||
object("events/metadata/00001-b.metadata.json", old),
|
||||
object("events/metadata/00002-c.metadata.json", NOW),
|
||||
object("events/metadata/snap-1.avro", old),
|
||||
object("events/metadata/snap-2.avro", old),
|
||||
object("events/metadata/stats-2.puffin", old),
|
||||
object("events/metadata/m1.avro", old),
|
||||
object("events/metadata/m2.avro", old),
|
||||
object("events/data/expired.parquet", old),
|
||||
object("events/data/kept.parquet", old),
|
||||
object("events/data/in-flight.parquet", NOW - 1000)), List.of(), false, null));
|
||||
|
||||
statements.vacuum(new AthenaHiveDdl.TableRef("lake", "events"), "default");
|
||||
|
||||
ArgumentCaptor<JsonNode> commit = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(catalog).commitTable(eq(":"), eq("lake"), eq("events"), commit.capture());
|
||||
assertEquals(mapper.readTree("""
|
||||
{"requirements":[{"type":"assert-table-uuid","uuid":"u"},
|
||||
{"type":"assert-ref-snapshot-id","ref":"main","snapshot-id":2}],
|
||||
"updates":[{"action":"remove-snapshots","snapshot-ids":[1]}]}
|
||||
"""), mapper.readTree(commit.getValue().toString()));
|
||||
ArgumentCaptor<String> deleted = ArgumentCaptor.forClass(String.class);
|
||||
verify(s3, Mockito.atLeastOnce()).deleteObject(eq("lake"), deleted.capture());
|
||||
assertEquals(Set.of("events/metadata/00000-a.metadata.json", "events/metadata/snap-1.avro",
|
||||
"events/metadata/m1.avro", "events/data/expired.parquet"), Set.copyOf(deleted.getAllValues()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDroppedIcebergTablesFilesAreDeletedOnlyFromTheCallingAccountsBucket() {
|
||||
when(s3.getBucketOwnerAccountId("ours")).thenReturn("111122223333");
|
||||
when(s3.getBucketOwnerAccountId("theirs")).thenReturn("999988887777");
|
||||
when(s3.listObjectsWithPrefixes(eq("ours"), eq("events/"), isNull(), anyInt(), isNull(), isNull()))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(object("events/data/a.parquet", NOW)), List.of(),
|
||||
false, null));
|
||||
|
||||
statements.purge(tableAt("s3://ours/events"));
|
||||
statements.purge(tableAt("s3://theirs/events/"));
|
||||
|
||||
verify(s3).deleteObject("ours", "events/data/a.parquet");
|
||||
verify(s3, never()).listObjectsWithPrefixes(eq("theirs"), any(), any(), anyInt(), any(), any());
|
||||
}
|
||||
|
||||
private static Table tableAt(String location) {
|
||||
Table table = new Table();
|
||||
StorageDescriptor descriptor = new StorageDescriptor();
|
||||
descriptor.setLocation(location);
|
||||
table.setStorageDescriptor(descriptor);
|
||||
return table;
|
||||
}
|
||||
|
||||
@Test
|
||||
void whileFlocisOwnWriteToTheTableRunsVacuumLeavesItsFilesForTheNextRun() throws Exception {
|
||||
glueTable("lake", "events", true);
|
||||
when(tokens.mint(anyString(), anyString(), any())).thenReturn("t");
|
||||
ObjectNode metadata = (ObjectNode) mapper.readTree("{\"table-uuid\":\"u\",\"location\":\"s3://lake/events\","
|
||||
+ "\"properties\":{},\"snapshots\":[],\"refs\":{},\"metadata-log\":[]}");
|
||||
when(catalog.loadTable(":", "lake", "events", null)).thenReturn(loaded(
|
||||
"s3://lake/events/metadata/00000-a.metadata.json", metadata));
|
||||
when(s3.getBucketOwnerAccountId("lake")).thenReturn("111122223333");
|
||||
when(s3.listObjectsWithPrefixes(eq("lake"), eq("events/"), isNull(), anyInt(), isNull(), isNull()))
|
||||
.thenReturn(new S3Service.ListObjectsResult(List.of(
|
||||
object("events/data/staged.parquet", NOW - 10 * DAY)), List.of(), false, null));
|
||||
|
||||
AthenaIcebergStatements.IcebergWrite write = statements.write("INSERT INTO events VALUES (1)", "lake");
|
||||
statements.vacuum(new AthenaHiveDdl.TableRef("lake", "events"), "default");
|
||||
verify(s3, never()).deleteObject(anyString(), anyString());
|
||||
|
||||
statements.finished(write);
|
||||
statements.vacuum(new AthenaHiveDdl.TableRef("lake", "events"), "default");
|
||||
verify(s3).deleteObject("lake", "events/data/staged.parquet");
|
||||
}
|
||||
|
||||
@Test
|
||||
void vacuumOfAHiveTableIsRefused() {
|
||||
glueTable("lake", "hive_events", false);
|
||||
|
||||
AwsException e = assertThrows(AwsException.class,
|
||||
() -> statements.vacuum(new AthenaHiveDdl.TableRef(null, "hive_events"), "lake"));
|
||||
|
||||
assertTrue(e.getMessage().contains("only for Apache Iceberg tables"), e.getMessage());
|
||||
}
|
||||
|
||||
private ObjectNode loaded(String metadataLocation, JsonNode metadata) {
|
||||
ObjectNode result = mapper.createObjectNode();
|
||||
result.put("metadata-location", metadataLocation);
|
||||
result.set("metadata", metadata);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static S3Object object(String key, long lastModified) {
|
||||
S3Object object = new S3Object();
|
||||
object.setKey(key);
|
||||
object.setLastModified(Instant.ofEpochMilli(lastModified));
|
||||
return object;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestScopes;
|
||||
import io.floci.aws.core.storage.StorageFactory;
|
||||
@@ -28,7 +27,6 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A query runs on a worker after the call that started it has returned, with no request scope of its own;
|
||||
@@ -68,7 +66,7 @@ class AthenaQueryScopeTest {
|
||||
return null;
|
||||
}).when(duckClient).execute(anyString(), any(), any(), any());
|
||||
AthenaService athena = new AthenaService(storageFactory, duckClient, glueService, mock(S3Service.class),
|
||||
realQueries(), vertx, ddlBuilder, regionResolver);
|
||||
AthenaTestConfigs.realQueries(), vertx, ddlBuilder, regionResolver, mock(AthenaIcebergStatements.class));
|
||||
try {
|
||||
String expected = RequestScopes.callAs(account, REGION, () -> {
|
||||
glueService.createDatabase(new Database(database));
|
||||
@@ -90,15 +88,4 @@ class AthenaQueryScopeTest {
|
||||
RequestScopes.runAs(account, REGION, () -> glueService.deleteDatabase(database));
|
||||
}
|
||||
}
|
||||
|
||||
/** A configuration under which a query is handed to the duck client rather than answered at once. */
|
||||
private static EmulatorConfig realQueries() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.AthenaServiceConfig athena = mock(EmulatorConfig.AthenaServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.athena()).thenReturn(athena);
|
||||
when(athena.mock()).thenReturn(false);
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ class AthenaServiceTest {
|
||||
when(athena.mock()).thenReturn(false);
|
||||
|
||||
service = new AthenaService(storageFactory, duckClient, glueService, s3Service,
|
||||
config, vertx, ddlBuilder, mock(RegionResolver.class));
|
||||
config, vertx, ddlBuilder, mock(RegionResolver.class), mock(AthenaIcebergStatements.class));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package io.floci.aws.services.athena;
|
||||
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Configurations Athena tests construct {@link AthenaService} with. */
|
||||
final class AthenaTestConfigs {
|
||||
|
||||
private AthenaTestConfigs() {
|
||||
}
|
||||
|
||||
/** A configuration under which a query is handed to the query engine rather than answered at once. */
|
||||
static EmulatorConfig realQueries() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
EmulatorConfig.AthenaServiceConfig athena = mock(EmulatorConfig.AthenaServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.athena()).thenReturn(athena);
|
||||
when(athena.mock()).thenReturn(false);
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -2,17 +2,14 @@ package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.glue.model.Database;
|
||||
import io.floci.aws.services.glue.model.Table;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
@@ -33,7 +30,7 @@ import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** The catalog's commit paths when Glue refuses the write, and who it answers under IAM enforcement. */
|
||||
/** The catalog's commit paths when Glue refuses the write. */
|
||||
class GlueIcebergCatalogTest {
|
||||
|
||||
private static final String CREATE_COMMIT = """
|
||||
@@ -50,18 +47,14 @@ class GlueIcebergCatalogTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private GlueService glue;
|
||||
private S3Service s3;
|
||||
private EmulatorConfig config;
|
||||
private RequestContext requestContext;
|
||||
private GlueIcebergCatalog catalog;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
glue = Mockito.mock(GlueService.class);
|
||||
s3 = Mockito.mock(S3Service.class);
|
||||
config = Mockito.mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
|
||||
requestContext = Mockito.mock(RequestContext.class);
|
||||
catalog = new GlueIcebergCatalog(glue, s3, new RegionResolver("us-east-1", "000000000000"), mapper, config,
|
||||
requestContext, Clock.fixed(Instant.ofEpochMilli(10_000L), ZoneOffset.UTC));
|
||||
catalog = new GlueIcebergCatalog(glue, s3, new RegionResolver("us-east-1", "000000000000"), mapper,
|
||||
Clock.fixed(Instant.ofEpochMilli(10_000L), ZoneOffset.UTC));
|
||||
Database database = new Database("lake");
|
||||
database.setLocationUri("s3://lake-bucket/lake");
|
||||
when(glue.getDatabase("lake")).thenReturn(database);
|
||||
@@ -140,28 +133,4 @@ class GlueIcebergCatalogTest {
|
||||
String written = writtenMetadataKey();
|
||||
verify(s3).deleteObject("lake-bucket", written);
|
||||
}
|
||||
|
||||
@Test
|
||||
void underIamEnforcementOnlyRootCredentialsAndFlocisOwnCallersReachTheCatalog() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
when(requestContext.getAccountId()).thenReturn("000000000000");
|
||||
|
||||
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
|
||||
IcebergRestException refused = assertThrows(IcebergRestException.class, () -> catalog.config(null));
|
||||
assertEquals(403, refused.code());
|
||||
assertEquals("ForbiddenException", refused.type());
|
||||
|
||||
for (String rootOrInternal : new String[] {"test", "000000000000", null}) {
|
||||
when(requestContext.getAccessKeyId()).thenReturn(rootOrInternal);
|
||||
assertEquals("catalogs/:", catalog.config(null).path("overrides").path("prefix").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutEnforcementAnyCallerReachesTheCatalog() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(false);
|
||||
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
|
||||
|
||||
assertEquals("catalogs/:", catalog.config(null).path("overrides").path("prefix").asText());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package io.floci.aws.services.glue.iceberg;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.RequestContext;
|
||||
import io.floci.aws.services.glue.GlueService;
|
||||
import io.floci.aws.services.s3.S3Service;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** Who the endpoint answers under IAM enforcement. */
|
||||
class GlueIcebergControllerTest {
|
||||
|
||||
private EmulatorConfig config;
|
||||
private RequestContext requestContext;
|
||||
private GlueIcebergController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
config = Mockito.mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS);
|
||||
requestContext = Mockito.mock(RequestContext.class);
|
||||
GlueIcebergCatalog catalog = new GlueIcebergCatalog(Mockito.mock(GlueService.class),
|
||||
Mockito.mock(S3Service.class), new RegionResolver("us-east-1", "000000000000"), new ObjectMapper());
|
||||
controller = new GlueIcebergController(catalog, config, requestContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
void underIamEnforcementOnlyRootCredentialsAndFlocisOwnCallersReachTheCatalog() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
when(requestContext.getAccountId()).thenReturn("000000000000");
|
||||
|
||||
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
|
||||
IcebergRestException refused = assertThrows(IcebergRestException.class, () -> controller.getConfig(null));
|
||||
assertEquals(403, refused.code());
|
||||
assertEquals("ForbiddenException", refused.type());
|
||||
|
||||
for (String rootOrInternal : new String[] {"test", "000000000000", null}) {
|
||||
when(requestContext.getAccessKeyId()).thenReturn(rootOrInternal);
|
||||
assertEquals("catalogs/:", controller.getConfig(null).path("overrides").path("prefix").asText());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutEnforcementAnyCallerReachesTheCatalog() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(false);
|
||||
when(requestContext.getAccessKeyId()).thenReturn("AKIAEXAMPLEUSER0001");
|
||||
|
||||
assertEquals("catalogs/:", controller.getConfig(null).path("overrides").path("prefix").asText());
|
||||
}
|
||||
}
|
||||
+28
-1
@@ -7,18 +7,22 @@ import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* Under IAM enforcement, no rule maps the Glue Iceberg REST endpoint's routes to the Glue actions AWS checks for them
|
||||
* yet, so the endpoint refuses an IAM principal, even one allowed every Glue action, rather than let it through
|
||||
* unchecked; the account's root credentials still reach it.
|
||||
* unchecked; the account's root credentials still reach it, and so does a token Floci minted for its query engine,
|
||||
* as the account and Region it was minted for.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(SignedIamEnforcementProfile.class)
|
||||
@@ -27,6 +31,9 @@ class GlueIcebergIamIntegrationTest {
|
||||
@TestHTTPResource("/")
|
||||
URI endpoint;
|
||||
|
||||
@Inject
|
||||
GlueIcebergTokens tokens;
|
||||
|
||||
@Test
|
||||
void anIamPrincipalIsRefusedAndRootCredentialsAreAnswered() throws Exception {
|
||||
String allowEverything = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
@@ -40,6 +47,26 @@ class GlueIcebergIamIntegrationTest {
|
||||
.body("overrides.prefix", equalTo("catalogs/:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMintedTokenActsAsItsAccountUntilRevokedAndAnUnknownOneReachesNothing() {
|
||||
String token = tokens.mint("111122223333", "eu-west-1", Duration.ofMinutes(5));
|
||||
try {
|
||||
bearer(token, "/iceberg/v1/config?warehouse=111122223333").then().statusCode(200)
|
||||
.body("overrides.prefix", equalTo("catalogs/111122223333"));
|
||||
bearer(token, "/iceberg/v1/config?warehouse=000000000000").then().statusCode(400)
|
||||
.body("error.type", equalTo("BadRequestException"));
|
||||
} finally {
|
||||
tokens.revoke(token);
|
||||
}
|
||||
bearer(token, "/iceberg/v1/config?warehouse=111122223333").then().statusCode(not(equalTo(200)));
|
||||
bearer("not-a-minted-token", "/iceberg/v1/config").then().statusCode(not(equalTo(200)));
|
||||
}
|
||||
|
||||
private Response bearer(String token, String path) {
|
||||
return given().urlEncodingEnabled(false).header("Authorization", "Bearer " + token)
|
||||
.get(endpoint.resolve(path));
|
||||
}
|
||||
|
||||
private Response get(AwsRequestSigner signer, String path) throws Exception {
|
||||
URI uri = endpoint.resolve(path);
|
||||
return given().urlEncodingEnabled(false).headers(signer.headersFor("GET", uri, Map.of(), new byte[0]))
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
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 org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** The Iceberg {@code CreateTableRequest} an Athena Iceberg {@code CREATE TABLE} describes. */
|
||||
class IcebergSchemasTest {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private static Column column(String name, String type) {
|
||||
return new Column(name, type);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hiveTypesBecomeIcebergTypesWithTopLevelIdsFirstThenNestedOnesInOrder() throws Exception {
|
||||
Column id = column("id", "bigint");
|
||||
id.setComment("the id");
|
||||
JsonNode request = IcebergSchemas.createTableRequest("events", List.of(id,
|
||||
column("tags", "array<string>"),
|
||||
column("attrs", "map<string,int>"),
|
||||
column("info", "struct<a:int,b:struct<c:varchar(10)>>"),
|
||||
column("price", "decimal(10,2)"),
|
||||
column("ts", "timestamp"),
|
||||
column("flag", "boolean")), List.of(), "s3://lake/events", Map.of("format-version", "2"));
|
||||
|
||||
assertEquals(mapper.readTree("""
|
||||
{"type":"struct","schema-id":0,"fields":[
|
||||
{"id":1,"name":"id","required":false,"type":"long","doc":"the id"},
|
||||
{"id":2,"name":"tags","required":false,"type":{"type":"list","element-id":8,"element":"string",
|
||||
"element-required":false}},
|
||||
{"id":3,"name":"attrs","required":false,"type":{"type":"map","key-id":9,"value-id":10,
|
||||
"key":"string","value":"int","value-required":false}},
|
||||
{"id":4,"name":"info","required":false,"type":{"type":"struct","fields":[
|
||||
{"id":11,"name":"a","required":false,"type":"int"},
|
||||
{"id":12,"name":"b","required":false,"type":{"type":"struct","fields":[
|
||||
{"id":13,"name":"c","required":false,"type":"string"}]}}]}},
|
||||
{"id":5,"name":"price","required":false,"type":"decimal(10, 2)"},
|
||||
{"id":6,"name":"ts","required":false,"type":"timestamp"},
|
||||
{"id":7,"name":"flag","required":false,"type":"boolean"}]}
|
||||
"""), request.path("schema"));
|
||||
assertEquals("events", request.path("name").asText());
|
||||
assertEquals("s3://lake/events", request.path("location").asText());
|
||||
assertEquals("2", request.path("properties").path("format-version").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void partitionedByEntriesBecomeASpecOfTransformsNamedAsIcebergNamesThem() throws Exception {
|
||||
JsonNode request = IcebergSchemas.createTableRequest("events", List.of(column("id", "bigint"),
|
||||
column("category", "string"), column("ts", "timestamp"), column("name", "string")), List.of(
|
||||
new IcebergSchemas.PartitionField("identity", null, "category"),
|
||||
new IcebergSchemas.PartitionField("bucket", 16, "id"),
|
||||
new IcebergSchemas.PartitionField("day", null, "ts"),
|
||||
new IcebergSchemas.PartitionField("truncate", 4, "NAME")), null, Map.of());
|
||||
|
||||
assertEquals(mapper.readTree("""
|
||||
{"spec-id":0,"fields":[
|
||||
{"name":"category","transform":"identity","source-id":2,"field-id":1000},
|
||||
{"name":"id_bucket","transform":"bucket[16]","source-id":1,"field-id":1001},
|
||||
{"name":"ts_day","transform":"day","source-id":3,"field-id":1002},
|
||||
{"name":"name_trunc","transform":"truncate[4]","source-id":4,"field-id":1003}]}
|
||||
"""), request.path("partition-spec"));
|
||||
assertTrue(request.path("location").isMissingNode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void typesAthenaDoesNotSupportOnIcebergTablesAreRefused() {
|
||||
for (String type : List.of("tinyint", "smallint", "char(3)")) {
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
|
||||
() -> IcebergSchemas.createTableRequest("t", List.of(column("c", type)), List.of(), null,
|
||||
Map.of()));
|
||||
assertTrue(e.getMessage().contains("not supported for Iceberg tables"), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartitionTransformWithoutItsWidthOrOnAColumnTypeItDoesNotTakeIsRefused() {
|
||||
List<Column> columns = List.of(column("id", "bigint"), column("name", "string"), column("ts", "timestamp"),
|
||||
column("dt", "date"));
|
||||
for (IcebergSchemas.PartitionField partition : List.of(
|
||||
new IcebergSchemas.PartitionField("bucket", null, "id"),
|
||||
new IcebergSchemas.PartitionField("bucket", 0, "id"),
|
||||
new IcebergSchemas.PartitionField("truncate", -1, "name"),
|
||||
new IcebergSchemas.PartitionField("day", 4, "ts"),
|
||||
new IcebergSchemas.PartitionField("identity", 2, "id"),
|
||||
new IcebergSchemas.PartitionField("day", null, "name"),
|
||||
new IcebergSchemas.PartitionField("hour", null, "dt"),
|
||||
new IcebergSchemas.PartitionField("truncate", 4, "ts"))) {
|
||||
assertThrows(IllegalArgumentException.class, () -> IcebergSchemas.createTableRequest("t", columns,
|
||||
List.of(partition), null, Map.of()), partition.toString());
|
||||
}
|
||||
JsonNode spec = IcebergSchemas.createTableRequest("t", columns, List.of(
|
||||
new IcebergSchemas.PartitionField("month", null, "dt"),
|
||||
new IcebergSchemas.PartitionField("bucket", 8, "name")), null, Map.of()).path("partition-spec");
|
||||
assertEquals("month", spec.path("fields").get(0).path("transform").asText());
|
||||
assertEquals("bucket[8]", spec.path("fields").get(1).path("transform").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPartitionOfAnUnknownColumnOrTransformIsRefused() {
|
||||
List<Column> columns = List.of(column("id", "bigint"));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () -> IcebergSchemas.createTableRequest("t", columns,
|
||||
List.of(new IcebergSchemas.PartitionField("identity", null, "missing")), null, Map.of()));
|
||||
assertThrows(IllegalArgumentException.class, () -> IcebergSchemas.createTableRequest("t", columns,
|
||||
List.of(new IcebergSchemas.PartitionField("week", null, "id")), null, Map.of()));
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,27 @@ class IcebergTableMetadataTest {
|
||||
assertEquals(-1L, other.path("current-snapshot-id").asLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRemovedSnapshotsStatisticsFilesGoWithIt() throws Exception {
|
||||
ObjectNode metadata = created();
|
||||
IcebergTableMetadata.apply(metadata, snapshotCommit(7L, null, 1).path("updates"), 6_000L);
|
||||
IcebergTableMetadata.apply(metadata, snapshotCommit(8L, 7L, 2).path("updates"), 6_100L);
|
||||
IcebergTableMetadata.apply(metadata, json("""
|
||||
[{"action":"set-statistics","statistics":{"snapshot-id":7,"statistics-path":"s3://b/t/7.stats",
|
||||
"file-size-in-bytes":1,"file-footer-size-in-bytes":1,"blob-metadata":[]}},
|
||||
{"action":"set-statistics","statistics":{"snapshot-id":8,"statistics-path":"s3://b/t/8.stats",
|
||||
"file-size-in-bytes":1,"file-footer-size-in-bytes":1,"blob-metadata":[]}},
|
||||
{"action":"set-partition-statistics","partition-statistics":{"snapshot-id":7,
|
||||
"statistics-path":"s3://b/t/7.pstats","file-size-in-bytes":1}}]
|
||||
"""), 6_200L);
|
||||
|
||||
IcebergTableMetadata.apply(metadata, json("[{\"action\":\"remove-snapshots\",\"snapshot-ids\":[7]}]"), 7_000L);
|
||||
|
||||
assertEquals(1, metadata.path("statistics").size());
|
||||
assertEquals(8L, metadata.path("statistics").get(0).path("snapshot-id").asLong());
|
||||
assertTrue(metadata.path("partition-statistics").isEmpty(), metadata.path("partition-statistics").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSchemaSpecOrSortOrderIdTheTableDoesNotHaveIsRefused() throws Exception {
|
||||
ObjectNode metadata = created();
|
||||
|
||||
Reference in new issue
Block a user