Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#12546] improvement(trino-connector): Report catalog registration status through system tables (#12547)

Yuhui67a06e60dd9e
diff --git a/docs/trino-connector/supported-catalog.md b/docs/trino-connector/supported-catalog.md
index 80a0380f30..0c2d547eeb 100644
--- a/docs/trino-connector/supported-catalog.md
+++ b/docs/trino-connector/supported-catalog.md
@@ -80,6 +80,68 @@ The result is like:
gt_hive | hive | {gravitino.bypass.hive.metastore.client.capability.check=false, metastore.uris=thrift://trino-ci-hive:9083}
```
+Check catalog registration status:
+
+`gravitino.system.catalog` lists the relational catalogs the Gravitino server knows about, minus any
+that match `gravitino.trino.skip-catalog-patterns`. A catalog listed there is not necessarily usable
+in Trino: registering it is a separate step that can fail. `gravitino.system.catalog_status` covers
+every catalog the connector considered, including the ones `catalog` filters out, and says why each
+one is or is not registered.
+
+```sql
+select catalog_name, status, last_error from gravitino.system.catalog_status;
+```
+
+The result is like:
+
+```test
+ catalog_name | status | last_error
+--------------+------------+-------------------------------------------------
+ gt_hive | REGISTERED | NULL
+ gt_iceberg | FAILED | Access Denied: Cannot create catalog gt_iceberg
+ gt_files | UNSUPPORTED| Only relational catalogs are supported, the catalog type is FILESET
+```
+
+| Column | Description |
+|----------------------|----------------------------------------------------------------------------------------------------------------------------------------|
+| `metalake` | The metalake the catalog belongs to. |
+| `catalog_name` | The name of the catalog in Gravitino. |
+| `trino_catalog_name` | The name the catalog is registered under in Trino, as it appears in `SHOW CATALOGS`. |
+| `provider` | The catalog provider, for example `hive` or `lakehouse-iceberg`. |
+| `status` | One of `REGISTERED`, `FAILED`, `UNSUPPORTED` or `SKIPPED`. See the table below. |
+| `last_error` | The reason the catalog is not registered, `NULL` when it is. |
+| `last_attempt_time` | When the catalog was last processed, as an ISO-8601 UTC timestamp. |
+| `last_success_time` | When the catalog was last registered successfully, `NULL` if it never was. Retained when a catalog later fails or becomes unsupported. |
+| `failure_count` | The number of consecutive failed attempts, `0` when the last attempt succeeded. |
+
+| Status | Meaning |
+|---------------|-------------------------------------------------------------------------------------------------|
+| `REGISTERED` | The catalog is registered in Trino and appears in `SHOW CATALOGS`. |
+| `FAILED` | The last registration attempt failed, `last_error` carries the reason. Retried every refresh. |
+| `UNSUPPORTED` | The catalog is not relational, or its provider is not supported by the connector. |
+| `SKIPPED` | The catalog matches `gravitino.trino.skip-catalog-patterns` and is deliberately not registered. |
+
+A failure that stops the connector before it can list catalogs at all, such as an unreachable
+Gravitino server, leaves no row to attach itself to. `gravitino.system.load_status` reports the
+health of the loop itself, and always has exactly one row.
+
+```sql
+select * from gravitino.system.load_status;
+```
+
+| Column | Description |
+|------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| `trino_reachable` | Whether the Trino server answered the last time the load loop probed it over JDBC. No catalog is registered while it does not, and `last_error` carries the connection error. |
+| `last_attempt_time` | When the loop last ran, as an ISO-8601 UTC timestamp. |
+| `last_success_time` | When the loop last completed successfully, `NULL` if it never did. |
+| `consecutive_failures` | The number of consecutive failed runs, `0` when the last run succeeded. |
+| `last_error` | The reason the last run did not complete, including the Trino server being unreachable, `NULL` when it succeeded. |
+| `metalake_errors` | A JSON map of metalake name to its last error, `NULL` when every metalake loaded. A metalake that fails here also fails the run as a whole. |
+
+Both tables are served by the coordinator and reflect the last refresh, which runs every
+`gravitino.metadata.refresh-interval-seconds` seconds (10 by default). A catalog created moments ago
+may not have been processed yet.
+
Example:
Run the following SQL to create a catalog named `mysql` with `jdbc-mysql` provider.
@@ -181,3 +243,21 @@ Hive does not support `TIME` data type.
| Struct | ROW |
For more about Trino data types, refer to [Trino data types](https://trino.io/docs/current/language/types.html) and Gravitino data types, refer to [Gravitino data types](../tables-and-views.md#table-column-type).
+
+## Troubleshooting
+
+Registration happens in the background, so a catalog that fails to register simply never appears in
+`SHOW CATALOGS`. Start from `gravitino.system.catalog_status` rather than the coordinator log.
+
+| Symptom | Likely cause |
+|--------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------|
+| A catalog is missing from `SHOW CATALOGS` | Query `gravitino.system.catalog_status` and read `status` and `last_error`, then follow the rows below |
+| `status = FAILED`, `last_error` mentions `Access Denied` | The `trino.jdbc.user` lacks a Trino system role permitted to run `CREATE CATALOG` |
+| `status = FAILED`, `last_error` mentions a configuration property | A `trino.bypass.` property is not accepted by the underlying Trino connector |
+| `status = UNSUPPORTED` | The catalog is not relational, or its provider is outside the supported list. `last_error` names the supported providers |
+| `status = SKIPPED` | The catalog matches `gravitino.trino.skip-catalog-patterns` |
+| The catalog has no row in `catalog_status` at all | The load loop never reached it. Check `gravitino.system.load_status` |
+| `load_status.trino_reachable = false` | The connector cannot reach Trino over JDBC. `last_error` carries the connection error. Check `discovery.uri`, `trino.jdbc.user` and `trino.jdbc.password` |
+| `load_status.last_error` mentions connection refused | The Gravitino server is unreachable. Check `gravitino.uri` |
+| `load_status.metalake_errors` names a metalake | That metalake could not be listed, the other metalakes are unaffected |
+| Querying `gravitino.system.catalog_status` itself fails | The entry catalog did not initialise. The error is reported when the entry catalog is created, check the Trino server log at startup |
diff --git a/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/jdbc-mysql/00015_catalog_status.sql b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/jdbc-mysql/00015_catalog_status.sql
new file mode 100644
index 0000000000..591c6f8f3a
--- /dev/null
+++ b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/jdbc-mysql/00015_catalog_status.sql
@@ -0,0 +1,3 @@
+select catalog_name, status, failure_count from gravitino.system.catalog_status where catalog_name = 'gt_mysql';
+
+select cast(trino_reachable as varchar), consecutive_failures from gravitino.system.load_status;
diff --git a/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/jdbc-mysql/00015_catalog_status.txt b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/jdbc-mysql/00015_catalog_status.txt
new file mode 100644
index 0000000000..dce3462b9c
--- /dev/null
+++ b/trino-connector/integration-test/src/test/resources/trino-ci-testset/testsets/jdbc-mysql/00015_catalog_status.txt
@@ -0,0 +1,3 @@
+"gt_mysql","REGISTERED","0"
+
+"true","0"
diff --git a/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory440.java b/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory440.java
index f167dfad92..06e52fc6eb 100644
--- a/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory440.java
+++ b/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory440.java
@@ -22,6 +22,7 @@ import org.apache.gravitino.client.GravitinoAdminClient;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
+import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFactory;
public class GravitinoConnectorFactory440 extends GravitinoConnectorFactory {
@@ -46,7 +47,8 @@ public class GravitinoConnectorFactory440 extends GravitinoConnectorFactory {
@Override
protected GravitinoSystemConnector createSystemConnector(
- GravitinoStoredProcedureFactory storedProcedureFactory) {
- return new GravitinoSystemConnector440(storedProcedureFactory);
+ GravitinoStoredProcedureFactory storedProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ return new GravitinoSystemConnector440(storedProcedureFactory, systemTableFactory);
}
}
diff --git a/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector440.java b/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector440.java
index de902bd958..b27aad3b28 100644
--- a/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector440.java
+++ b/trino-connector/trino-connector-440-445/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector440.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.trino.connector;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
+import io.trino.spi.HostAddress;
import io.trino.spi.Page;
import io.trino.spi.connector.ConnectorPageSource;
import io.trino.spi.connector.ConnectorPageSourceProvider;
@@ -28,12 +29,14 @@ import io.trino.spi.connector.ConnectorSplitManager;
import io.trino.spi.connector.SchemaTableName;
import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
+import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFactory;
public class GravitinoSystemConnector440 extends GravitinoSystemConnector {
public GravitinoSystemConnector440(
- GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory) {
- super(gravitinoStoredProcedureFactory);
+ GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ super(gravitinoStoredProcedureFactory, systemTableFactory);
}
@Override
@@ -43,11 +46,15 @@ public class GravitinoSystemConnector440 extends GravitinoSystemConnector {
@Override
protected ConnectorPageSourceProvider createPageSourceProvider() {
- return new DatasourceProvider440();
+ return new DatasourceProvider440(getSystemTableFactory());
}
static class DatasourceProvider440 extends DatasourceProvider {
+ DatasourceProvider440(GravitinoSystemTableFactory systemTableFactory) {
+ super(systemTableFactory);
+ }
+
@Override
protected ConnectorPageSource createPageSource(Page page) {
return new SystemTablePageSource440(page);
@@ -57,7 +64,7 @@ public class GravitinoSystemConnector440 extends GravitinoSystemConnector {
static class GravitinoSplitManager440 extends SplitManager {
protected ConnectorSplit createSplit(SchemaTableName tableName) {
- return new Split440(tableName);
+ return new Split440(tableName, Split.getCurrentCoordinatorAddress());
}
}
@@ -75,8 +82,10 @@ public class GravitinoSystemConnector440 extends GravitinoSystemConnector {
public static class Split440 extends Split {
@JsonCreator
- public Split440(@JsonProperty("tableName") SchemaTableName tableName) {
- super(tableName);
+ public Split440(
+ @JsonProperty("tableName") SchemaTableName tableName,
+ @JsonProperty("coordinatorAddress") HostAddress coordinatorAddress) {
+ super(tableName, coordinatorAddress);
}
@Override
diff --git a/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory446.java b/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory446.java
index 39e273e0a3..7e02341b76 100644
--- a/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory446.java
+++ b/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory446.java
@@ -22,6 +22,7 @@ import org.apache.gravitino.client.GravitinoAdminClient;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
+import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFactory;
public class GravitinoConnectorFactory446 extends GravitinoConnectorFactory {
@@ -51,7 +52,8 @@ public class GravitinoConnectorFactory446 extends GravitinoConnectorFactory {
@Override
protected GravitinoSystemConnector createSystemConnector(
- GravitinoStoredProcedureFactory storedProcedureFactory) {
- return new GravitinoSystemConnector446(storedProcedureFactory);
+ GravitinoStoredProcedureFactory storedProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ return new GravitinoSystemConnector446(storedProcedureFactory, systemTableFactory);
}
}
diff --git a/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector446.java b/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector446.java
index 5eee4446e7..224a22acf9 100644
--- a/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector446.java
+++ b/trino-connector/trino-connector-446-451/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector446.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.trino.connector;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
+import io.trino.spi.HostAddress;
import io.trino.spi.Page;
import io.trino.spi.connector.ConnectorPageSource;
import io.trino.spi.connector.ConnectorPageSourceProvider;
@@ -28,12 +29,14 @@ import io.trino.spi.connector.ConnectorSplitManager;
import io.trino.spi.connector.SchemaTableName;
import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
+import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFactory;
public class GravitinoSystemConnector446 extends GravitinoSystemConnector {
public GravitinoSystemConnector446(
- GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory) {
- super(gravitinoStoredProcedureFactory);
+ GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ super(gravitinoStoredProcedureFactory, systemTableFactory);
}
@Override
@@ -43,11 +46,15 @@ public class GravitinoSystemConnector446 extends GravitinoSystemConnector {
@Override
protected ConnectorPageSourceProvider createPageSourceProvider() {
- return new DatasourceProvider446();
+ return new DatasourceProvider446(getSystemTableFactory());
}
static class DatasourceProvider446 extends DatasourceProvider {
+ DatasourceProvider446(GravitinoSystemTableFactory systemTableFactory) {
+ super(systemTableFactory);
+ }
+
@Override
protected ConnectorPageSource createPageSource(Page page) {
return new SystemTablePageSource446(page);
@@ -57,7 +64,7 @@ public class GravitinoSystemConnector446 extends GravitinoSystemConnector {
static class GravitinoSplitManager446 extends SplitManager {
protected ConnectorSplit createSplit(SchemaTableName tableName) {
- return new Split446(tableName);
+ return new Split446(tableName, Split.getCurrentCoordinatorAddress());
}
}
@@ -75,8 +82,10 @@ public class GravitinoSystemConnector446 extends GravitinoSystemConnector {
public static class Split446 extends Split {
@JsonCreator
- public Split446(@JsonProperty("tableName") SchemaTableName tableName) {
- super(tableName);
+ public Split446(
+ @JsonProperty("tableName") SchemaTableName tableName,
+ @JsonProperty("coordinatorAddress") HostAddress coordinatorAddress) {
+ super(tableName, coordinatorAddress);
}
}
}
diff --git a/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory452.java b/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory452.java
index 01f73440e1..7cf665bcba 100644
--- a/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory452.java
+++ b/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory452.java
@@ -22,6 +22,7 @@ import org.apache.gravitino.client.GravitinoAdminClient;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
+import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFactory;
public class GravitinoConnectorFactory452 extends GravitinoConnectorFactory {
@@ -51,7 +52,8 @@ public class GravitinoConnectorFactory452 extends GravitinoConnectorFactory {
@Override
protected GravitinoSystemConnector createSystemConnector(
- GravitinoStoredProcedureFactory storedProcedureFactory) {
- return new GravitinoSystemConnector452(storedProcedureFactory);
+ GravitinoStoredProcedureFactory storedProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ return new GravitinoSystemConnector452(storedProcedureFactory, systemTableFactory);
}
}
diff --git a/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector452.java b/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector452.java
index 3dd53e12d5..7fad2a0473 100644
--- a/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector452.java
+++ b/trino-connector/trino-connector-452-468/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector452.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.trino.connector;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
+import io.trino.spi.HostAddress;
import io.trino.spi.Page;
import io.trino.spi.connector.ConnectorPageSource;
import io.trino.spi.connector.ConnectorPageSourceProvider;
@@ -28,12 +29,14 @@ import io.trino.spi.connector.ConnectorSplitManager;
import io.trino.spi.connector.SchemaTableName;
import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
+import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFactory;
public class GravitinoSystemConnector452 extends GravitinoSystemConnector {
public GravitinoSystemConnector452(
- GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory) {
- super(gravitinoStoredProcedureFactory);
+ GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ super(gravitinoStoredProcedureFactory, systemTableFactory);
}
@Override
@@ -43,11 +46,15 @@ public class GravitinoSystemConnector452 extends GravitinoSystemConnector {
@Override
protected ConnectorPageSourceProvider createPageSourceProvider() {
- return new DatasourceProvider452();
+ return new DatasourceProvider452(getSystemTableFactory());
}
static class DatasourceProvider452 extends DatasourceProvider {
+ DatasourceProvider452(GravitinoSystemTableFactory systemTableFactory) {
+ super(systemTableFactory);
+ }
+
@Override
protected ConnectorPageSource createPageSource(Page page) {
return new SystemTablePageSource452(page);
@@ -57,7 +64,7 @@ public class GravitinoSystemConnector452 extends GravitinoSystemConnector {
static class GravitinoSplitManager452 extends SplitManager {
protected ConnectorSplit createSplit(SchemaTableName tableName) {
- return new Split452(tableName);
+ return new Split452(tableName, Split.getCurrentCoordinatorAddress());
}
}
@@ -75,8 +82,10 @@ public class GravitinoSystemConnector452 extends GravitinoSystemConnector {
public static class Split452 extends Split {
@JsonCreator
- public Split452(@JsonProperty("tableName") SchemaTableName tableName) {
- super(tableName);
+ public Split452(
+ @JsonProperty("tableName") SchemaTableName tableName,
+ @JsonProperty("coordinatorAddress") HostAddress coordinatorAddress) {
+ super(tableName, coordinatorAddress);
}
}
}
diff --git a/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory469.java b/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory469.java
index 66b42c9ad0..7abe580823 100644
--- a/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory469.java
+++ b/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory469.java
@@ -22,6 +22,7 @@ import org.apache.gravitino.client.GravitinoAdminClient;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
+import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFactory;
public class GravitinoConnectorFactory469 extends GravitinoConnectorFactory {
@@ -46,7 +47,8 @@ public class GravitinoConnectorFactory469 extends GravitinoConnectorFactory {
@Override
protected GravitinoSystemConnector createSystemConnector(
- GravitinoStoredProcedureFactory storedProcedureFactory) {
- return new GravitinoSystemConnector469(storedProcedureFactory);
+ GravitinoStoredProcedureFactory storedProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ return new GravitinoSystemConnector469(storedProcedureFactory, systemTableFactory);
}
}
diff --git a/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector469.java b/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector469.java
index b2d5483b27..c8a61f95ae 100644
--- a/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector469.java
+++ b/trino-connector/trino-connector-469-472/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector469.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.trino.connector;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
+import io.trino.spi.HostAddress;
import io.trino.spi.Page;
import io.trino.spi.connector.ConnectorPageSource;
import io.trino.spi.connector.ConnectorPageSourceProvider;
@@ -28,12 +29,14 @@ import io.trino.spi.connector.ConnectorSplitManager;
import io.trino.spi.connector.SchemaTableName;
import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
+import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFactory;
public class GravitinoSystemConnector469 extends GravitinoSystemConnector {
public GravitinoSystemConnector469(
- GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory) {
- super(gravitinoStoredProcedureFactory);
+ GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ super(gravitinoStoredProcedureFactory, systemTableFactory);
}
@Override
@@ -43,11 +46,15 @@ public class GravitinoSystemConnector469 extends GravitinoSystemConnector {
@Override
protected ConnectorPageSourceProvider createPageSourceProvider() {
- return new DatasourceProvider469();
+ return new DatasourceProvider469(getSystemTableFactory());
}
static class DatasourceProvider469 extends DatasourceProvider {
+ DatasourceProvider469(GravitinoSystemTableFactory systemTableFactory) {
+ super(systemTableFactory);
+ }
+
@Override
protected ConnectorPageSource createPageSource(Page page) {
return new SystemTablePageSource469(page);
@@ -57,7 +64,7 @@ public class GravitinoSystemConnector469 extends GravitinoSystemConnector {
static class GravitinoSplitManager469 extends SplitManager {
protected ConnectorSplit createSplit(SchemaTableName tableName) {
- return new Split469(tableName);
+ return new Split469(tableName, Split.getCurrentCoordinatorAddress());
}
}
@@ -75,8 +82,10 @@ public class GravitinoSystemConnector469 extends GravitinoSystemConnector {
public static class Split469 extends Split {
@JsonCreator
- public Split469(@JsonProperty("tableName") SchemaTableName tableName) {
- super(tableName);
+ public Split469(
+ @JsonProperty("tableName") SchemaTableName tableName,
+ @JsonProperty("coordinatorAddress") HostAddress coordinatorAddress) {
+ super(tableName, coordinatorAddress);
}
}
}
diff --git a/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory478.java b/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory478.java
index 9da0802a89..ec8adc60d8 100644
--- a/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory478.java
+++ b/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory478.java
@@ -22,6 +22,7 @@ import org.apache.gravitino.client.GravitinoAdminClient;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
+import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFactory;
public class GravitinoConnectorFactory478 extends GravitinoConnectorFactory {
@@ -46,7 +47,8 @@ public class GravitinoConnectorFactory478 extends GravitinoConnectorFactory {
@Override
protected GravitinoSystemConnector createSystemConnector(
- GravitinoStoredProcedureFactory storedProcedureFactory) {
- return new GravitinoSystemConnector478(storedProcedureFactory);
+ GravitinoStoredProcedureFactory storedProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ return new GravitinoSystemConnector478(storedProcedureFactory, systemTableFactory);
}
}
diff --git a/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector478.java b/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector478.java
index 208671e051..ef8060831d 100644
--- a/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector478.java
+++ b/trino-connector/trino-connector-473-478/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector478.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.trino.connector;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
+import io.trino.spi.HostAddress;
import io.trino.spi.Page;
import io.trino.spi.connector.ConnectorPageSource;
import io.trino.spi.connector.ConnectorPageSourceProvider;
@@ -29,12 +30,14 @@ import io.trino.spi.connector.SchemaTableName;
import io.trino.spi.connector.SourcePage;
import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
+import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFactory;
public class GravitinoSystemConnector478 extends GravitinoSystemConnector {
public GravitinoSystemConnector478(
- GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory) {
- super(gravitinoStoredProcedureFactory);
+ GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ super(gravitinoStoredProcedureFactory, systemTableFactory);
}
@Override
@@ -44,11 +47,15 @@ public class GravitinoSystemConnector478 extends GravitinoSystemConnector {
@Override
protected ConnectorPageSourceProvider createPageSourceProvider() {
- return new DatasourceProvider478();
+ return new DatasourceProvider478(getSystemTableFactory());
}
static class DatasourceProvider478 extends DatasourceProvider {
+ DatasourceProvider478(GravitinoSystemTableFactory systemTableFactory) {
+ super(systemTableFactory);
+ }
+
@Override
protected ConnectorPageSource createPageSource(Page page) {
return new SystemTablePageSource478(page);
@@ -58,7 +65,7 @@ public class GravitinoSystemConnector478 extends GravitinoSystemConnector {
static class GravitinoSplitManager478 extends SplitManager {
protected ConnectorSplit createSplit(SchemaTableName tableName) {
- return new Split478(tableName);
+ return new Split478(tableName, Split.getCurrentCoordinatorAddress());
}
}
@@ -76,8 +83,10 @@ public class GravitinoSystemConnector478 extends GravitinoSystemConnector {
public static class Split478 extends Split {
@JsonCreator
- public Split478(@JsonProperty("tableName") SchemaTableName tableName) {
- super(tableName);
+ public Split478(
+ @JsonProperty("tableName") SchemaTableName tableName,
+ @JsonProperty("coordinatorAddress") HostAddress coordinatorAddress) {
+ super(tableName, coordinatorAddress);
}
}
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
index 553e091e4d..6bad499794 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
@@ -350,7 +350,10 @@ public class GravitinoConfig {
* @return the metalake name for used
*/
public String getMetalake() {
- return config.getOrDefault(GRAVITINO_METALAKE.key, GRAVITINO_METALAKE.defaultValue);
+ // Trimmed so a stray leading/trailing space in the catalog properties file does not make this
+ // value silently stop matching the canonical metalake name the load loop records states
+ // under, e.g. in the catalog_status/load_status system tables' per-metalake filtering.
+ return config.getOrDefault(GRAVITINO_METALAKE.key, GRAVITINO_METALAKE.defaultValue).trim();
}
/**
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
index df83dd387e..d59ff46ede 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
@@ -26,6 +26,7 @@ import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import io.airlift.log.Logger;
+import io.trino.spi.HostAddress;
import io.trino.spi.TrinoException;
import io.trino.spi.connector.Connector;
import io.trino.spi.connector.ConnectorContext;
@@ -59,10 +60,8 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
/** The default connector name. */
public static final String DEFAULT_CONNECTOR_NAME = "gravitino";
- @SuppressWarnings("UnusedVariable")
- private GravitinoSystemTableFactory gravitinoSystemTableFactory;
-
private CatalogConnectorManager catalogConnectorManager;
+
private boolean catalogConnectorManagerStartTriggered = false;
private GravitinoAdminClient client;
@@ -134,7 +133,6 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
// failed client initialization leaves a shared manager with a null Gravitino client,
// causing later connector creation attempts to fail with a misleading NPE.
catalogConnectorManager = newCatalogConnectorManager;
- gravitinoSystemTableFactory = new GravitinoSystemTableFactory(catalogConnectorManager);
}
// The `trino.jdbc.*` settings that CatalogRegister needs to connect back to the
@@ -146,16 +144,23 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
if (!catalogConnectorManagerStartTriggered
&& !config.isDynamicConnector()
&& isCoordinator(trinoConnectorContext)) {
- // Triggered before start() on purpose: everything that makes it fail is a
- // configuration error, and retrying on the next create() would only open another
- // connection.
catalogConnectorManagerStartTriggered = true;
// Only the configuration is re-applied here: rebuilding the Gravitino client would leak
// the one a dynamic connector may have already built.
catalogConnectorManager.updateConfig(config);
+ // Only the coordinator runs the load loop, so it is the only node holding the
+ // registration state the system tables report. Pin their splits to it.
+ GravitinoSystemConnector.Split.setCoordinatorAddress(
+ getCurrentNodeAddress(trinoConnectorContext));
catalogConnectorManager.start();
}
} catch (Exception e) {
+ // Clearing the flag is what stops a later create() from skipping the startup and
+ // handing out a connector whose load loop never started, and it lets a corrected
+ // configuration recover. The manager is deliberately kept: it is shared, and a dynamic
+ // connector created before the static one may already be running against it. start()
+ // releases what it allocated before failing.
+ catalogConnectorManagerStartTriggered = false;
String message = "Initialization of the GravitinoConnector failed " + e.getMessage();
LOG.error(e, message);
throw new TrinoException(GRAVITINO_RUNTIME_ERROR, message, e);
@@ -179,9 +184,13 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
throw new TrinoException(
GravitinoErrorCode.GRAVITINO_METALAKE_NOT_EXISTS, "No gravitino metalake selected");
}
+ // Built per entry catalog, like the stored procedures: both are scoped to this catalog's
+ // metalake even though the underlying manager is shared.
GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory =
new GravitinoStoredProcedureFactory(catalogConnectorManager, metalake);
- return createSystemConnector(gravitinoStoredProcedureFactory);
+ GravitinoSystemTableFactory systemTableFactory =
+ new GravitinoSystemTableFactory(catalogConnectorManager, metalake);
+ return createSystemConnector(gravitinoStoredProcedureFactory, systemTableFactory);
}
}
@@ -201,8 +210,9 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
}
protected GravitinoSystemConnector createSystemConnector(
- GravitinoStoredProcedureFactory storedProcedureFactory) {
- return new GravitinoSystemConnector(storedProcedureFactory);
+ GravitinoStoredProcedureFactory storedProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
+ return new GravitinoSystemConnector(storedProcedureFactory, systemTableFactory);
}
protected String getTrinoCatalogName(String metalakeName, String catalogName) {
@@ -291,6 +301,17 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
return connectorContext.getNodeManager().getCurrentNode().isCoordinator();
}
+ /**
+ * Retrieves the address of the Trino node this connector is running on.
+ *
+ * @param connectorContext the Trino connector context
+ * @return the host and port of the current node
+ */
+ @SuppressWarnings("deprecation")
+ protected HostAddress getCurrentNodeAddress(ConnectorContext connectorContext) {
+ return connectorContext.getNodeManager().getCurrentNode().getHostAndPort();
+ }
+
private CatalogConnectorFactory createCatalogConnectorFactory(GravitinoConfig config) {
// Create a CatalogConnectorFactory. If we specify a customized class name for the
// CatalogConnectorFactory,
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
index 4c93045330..5b9daab632 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
@@ -19,23 +19,26 @@
package org.apache.gravitino.trino.connector.catalog;
import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.airlift.log.Logger;
import io.trino.spi.TrinoException;
import io.trino.spi.connector.ConnectorContext;
-import java.util.Arrays;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
+import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
-import java.util.stream.Collectors;
+import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.client.GravitinoAdminClient;
@@ -73,6 +76,24 @@ public class CatalogConnectorManager {
private final ConcurrentHashMap<String, CatalogConnectorContext> catalogConnectors =
new ConcurrentHashMap<>();
+ // The registration state of every catalog seen by the load loop, keyed by the Trino catalog
+ // name. Written only by the load loop thread, read by query threads through the system tables
+ // and by stored procedure threads through describeRegistrationFailure().
+ private final ConcurrentHashMap<String, CatalogRegistrationState> catalogStates =
+ new ConcurrentHashMap<>();
+
+ // The last error reported by each metalake, keyed by the metalake name.
+ private final ConcurrentHashMap<String, String> metalakeErrors = new ConcurrentHashMap<>();
+
+ private volatile boolean trinoReachable = false;
+ private volatile long lastLoadAttemptTimeMs = 0L;
+ // The outcome of the last completed load attempt: its success time, error and consecutive
+ // failure count always change together, so they are published through one volatile reference
+ // rather than as separate fields. Reading them independently would let a query thread observe
+ // a combination from two different load attempts, e.g. a fresh success time next to a stale
+ // error that a concurrent recordLoadSuccess() had not cleared yet.
+ private volatile LoadOutcome loadOutcome = new LoadOutcome(false, 0L, null, 0L, Map.of());
+
private String targetMetalake;
private final Map<String, GravitinoMetalake> metalakes = new ConcurrentHashMap<>();
private final IcebergRestUriDiscovery icebergRestUriDiscovery = new IcebergRestUriDiscovery();
@@ -171,7 +192,15 @@ public class CatalogConnectorManager {
* @throws Exception if the catalog connector manager fails to start
*/
public void start() throws Exception {
- catalogRegister.init(config);
+ try {
+ catalogRegister.init(config);
+ } catch (Exception e) {
+ // Release the connection init() may have opened before failing, so that a later attempt
+ // does not leave it behind. The manager itself stays usable: a dynamic connector may
+ // already be running against it.
+ catalogRegister.close();
+ throw e;
+ }
executorService.scheduleWithFixedDelay(
this::loadMetalake,
metadataUpdateIntervalSecond,
@@ -181,11 +210,24 @@ public class CatalogConnectorManager {
}
private void loadMetalake() {
+ lastLoadAttemptTimeMs = System.currentTimeMillis();
try {
- if (!catalogRegister.isTrinoStarted()) {
- LOG.info("Waiting for the Trino started.");
+ if (!catalogRegister.isTrinoReachable()) {
+ // Report why the connection failed. "The Trino server is not reachable" alone reads the
+ // same for a coordinator that is seconds from ready and for credentials that will never
+ // work.
+ String cause = catalogRegister.getLastConnectionError();
+ String message =
+ cause == null
+ ? "The Trino server is not reachable"
+ : "The Trino server is not reachable, the last connection attempt failed: " + cause;
+ trinoReachable = false;
+ // No metalake was touched, so the errors left over from earlier cycles say nothing
+ // about this one.
+ recordLoadFailure(message, null, Map.of(), true);
return;
}
+ trinoReachable = true;
Set<String> usedMetalakes = new HashSet<>();
if (config.singleMetalakeMode()) {
@@ -206,14 +248,177 @@ public class CatalogConnectorManager {
icebergRestUriDiscovery.refresh(usedMetalake, config, gravitinoClient);
loadCatalogs(metalake);
} catch (Exception e) {
- LOG.error(e, "Load Metalake %s failed.", usedMetalake);
+ recordMetalakeError(usedMetalake, e);
}
}
- } catch (Exception e) {
- LOG.error(e, "Error when loading metalake");
+
+ pruneMissingMetalakes(usedMetalakes);
+
+ if (metalakeErrors.isEmpty()) {
+ recordLoadSuccess();
+ } else {
+ // Some metalake failed. The loop reaching its last line is not a health signal, so do not
+ // advance the success time or clear the error, or load_status would report a healthy loop
+ // while no catalog is being registered at all.
+ recordLoadFailure(
+ String.format(
+ "%d of %d metalakes failed to load: %s",
+ metalakeErrors.size(), usedMetalakes.size(), new TreeMap<>(metalakeErrors)),
+ null);
+ }
+ } catch (Throwable t) {
+ // Catch Throwable, not Exception: scheduleWithFixedDelay silently cancels the task forever
+ // the first time the runnable throws, and loading a Trino connector plugin can raise
+ // NoClassDefFoundError. A dead loop must not look like a healthy one.
+ recordLoadFailure(toErrorMessage(t), t);
+ }
+ }
+
+ private void pruneMissingMetalakes(Set<String> usedMetalakes) {
+ // A metalake that was deleted, or that dropped out of the configuration, leaves its catalog
+ // connectors, catalog rows and cached metalake handle behind. Without this its catalogs keep
+ // reporting REGISTERED and stay live in Trino even though they no longer exist, and
+ // getUsedMetalakes()/getMetalake() keep returning a metalake that isn't loaded anymore.
+ for (Map.Entry<String, CatalogConnectorContext> entry : catalogConnectors.entrySet()) {
+ GravitinoCatalog catalog = entry.getValue().getCatalog();
+ if (usedMetalakes.contains(catalog.getMetalake())) {
+ continue;
+ }
+ try {
+ unloadCatalog(catalog);
+ } catch (Exception e) {
+ // The metalake is gone but the catalog is still registered in Trino. Record it, or the
+ // pruning below would drop the row and the table would report nothing at all about a
+ // catalog that still shows up in SHOW CATALOGS.
+ recordCatalogState(
+ CatalogRegistrationState.failed(
+ catalog.getMetalake(),
+ catalog.getName(),
+ entry.getKey(),
+ catalog.getProvider(),
+ "The metalake was removed but the catalog could not be unregistered from Trino: "
+ + toErrorMessage(e)),
+ e);
+ }
+ }
+
+ // A catalog whose connector could not be removed from Trino keeps its state, the same way the
+ // per-catalog pruning in loadCatalogs() does, so the failure recorded just above stays visible
+ // for as long as the connector still shows up in SHOW CATALOGS.
+ catalogStates
+ .values()
+ .removeIf(
+ state ->
+ !usedMetalakes.contains(state.getMetalake())
+ && !catalogConnectors.containsKey(state.getTrinoCatalogName()));
+ metalakeErrors.keySet().removeIf(metalakeName -> !usedMetalakes.contains(metalakeName));
+ metalakes.keySet().removeIf(metalakeName -> !usedMetalakes.contains(metalakeName));
+ }
+
+ private void recordLoadSuccess() {
+ if (loadOutcome.lastError != null) {
+ LOG.info("The Gravitino catalog load loop recovered.");
+ }
+ loadOutcome = new LoadOutcome(trinoReachable, System.currentTimeMillis(), null, 0, Map.of());
+ }
+
+ private void recordLoadFailure(String message, Throwable cause) {
+ recordLoadFailure(message, cause, Map.copyOf(metalakeErrors), false);
+ }
+
+ /**
+ * @param awaitingTrino whether the attempt stopped at the reachability check, which is the normal
+ * state during startup and the only failure this reports quietly. Passed in rather than read
+ * from the field, which outlives the cycle: a plugin failing to load while Trino happens to
+ * be down is still an error worth an ERROR line and a stack trace.
+ */
+ private void recordLoadFailure(
+ String message,
+ Throwable cause,
+ Map<String, String> attemptMetalakeErrors,
+ boolean awaitingTrino) {
+ LoadOutcome previous = loadOutcome;
+ boolean changed = !Objects.equals(previous.lastError, message);
+ loadOutcome =
+ new LoadOutcome(
+ trinoReachable,
+ previous.lastSuccessTimeMs,
+ message,
+ previous.consecutiveFailures + 1,
+ attemptMetalakeErrors);
+ if (awaitingTrino) {
+ // Waiting for Trino is the normal state during startup, and a repeat of it is just as
+ // normal, so this branch comes before the ones that escalate.
+ LOG.info("%s", message);
+ } else if (changed) {
+ LOG.error("Failed to load catalogs from the Gravitino server: %s", withCause(message, cause));
+ } else {
+ LOG.warn("Failed to load catalogs from the Gravitino server: %s", withCause(message, cause));
+ }
+ }
+
+ private void recordMetalakeError(String metalakeName, Throwable cause) {
+ String message = toErrorMessage(cause);
+ String previous = metalakeErrors.put(metalakeName, message);
+ if (!Objects.equals(previous, message)) {
+ LOG.error("Load metalake %s failed: %s", metalakeName, withCause(message, cause));
+ } else {
+ LOG.warn("Load metalake %s failed: %s", metalakeName, withCause(message, cause));
}
}
+ /**
+ * The message, followed by the rendered throwable when there is one.
+ *
+ * <p>A failure the load loop reports is not always tied to a single exception: waiting for the
+ * Trino server and the summary of several failed metalakes both stand on their own. Rendering a
+ * missing cause would throw right where an error is being reported, and the loop's own catch
+ * would then replace the real message with that secondary failure.
+ */
+ private static String withCause(String message, @Nullable Throwable cause) {
+ return cause == null
+ ? message
+ : message + System.lineSeparator() + CatalogRegister.describe(cause);
+ }
+
+ private static String toErrorMessage(Throwable e) {
+ // Redact here rather than on the exceptions themselves: a failed CREATE CATALOG carries the
+ // credentials it embedded, and this is the single point where that chain is turned into the
+ // text the catalog_status and load_status tables report.
+ return CatalogRegister.redactSecrets(describeFailure(e));
+ }
+
+ private static String describeFailure(Throwable e) {
+ // Report the root cause: the actual reason a registration failed, such as "Access Denied:
+ // Cannot create catalog", is wrapped in several layers of TrinoException by the time it gets
+ // here, and the outer messages say nothing a user can act on. The outermost message is kept
+ // as a prefix because it names the subsystem that failed. Do not use
+ // GravitinoErrorCode.toSimpleErrorMessage(), it throws on an exception with no message.
+ Throwable rootCause;
+ try {
+ rootCause = Throwables.getRootCause(e);
+ } catch (IllegalArgumentException cycleDetected) {
+ // Throwables.getRootCause() throws instead of returning a best-effort answer when the
+ // cause chain loops back on itself. This runs on the single load loop thread, so falling
+ // back to the exception itself is safer than letting that escape: an uncaught exception
+ // would cancel the loop permanently.
+ rootCause = e;
+ }
+ String rootMessage = describeThrowable(rootCause);
+ if (rootCause == e) {
+ return rootMessage;
+ }
+ String outerMessage = e.getMessage();
+ return StringUtils.isBlank(outerMessage) || outerMessage.contains(rootMessage)
+ ? rootMessage
+ : outerMessage + ": " + rootMessage;
+ }
+
+ private static String describeThrowable(Throwable e) {
+ String message = e.getMessage();
+ return StringUtils.isBlank(message) ? e.getClass().getName() : message;
+ }
+
/**
* Retrieves a metalake by its name.
*
@@ -232,70 +437,251 @@ public class CatalogConnectorManager {
}
private void loadCatalogs(GravitinoMetalake metalake) {
- List<String> catalogNames;
+ String metalakeName = metalake.name();
+ String[] allCatalogNames;
try {
- catalogNames =
- Arrays.stream(metalake.listCatalogs())
- .filter(id -> !skipCatalog(getTrinoCatalogName(metalake.name(), id)))
- .collect(Collectors.toList());
+ allCatalogNames = metalake.listCatalogs();
} catch (Exception e) {
- LOG.error(e, "Failed to list catalogs in metalake %s.", metalake.name());
+ // Keep the existing catalog states untouched, a transient listing failure must not turn
+ // healthy catalogs into failed ones. The load status system table reports the cause.
+ recordMetalakeError(metalakeName, e);
return;
}
+ metalakeErrors.remove(metalakeName);
- LOG.debug("Load metalake %s's catalogs. catalogs: %s.", metalake.name(), catalogNames);
+ // The Trino names of every catalog the Gravitino server currently reports, including the
+ // catalogs that are intentionally not registered.
+ Set<String> presentTrinoNames = new HashSet<>();
+ List<String> catalogNames = new ArrayList<>();
+ for (String catalogName : allCatalogNames) {
+ String trinoCatalogName = getTrinoCatalogName(metalakeName, catalogName);
+ presentTrinoNames.add(trinoCatalogName);
+ if (skipCatalog(trinoCatalogName)) {
+ recordCatalogState(
+ CatalogRegistrationState.skipped(
+ metalakeName,
+ catalogName,
+ trinoCatalogName,
+ "Matched gravitino.trino.skip-catalog-patterns"),
+ null);
+ continue;
+ }
+ catalogNames.add(catalogName);
+ }
+
+ LOG.debug("Load metalake %s's catalogs. catalogs: %s.", metalakeName, catalogNames);
// Delete those catalogs that have been deleted in Gravitino server
- Set<String> catalogNameStrings =
- catalogNames.stream()
- .map(id -> getTrinoCatalogName(metalake.name(), id))
- .collect(Collectors.toSet());
+ Set<String> catalogNameStrings = new HashSet<>();
+ for (String catalogName : catalogNames) {
+ catalogNameStrings.add(getTrinoCatalogName(metalakeName, catalogName));
+ }
for (Map.Entry<String, CatalogConnectorContext> entry : catalogConnectors.entrySet()) {
if (!catalogNameStrings.contains(entry.getKey())
&&
// Skip the catalog doesn't belong to this metalake.
- entry.getValue().getMetalake().name().equals(metalake.name())) {
+ entry.getValue().getMetalake().name().equals(metalakeName)) {
try {
unloadCatalog(entry.getValue().getCatalog());
} catch (Exception e) {
- LOG.error(e, "Failed to remove catalog %s.", entry.getKey());
+ // The catalog is still registered in Trino. Record it, or the pruning below would drop
+ // the row and the table would report nothing at all about a catalog that still shows
+ // up in SHOW CATALOGS. This branch unloads for two different reasons, and saying the
+ // catalog was deleted when it is merely skipped would send its owner looking in the
+ // wrong place: presentTrinoNames still holds the ones Gravitino reports.
+ GravitinoCatalog catalog = entry.getValue().getCatalog();
+ String reason =
+ presentTrinoNames.contains(entry.getKey())
+ ? "The catalog matches gravitino.trino.skip-catalog-patterns but could not be "
+ + "unregistered from Trino: "
+ : "The catalog was deleted in Gravitino but could not be unregistered from "
+ + "Trino: ";
+ recordCatalogState(
+ CatalogRegistrationState.failed(
+ metalakeName,
+ catalog.getName(),
+ entry.getKey(),
+ catalog.getProvider(),
+ reason + toErrorMessage(e)),
+ e);
}
}
}
+ // Drop the states of catalogs that no longer exist in the Gravitino server, including the
+ // states of catalogs that never had a connector. A catalog whose connector could not be
+ // removed from Trino is kept, so that its failure stays visible for as long as it is real.
+ catalogStates
+ .values()
+ .removeIf(
+ state ->
+ state.getMetalake().equals(metalakeName)
+ && !presentTrinoNames.contains(state.getTrinoCatalogName())
+ && !catalogConnectors.containsKey(state.getTrinoCatalogName()));
+
// Load new catalogs belows to the metalake.
- catalogNames.stream()
- .forEach(
- (String catalogName) -> {
- try {
- Catalog catalog = metalake.loadCatalog(catalogName);
- Map<String, String> properties = propsWithSecrets(catalog);
- GravitinoCatalog gravitinoCatalog =
- new GravitinoCatalog(metalake.name(), catalog, properties);
- if (catalogConnectors.containsKey(getTrinoCatalogName(gravitinoCatalog))) {
- // Reload catalogs that have been updated in Gravitino server.
- reloadCatalog(gravitinoCatalog);
- } else {
- if (catalog.type() == Catalog.Type.RELATIONAL
- && catalogConnectorFactory
- .getSupportedCatalogProviders()
- .contains(gravitinoCatalog.getProvider())) {
- loadCatalog(gravitinoCatalog);
- }
- }
- } catch (UnsupportedOperationException e) {
- LOG.warn(
- "Unsupported catalog type for catalog %s in metalake %s: %s",
- catalogName, metalake.name(), e.getMessage());
- } catch (Exception e) {
- LOG.error(
- e, "Failed to load metalake %s's catalog %s.", metalake.name(), catalogName);
- }
+ for (String catalogName : catalogNames) {
+ String trinoCatalogName = getTrinoCatalogName(metalakeName, catalogName);
+ // Known before the catalog is even loaded, since it only depends on the name.
+ boolean alreadyRegistered = catalogConnectors.containsKey(trinoCatalogName);
+ // Tracked outside the try so that a failure can still report the provider it knows about.
+ String provider = null;
+ try {
+ Catalog catalog = metalake.loadCatalog(catalogName);
+ // Registration deliberately carries only the visible properties. The resolved secrets are
+ // added by each node in createCatalogConnectorContext(), so that they never reach the
+ // CREATE CATALOG statement, the catalog properties file Trino persists from it, or
+ // anything that quotes either of them back.
+ GravitinoCatalog gravitinoCatalog =
+ new GravitinoCatalog(metalakeName, catalog, visibleProps(catalog));
+ provider = gravitinoCatalog.getProvider();
+ // Checked before the already-registered path: a catalog can be dropped and recreated
+ // under the same name with a type or provider this connector cannot serve, and treating
+ // it as a refresh would leave Trino serving a catalog that no longer qualifies.
+ String unsupportedReason = unsupportedReason(catalog, gravitinoCatalog);
+ if (unsupportedReason != null) {
+ if (alreadyRegistered && !unloadUnsupported(gravitinoCatalog, trinoCatalogName)) {
+ // Still live in Trino, so reporting it as merely unsupported would hide that it is
+ // also still being served.
+ continue;
+ }
+ recordCatalogState(
+ CatalogRegistrationState.unsupported(
+ metalakeName,
+ catalogName,
+ trinoCatalogName,
+ gravitinoCatalog.getProvider(),
+ unsupportedReason),
+ null);
+ } else if (alreadyRegistered) {
+ // Reload catalogs that have been updated in Gravitino server. The state is recorded
+ // either way, so that last_attempt_time keeps saying when the catalog was last looked
+ // at; only a reload that actually re-registered stamps a new success time.
+ recordCatalogState(
+ reloadCatalog(gravitinoCatalog)
+ ? CatalogRegistrationState.succeeded(gravitinoCatalog, trinoCatalogName)
+ : CatalogRegistrationState.unchanged(gravitinoCatalog, trinoCatalogName),
+ null);
+ } else {
+ loadCatalog(gravitinoCatalog);
+ recordCatalogState(
+ CatalogRegistrationState.succeeded(gravitinoCatalog, trinoCatalogName), null);
+ }
+ } catch (UnsupportedOperationException e) {
+ // The client library does not recognize this catalog's type, e.g. DTOConverters.toCatalog
+ // throws for a type it cannot map. This is the same "we know about it, we just don't
+ // support it" case as the type/provider checks above, not a registration failure.
+ recordCatalogState(
+ CatalogRegistrationState.unsupported(
+ metalakeName, catalogName, trinoCatalogName, provider, toErrorMessage(e)),
+ e);
+ } catch (Exception e) {
+ // reloadCatalog() unregisters the old connector before re-registering; if the
+ // re-register then fails, the catalog is no longer in catalogConnectors even though
+ // alreadyRegistered was true when this iteration started. Re-check the live map instead
+ // of trusting the pre-try snapshot, or a reload failure gets reported as "still
+ // registered" when the catalog has actually dropped out of Trino.
+ boolean stillRegistered = catalogConnectors.containsKey(trinoCatalogName);
+ if (alreadyRegistered && stillRegistered) {
+ // The catalog is still registered and visible via SHOW CATALOGS; a transient failure to
+ // refresh it must not flip it to FAILED and hide that it is still usable.
+ LOG.warn(
+ "Failed to refresh already-registered catalog %s: %s",
+ trinoCatalogName, withCause(toErrorMessage(e), e));
+ } else {
+ recordCatalogState(
+ CatalogRegistrationState.failed(
+ metalakeName, catalogName, trinoCatalogName, provider, toErrorMessage(e)),
+ e);
+ }
+ }
+ }
+ }
+
+ private void recordCatalogState(CatalogRegistrationState newState, Throwable cause) {
+ // Merge under compute() so the history carried over cannot be lost to a concurrent record.
+ CatalogRegistrationState[] seen = new CatalogRegistrationState[1];
+ CatalogRegistrationState state =
+ catalogStates.compute(
+ newState.getTrinoCatalogName(),
+ (name, previous) -> {
+ seen[0] = previous;
+ return newState.withHistoryOf(previous);
});
+ CatalogRegistrationState previous = seen[0];
+ boolean changed =
+ previous == null
+ || previous.getStatus() != state.getStatus()
+ || !Objects.equals(previous.getLastError(), state.getLastError());
+ if (!changed) {
+ LOG.debug("Catalog %s registration state unchanged: %s", state.getTrinoCatalogName(), state);
+ return;
+ }
+
+ if (state.getStatus() == CatalogRegistrationState.Status.REGISTERED) {
+ LOG.info("Catalog %s is registered in Trino.", state.getTrinoCatalogName());
+ } else if (state.getStatus() == CatalogRegistrationState.Status.FAILED) {
+ LOG.error(
+ "Failed to register catalog %s in Trino: %s",
+ state.getTrinoCatalogName(), withCause(state.getLastError(), cause));
+ } else {
+ LOG.warn(
+ "Catalog %s is not registered in Trino (%s): %s",
+ state.getTrinoCatalogName(), state.getStatus(), state.getLastError());
+ }
}
- private void reloadCatalog(GravitinoCatalog catalog) {
+ /**
+ * Unregisters a catalog that is live in Trino but no longer eligible.
+ *
+ * @return true if it is gone from Trino, false if it is still there and was reported as failed
+ */
+ private boolean unloadUnsupported(GravitinoCatalog catalog, String trinoCatalogName) {
+ try {
+ unloadCatalog(catalog);
+ return true;
+ } catch (Exception e) {
+ recordCatalogState(
+ CatalogRegistrationState.failed(
+ catalog.getMetalake(),
+ catalog.getName(),
+ trinoCatalogName,
+ catalog.getProvider(),
+ "The catalog is no longer supported but could not be unregistered from Trino: "
+ + toErrorMessage(e)),
+ e);
+ return false;
+ }
+ }
+
+ /**
+ * Why this connector cannot serve the catalog, or null when it can.
+ *
+ * @param catalog the catalog as the Gravitino server reports it
+ * @param gravitinoCatalog the same catalog as it would be registered
+ */
+ @Nullable
+ private String unsupportedReason(Catalog catalog, GravitinoCatalog gravitinoCatalog) {
+ if (catalog.type() != Catalog.Type.RELATIONAL) {
+ return String.format(
+ "Only relational catalogs are supported, the catalog type is %s", catalog.type());
+ }
+ Set<String> supported = catalogConnectorFactory.getSupportedCatalogProviders();
+ if (!supported.contains(gravitinoCatalog.getProvider())) {
+ return String.format(
+ "The catalog provider %s is not supported, the supported providers are %s",
+ gravitinoCatalog.getProvider(), supported);
+ }
+ return null;
+ }
+
+ /**
+ * Re-registers a catalog whose definition changed.
+ *
+ * @return true if the catalog was re-registered, false if it was already up to date
+ */
+ private boolean reloadCatalog(GravitinoCatalog catalog) {
String catalogFullName = getTrinoCatalogName(catalog);
GravitinoCatalog oldCatalog = catalogConnectors.get(catalogFullName).getCatalog();
// The discovered Iceberg REST endpoint is embedded into the catalog independently of
@@ -304,7 +690,7 @@ public class CatalogConnectorManager {
IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(catalog, oldCatalog, config);
if (catalog.getLastModifiedTime() <= oldCatalog.getLastModifiedTime()
&& !icebergRestUriChanged) {
- return;
+ return false;
}
catalogRegister.unregisterCatalog(catalogFullName);
@@ -312,6 +698,7 @@ public class CatalogConnectorManager {
loadCatalogImpl(catalog);
LOG.info("Update catalog '%s' in metalake %s successfully.", catalog, catalog.getMetalake());
+ return true;
}
private void loadCatalog(GravitinoCatalog catalog) {
@@ -325,7 +712,10 @@ public class CatalogConnectorManager {
} catch (Exception e) {
String message =
String.format("Failed to create internal catalog connector. The catalog is: %s", catalog);
- LOG.error(e, message);
+ // Debug only: the caller always rethrows and, when this leaves a catalog unregistered,
+ // records it via recordCatalogState() which logs the full cause chain at ERROR. Logging
+ // it again here at ERROR would duplicate that.
+ LOG.debug("%s", withCause(message, e));
throw new TrinoException(
GravitinoErrorCode.GRAVITINO_CREATE_INTERNAL_CONNECTOR_ERROR, message, e);
}
@@ -335,6 +725,10 @@ public class CatalogConnectorManager {
String catalogFullName = getTrinoCatalogName(catalog);
catalogRegister.unregisterCatalog(catalogFullName);
catalogConnectors.remove(catalogFullName);
+ // Not removing catalogStates here: the caller may have just recorded a SKIPPED state for a
+ // catalog that still exists in Gravitino, and unconditionally clearing it here would wipe
+ // that state out in the same load cycle. The pruning in loadCatalogs() drops states for
+ // catalogs that are genuinely gone, once this method's caller has finished this cycle.
LOG.info(
"Remove catalog '%s' in metalake %s successfully.",
catalog.getName(), catalog.getMetalake());
@@ -406,6 +800,102 @@ public class CatalogConnectorManager {
return getTrinoCatalogName(catalog.getMetalake(), catalog.getName());
}
+ /**
+ * Retrieves a snapshot of the registration state of every Gravitino catalog seen by the load
+ * loop. Package-private: production callers always know which metalake they report on and use
+ * {@link #getCatalogRegistrationStates(String)}; this exists for tests that assert on the whole
+ * set of tracked catalogs.
+ *
+ * @return the registration states
+ */
+ List<CatalogRegistrationState> getCatalogRegistrationStates() {
+ return List.copyOf(catalogStates.values());
+ }
+
+ /**
+ * Retrieves a snapshot of the registration state of every Gravitino catalog seen by the load loop
+ * that belongs to the given metalake.
+ *
+ * @param metalake the metalake to filter by
+ * @return the registration states belonging to that metalake
+ */
+ public List<CatalogRegistrationState> getCatalogRegistrationStates(String metalake) {
+ return catalogStates.values().stream()
+ .filter(state -> state.getMetalake().equals(metalake))
+ .toList();
+ }
+
+ /**
+ * Checks whether the Trino server answered the last time the load loop probed it. No catalog can
+ * be registered while it does not.
+ *
+ * @return true if the Trino server is started, false otherwise
+ */
+ public boolean isTrinoReachable() {
+ return trinoReachable;
+ }
+
+ /**
+ * Retrieves the time of the last catalog load attempt.
+ *
+ * @return the time in milliseconds since the epoch, 0 if the load loop never ran
+ */
+ public long getLastLoadAttemptTimeMs() {
+ return lastLoadAttemptTimeMs;
+ }
+
+ /**
+ * Retrieves the last completed load attempt's success time, error and consecutive failure count
+ * as one consistent snapshot, so a caller needing more than one of those fields cannot observe a
+ * combination from two different load attempts.
+ *
+ * @return the load outcome
+ */
+ public LoadOutcome getLoadOutcome() {
+ return loadOutcome;
+ }
+
+ /**
+ * Retrieves the last error reported by each metalake, keyed by the metalake name.
+ *
+ * @return the metalake errors, empty if every metalake was loaded successfully
+ */
+ public Map<String, String> getMetalakeErrors() {
+ return loadOutcome.getMetalakeErrors();
+ }
+
+ /**
+ * Describes why a catalog is not registered in Trino, for use in error messages.
+ *
+ * @param metalake the name of the metalake the catalog belongs to
+ * @param trinoCatalogName the name the catalog would be registered under in Trino
+ * @return a human readable explanation
+ */
+ public String describeRegistrationFailure(String metalake, String trinoCatalogName) {
+ CatalogRegistrationState state = catalogStates.get(trinoCatalogName);
+ if (state != null && state.getLastError() != null) {
+ return String.format("%s: %s", state.getStatus(), state.getLastError());
+ }
+ // Read from the published outcome rather than the live map: an attempt that stopped at the
+ // reachability check touched no metalake, and quoting what an earlier one reported would
+ // contradict what load_status says about the same attempt.
+ String metalakeError = loadOutcome.getMetalakeErrors().get(metalake);
+ if (metalakeError != null) {
+ return String.format("Metalake %s could not be loaded: %s", metalake, metalakeError);
+ }
+ String lastLoadError = loadOutcome.lastError;
+ if (lastLoadError != null) {
+ return lastLoadError;
+ }
+ if (state != null) {
+ // The catalog is registered, so the caller is looking at a change that did not take effect.
+ return String.format(
+ "The catalog is %s and the last load attempt did not pick up the change.",
+ state.getStatus());
+ }
+ return "The catalog has not been loaded yet, please retry later.";
+ }
+
/**
* Retrieves the set of metalakes that have been used.
*
@@ -436,20 +926,26 @@ public class CatalogConnectorManager {
GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION,
"Multiple metalakes are not supported");
}
+ GravitinoMetalake metalake =
+ metalakes.computeIfAbsent(catalog.getMetalake(), this::retrieveMetalake);
+ catalog = withResolvedSecrets(catalog, metalake);
CatalogConnectorContext.Builder builder =
catalogConnectorFactory.createCatalogConnectorContextBuilder(catalog);
- builder
- .withMetalake(metalakes.computeIfAbsent(catalog.getMetalake(), this::retrieveMetalake))
- .withContext(context)
- .withConfig(config);
+ builder.withMetalake(metalake).withContext(context).withConfig(config);
CatalogConnectorContext connectorContext = builder.build();
String fullCatalogName = getTrinoCatalogName(catalog);
catalogConnectors.put(fullCatalogName, connectorContext);
LOG.info("Create connector %s successful", connectorName);
return connectorContext;
+ } catch (TrinoException e) {
+ // Already carries a specific error code and message from wherever it was thrown (e.g. the
+ // metalake mismatch check above, or connector instantiation failing several layers down);
+ // wrapping it again here would only bury that detail under a second, less specific layer.
+ LOG.error("Failed to create connector: %s%n%s", connectorName, CatalogRegister.describe(e));
+ throw e;
} catch (Exception e) {
- LOG.error(e, "Failed to create connector: %s", connectorName);
+ LOG.error("Failed to create connector: %s%n%s", connectorName, CatalogRegister.describe(e));
throw new TrinoException(
GravitinoErrorCode.GRAVITINO_OPERATION_FAILED,
"Failed to create connector: " + connectorName,
@@ -495,15 +991,133 @@ public class CatalogConnectorManager {
return false;
}
- /** Visible catalog properties overlaid with {@code getSecrets()}. */
- static Map<String, String> propsWithSecrets(Catalog catalog) {
- Map<String, String> props =
- new HashMap<>(catalog.properties() == null ? Map.of() : catalog.properties());
- props.putAll(catalog.supportsSecrets().getSecrets());
- return props;
+ /** The catalog properties as the Gravitino server reports them, secret URNs unresolved. */
+ static Map<String, String> visibleProps(Catalog catalog) {
+ return new HashMap<>(catalog.properties() == null ? Map.of() : catalog.properties());
+ }
+
+ /**
+ * Overlays the secrets the Gravitino server vends for this catalog onto its properties.
+ *
+ * <p>Resolved here, on the node that is about to build the connector, rather than once at
+ * registration time: the registered definition travels through a CREATE CATALOG statement that
+ * Trino persists as a catalog properties file, and a secret placed in it would be readable there
+ * for as long as the catalog exists.
+ */
+ private GravitinoCatalog withResolvedSecrets(
+ GravitinoCatalog catalog, GravitinoMetalake metalake) {
+ Map<String, String> secrets;
+ try {
+ secrets = metalake.loadCatalog(catalog.getName()).supportsSecrets().getSecrets();
+ } catch (Exception e) {
+ // Named explicitly: the caller's message only says the connector could not be created, and
+ // this step is the one that needs the Gravitino server reachable from this node.
+ throw new TrinoException(
+ GravitinoErrorCode.GRAVITINO_OPERATION_FAILED,
+ String.format(
+ "Failed to resolve the secrets of catalog %s in metalake %s: %s",
+ catalog.getName(), catalog.getMetalake(), toErrorMessage(e)),
+ e);
+ }
+ if (secrets.isEmpty()) {
+ return catalog;
+ }
+ Map<String, String> properties = new HashMap<>(catalog.getProperties());
+ properties.putAll(secrets);
+ return new GravitinoCatalog(
+ catalog.getMetalake(),
+ catalog.getProvider(),
+ catalog.getName(),
+ properties,
+ catalog.getLastModifiedTime());
}
public interface TrinoCatalogNameHandler {
String getCatalogName(String metalake, String catalog);
}
+
+ /**
+ * Immutable snapshot of the outcome of the last completed load attempt.
+ *
+ * <p>Everything a load attempt concluded travels together, so that a row built from it cannot
+ * combine facts from two different attempts, e.g. no error next to the metalake that produced
+ * one. The time of the last attempt is deliberately not part of it: it says when the loop last
+ * ran rather than what it concluded, and freezing it until an attempt completes would hide a loop
+ * that hangs half way.
+ */
+ public static final class LoadOutcome {
+ private final boolean trinoReachable;
+ private final long lastSuccessTimeMs;
+ private final String lastError;
+ private final long consecutiveFailures;
+ private final Map<String, String> metalakeErrors;
+
+ /**
+ * Constructs a new LoadOutcome.
+ *
+ * @param trinoReachable whether the Trino server answered during the attempt
+ * @param lastSuccessTimeMs the time of the last successful load, 0 if never successful
+ * @param lastError the error that made the last load fail, null if it succeeded
+ * @param consecutiveFailures the number of consecutive failed loads, 0 if the last succeeded
+ * @param metalakeErrors the error each metalake reported, empty if none did
+ */
+ public LoadOutcome(
+ boolean trinoReachable,
+ long lastSuccessTimeMs,
+ String lastError,
+ long consecutiveFailures,
+ Map<String, String> metalakeErrors) {
+ this.trinoReachable = trinoReachable;
+ this.lastSuccessTimeMs = lastSuccessTimeMs;
+ this.lastError = lastError;
+ this.consecutiveFailures = consecutiveFailures;
+ this.metalakeErrors = Map.copyOf(metalakeErrors);
+ }
+
+ /**
+ * Whether the Trino server answered during the attempt.
+ *
+ * @return true if the load loop reached the Trino server
+ */
+ public boolean isTrinoReachable() {
+ return trinoReachable;
+ }
+
+ /**
+ * Retrieves the error each metalake reported during the attempt.
+ *
+ * @return the errors keyed by metalake name, empty if none failed
+ */
+ public Map<String, String> getMetalakeErrors() {
+ return metalakeErrors;
+ }
+
+ /**
+ * Retrieves the time of the last successful catalog load.
+ *
+ * @return the time in milliseconds since the epoch, 0 if the load loop never succeeded
+ */
+ public long getLastSuccessTimeMs() {
+ return lastSuccessTimeMs;
+ }
+
+ /**
+ * Retrieves the error that made the last catalog load fail.
+ *
+ * @return the error message, null if the last load succeeded
+ */
+ @Nullable
+ public String getLastError() {
+ return lastError;
+ }
+
+ /**
+ * Retrieves the number of consecutive failed catalog loads.
+ *
+ * @return the failure count, 0 if the last load succeeded
+ */
+ public long getConsecutiveFailures() {
+ return consecutiveFailures;
+ }
+ }
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
index db06918904..61440365a0 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
@@ -22,6 +22,7 @@ import static org.apache.gravitino.trino.connector.GravitinoConfig.GRAVITINO_DYN
import static org.apache.gravitino.trino.connector.GravitinoConfig.GRAVITINO_DYNAMIC_CONNECTOR_CATALOG_CONFIG;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
import io.airlift.log.Logger;
import io.trino.jdbc.TrinoDriver;
@@ -38,6 +39,7 @@ import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.trino.connector.GravitinoConfig;
import org.apache.gravitino.trino.connector.GravitinoErrorCode;
@@ -80,25 +82,46 @@ public class CatalogRegister {
Pattern.CASE_INSENSITIVE);
private Connection connection;
- private boolean isStarted = false;
+ private volatile String lastConnectionError;
private String catalogStoreDirectory;
private GravitinoConfig config;
- boolean isTrinoStarted() {
- if (isStarted) {
- return true;
- }
-
+ /**
+ * Whether the Trino server currently answers over the connector's own JDBC connection.
+ *
+ * <p>Probed on every call rather than latched once: this gates a load cycle, and the connection
+ * is created lazily, so a coordinator that was reachable when the connector started can be gone
+ * by the next cycle. Answering from a past probe would keep the loop issuing statements over a
+ * connection that no longer works, and would report each catalog failing separately instead of
+ * the one reason they all did.
+ *
+ * @return true if the Trino server answered
+ */
+ boolean isTrinoReachable() {
String command = "SELECT 1";
try (Statement statement = connection.createStatement()) {
- isStarted = statement.execute(command);
- return isStarted;
+ boolean reachable = statement.execute(command);
+ lastConnectionError = null;
+ return reachable;
} catch (Exception e) {
- LOG.warn("Trino server is not started: %s", e.getMessage());
+ // Keep the reason: wrong credentials, a wrong port and a coordinator that is still booting
+ // are indistinguishable to the caller otherwise, and only the first two are actionable.
+ lastConnectionError = e.getMessage() == null ? e.getClass().getName() : e.getMessage();
+ LOG.warn("The Trino server is not reachable: %s", lastConnectionError);
return false;
}
}
+ /**
+ * Retrieves the error from the last failed attempt to reach the Trino server.
+ *
+ * @return the error message, null if the Trino server was reached
+ */
+ @Nullable
+ String getLastConnectionError() {
+ return lastConnectionError;
+ }
+
/**
* Initializes the catalog register with the specified Trino connector context and Gravitino
* configuration.
@@ -341,20 +364,33 @@ public class CatalogRegister {
config.toCatalogConfig());
}
- @VisibleForTesting
- static String redactSecrets(String createCatalogCommand) {
- return redactJsonSecrets(redactSqlSecrets(createCatalogCommand));
+ /**
+ * Renders a throwable, stack trace and cause chain included, with every secret it carries masked.
+ *
+ * <p>Logging a throwable directly would print the driver's own message, which for a failed CREATE
+ * CATALOG can hold the credentials the statement embedded. Rendering it here first is what makes
+ * that impossible, and it leaves the exception itself untouched. Cause cycles are handled by the
+ * JDK's own stack trace printer.
+ *
+ * @param e the throwable to render
+ * @return the rendered throwable with every secret value replaced
+ */
+ public static String describe(Throwable e) {
+ return redactSecrets(Throwables.getStackTraceAsString(e));
}
- // Some JDBC drivers echo the failing statement back in the exception message, which for a
- // failed CREATE CATALOG would otherwise carry its embedded credentials into every caller and
- // log line downstream. The original exception is deliberately not kept as the cause, since a
- // logged stack trace prints causes' messages too and would defeat the redaction.
- private static SQLException redactedSqlException(SQLException e) {
- String message = e.getMessage() == null ? null : redactSecrets(e.getMessage());
- SQLException redacted = new SQLException(message, e.getSQLState(), e.getErrorCode());
- redacted.setStackTrace(e.getStackTrace());
- return redacted;
+ /**
+ * Masks the values of the secret bearing properties of a CREATE CATALOG statement, in both its
+ * SQL assignments and the catalog JSON it carries.
+ *
+ * <p>Applied where a message is rendered for a user or a log rather than to the exceptions
+ * themselves, so that the original failure keeps its type and its cause chain.
+ *
+ * @param createCatalogCommand the text to redact
+ * @return the text with every secret value replaced
+ */
+ public static String redactSecrets(String createCatalogCommand) {
+ return redactJsonSecrets(redactSqlSecrets(createCatalogCommand));
}
private static String redactSqlSecrets(String createCatalogCommand) {
@@ -424,7 +460,7 @@ public class CatalogRegister {
throw new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, message, e);
} catch (Exception e) {
String message = String.format("Failed to register catalog %s", name);
- LOG.error(e, message);
+ LOG.error("%s%n%s", message, describe(e));
throw new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, message, e);
}
}
@@ -477,10 +513,13 @@ public class CatalogRegister {
statement.execute(sql);
return;
} catch (SQLException e) {
- throw redactedSqlException(e);
+ // Fail fast: the statement was rejected, so retrying it would only repeat the same
+ // rejection. The exception is passed on untouched, and the redaction happens where its
+ // message is rendered.
+ throw e;
} catch (Exception e) {
failedException = e;
- LOG.warn(e, "Failed to execute command: %s", redactSecrets(sql));
+ LOG.warn("Failed to execute command: %s%n%s", redactSecrets(sql), describe(e));
Thread.sleep(EXECUTE_QUERY_BACKOFF_TIME_SECOND * 1000);
}
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegistrationState.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegistrationState.java
new file mode 100644
index 0000000000..406ba3a82e
--- /dev/null
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegistrationState.java
@@ -0,0 +1,358 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.trino.connector.catalog;
+
+import com.google.common.base.Preconditions;
+import javax.annotation.Nullable;
+import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
+
+/**
+ * The registration state of a single Apache Gravitino catalog in Trino.
+ *
+ * <p>Instances are immutable and are always replaced as a whole, so a reader never observes a
+ * partially updated state.
+ */
+public final class CatalogRegistrationState {
+
+ /** The registration status of a catalog. */
+ public enum Status {
+ /** The catalog was registered in Trino with a CREATE CATALOG statement. */
+ REGISTERED,
+ /** The last registration attempt failed. */
+ FAILED,
+ /** The catalog matches `gravitino.trino.skip-catalog-patterns` and is not registered. */
+ SKIPPED,
+ /** The catalog type or provider is not supported by the connector. */
+ UNSUPPORTED
+ }
+
+ private final String metalake;
+ private final String catalogName;
+ private final String trinoCatalogName;
+ private final String provider;
+ private final Status status;
+ private final String lastError;
+ private final long lastAttemptTimeMs;
+ private final long lastSuccessTimeMs;
+ private final long failureCount;
+ // Whether this state comes from a registration that actually ran. A poll that found the catalog
+ // already up to date is still REGISTERED, but it did not register anything, so it must not
+ // stamp a new success time.
+ private final boolean reRegistered;
+
+ private CatalogRegistrationState(
+ String metalake,
+ String catalogName,
+ String trinoCatalogName,
+ String provider,
+ Status status,
+ String lastError,
+ long lastAttemptTimeMs,
+ long lastSuccessTimeMs,
+ long failureCount,
+ boolean reRegistered) {
+ this.metalake = metalake;
+ this.catalogName = catalogName;
+ this.trinoCatalogName = trinoCatalogName;
+ this.provider = provider;
+ this.status = status;
+ this.lastError = lastError;
+ this.lastAttemptTimeMs = lastAttemptTimeMs;
+ this.lastSuccessTimeMs = lastSuccessTimeMs;
+ this.failureCount = failureCount;
+ this.reRegistered = reRegistered;
+ }
+
+ /**
+ * Creates a state for a catalog that was registered in Trino successfully.
+ *
+ * @param catalog the Gravitino catalog
+ * @param trinoCatalogName the name the catalog is registered under in Trino
+ * @return the registration state
+ */
+ public static CatalogRegistrationState succeeded(
+ GravitinoCatalog catalog, String trinoCatalogName) {
+ return of(
+ catalog.getMetalake(),
+ catalog.getName(),
+ trinoCatalogName,
+ catalog.getProvider(),
+ Status.REGISTERED,
+ null,
+ true);
+ }
+
+ /**
+ * Creates a state for a catalog that a load attempt found already registered and up to date.
+ *
+ * <p>Reported the same way a fresh registration is, but it keeps the success time of the
+ * registration that put the catalog there: a poll that had nothing to do is not a new success,
+ * and advancing it every time would make last_success_time say nothing more than
+ * last_attempt_time already does.
+ *
+ * @param catalog the Gravitino catalog
+ * @param trinoCatalogName the name the catalog is registered under in Trino
+ * @return the registration state
+ */
+ public static CatalogRegistrationState unchanged(
+ GravitinoCatalog catalog, String trinoCatalogName) {
+ return of(
+ catalog.getMetalake(),
+ catalog.getName(),
+ trinoCatalogName,
+ catalog.getProvider(),
+ Status.REGISTERED,
+ null,
+ false);
+ }
+
+ /**
+ * Creates a state for a catalog whose registration attempt failed.
+ *
+ * @param metalake the name of the metalake the catalog belongs to
+ * @param catalogName the name of the catalog in Gravitino
+ * @param trinoCatalogName the name the catalog would be registered under in Trino
+ * @param provider the catalog provider, null if it could not be determined
+ * @param error the error that prevented the registration
+ * @return the registration state
+ */
+ public static CatalogRegistrationState failed(
+ String metalake,
+ String catalogName,
+ String trinoCatalogName,
+ @Nullable String provider,
+ String error) {
+ return of(metalake, catalogName, trinoCatalogName, provider, Status.FAILED, error);
+ }
+
+ /**
+ * Creates a state for a catalog that is deliberately not registered because it matches {@code
+ * gravitino.trino.skip-catalog-patterns}.
+ *
+ * @param metalake the name of the metalake the catalog belongs to
+ * @param catalogName the name of the catalog in Gravitino
+ * @param trinoCatalogName the name the catalog would be registered under in Trino
+ * @param reason a human readable explanation of why the catalog is skipped
+ * @return the registration state
+ */
+ public static CatalogRegistrationState skipped(
+ String metalake, String catalogName, String trinoCatalogName, String reason) {
+ return of(metalake, catalogName, trinoCatalogName, null, Status.SKIPPED, reason);
+ }
+
+ /**
+ * Creates a state for a catalog the connector cannot register because of its type or provider.
+ *
+ * @param metalake the name of the metalake the catalog belongs to
+ * @param catalogName the name of the catalog in Gravitino
+ * @param trinoCatalogName the name the catalog would be registered under in Trino
+ * @param provider the catalog provider, null if it could not be determined
+ * @param reason a human readable explanation of why the catalog is not supported
+ * @return the registration state
+ */
+ public static CatalogRegistrationState unsupported(
+ String metalake,
+ String catalogName,
+ String trinoCatalogName,
+ @Nullable String provider,
+ String reason) {
+ return of(metalake, catalogName, trinoCatalogName, provider, Status.UNSUPPORTED, reason);
+ }
+
+ // Shared by the factory methods above: they differ only in status and a couple of fields, and
+ // funneling them through one constructor call keeps a newly added field from being forgotten in
+ // one of several near-identical call sites.
+ private static CatalogRegistrationState of(
+ String metalake,
+ String catalogName,
+ String trinoCatalogName,
+ @Nullable String provider,
+ Status status,
+ @Nullable String lastError) {
+ return of(metalake, catalogName, trinoCatalogName, provider, status, lastError, true);
+ }
+
+ private static CatalogRegistrationState of(
+ String metalake,
+ String catalogName,
+ String trinoCatalogName,
+ @Nullable String provider,
+ Status status,
+ @Nullable String lastError,
+ boolean reRegistered) {
+ Preconditions.checkArgument(metalake != null, "metalake must not be null");
+ Preconditions.checkArgument(catalogName != null, "catalogName must not be null");
+ Preconditions.checkArgument(trinoCatalogName != null, "trinoCatalogName must not be null");
+ Preconditions.checkArgument(
+ status == Status.REGISTERED || lastError != null,
+ "lastError must not be null for status %s",
+ status);
+ long now = System.currentTimeMillis();
+ return new CatalogRegistrationState(
+ metalake,
+ catalogName,
+ trinoCatalogName,
+ provider,
+ status,
+ lastError,
+ now,
+ status == Status.REGISTERED ? now : 0,
+ status == Status.FAILED ? 1 : 0,
+ reRegistered);
+ }
+
+ /**
+ * Returns this state with the history carried over from the state it replaces. A catalog keeps
+ * the time it was last registered even after it starts failing, and consecutive failures are
+ * counted across attempts.
+ *
+ * @param previous the state being replaced, null if this catalog was never seen before
+ * @return this state if there is no history to carry over, a new state carrying it otherwise
+ */
+ CatalogRegistrationState withHistoryOf(@Nullable CatalogRegistrationState previous) {
+ if (previous == null) {
+ return this;
+ }
+ // A registration that actually ran stamps its own success time; a poll that found the
+ // catalog unchanged, and every other status, keeps the last one. A catalog observed
+ // registered with no earlier success time to keep, e.g. one whose previous row was a failed
+ // unregistration, stamps this observation rather than reporting none at all.
+ long successTime;
+ if (status != Status.REGISTERED) {
+ successTime = previous.lastSuccessTimeMs;
+ } else if (reRegistered || previous.lastSuccessTimeMs == 0) {
+ successTime = lastSuccessTimeMs;
+ } else {
+ successTime = previous.lastSuccessTimeMs;
+ }
+ // Consecutive failures only accumulate while the catalog keeps failing. Any other status
+ // interrupts the run, and its own count is already zero.
+ long failures = status == Status.FAILED ? previous.failureCount + 1 : failureCount;
+ // A failure that happens before the provider is known (e.g. metalake.loadCatalog() itself
+ // throws) must not blank out a provider a previous attempt already discovered.
+ String effectiveProvider = provider != null ? provider : previous.provider;
+ if (successTime == lastSuccessTimeMs
+ && failures == failureCount
+ && effectiveProvider == provider) {
+ return this;
+ }
+ return new CatalogRegistrationState(
+ metalake,
+ catalogName,
+ trinoCatalogName,
+ effectiveProvider,
+ status,
+ lastError,
+ lastAttemptTimeMs,
+ successTime,
+ failures,
+ reRegistered);
+ }
+
+ /**
+ * Retrieves the name of the metalake the catalog belongs to.
+ *
+ * @return the metalake name
+ */
+ public String getMetalake() {
+ return metalake;
+ }
+
+ /**
+ * Retrieves the name of the catalog in Gravitino.
+ *
+ * @return the catalog name
+ */
+ public String getCatalogName() {
+ return catalogName;
+ }
+
+ /**
+ * Retrieves the name the catalog is registered under in Trino.
+ *
+ * @return the Trino catalog name
+ */
+ public String getTrinoCatalogName() {
+ return trinoCatalogName;
+ }
+
+ /**
+ * Retrieves the catalog provider.
+ *
+ * @return the provider, null if it could not be determined
+ */
+ @Nullable
+ public String getProvider() {
+ return provider;
+ }
+
+ /**
+ * Retrieves the registration status of the catalog.
+ *
+ * @return the status
+ */
+ public Status getStatus() {
+ return status;
+ }
+
+ /**
+ * Retrieves the error or the reason why the catalog is not registered.
+ *
+ * @return the message, null if the catalog is registered
+ */
+ @Nullable
+ public String getLastError() {
+ return lastError;
+ }
+
+ /**
+ * Retrieves the time of the last registration attempt.
+ *
+ * @return the time in milliseconds since the epoch
+ */
+ public long getLastAttemptTimeMs() {
+ return lastAttemptTimeMs;
+ }
+
+ /**
+ * Retrieves the time of the last successful registration.
+ *
+ * @return the time in milliseconds since the epoch, 0 if the catalog was never registered
+ */
+ public long getLastSuccessTimeMs() {
+ return lastSuccessTimeMs;
+ }
+
+ /**
+ * Retrieves the number of consecutive failed registration attempts.
+ *
+ * @return the failure count, 0 if the last attempt succeeded
+ */
+ public long getFailureCount() {
+ return failureCount;
+ }
+
+ @Override
+ public String toString() {
+ return String.format(
+ "CatalogRegistrationState{metalake=%s, catalog=%s, trinoCatalog=%s, provider=%s,"
+ + " status=%s, lastError=%s, failureCount=%d}",
+ metalake, catalogName, trinoCatalogName, provider, status, lastError, failureCount);
+ }
+}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnector.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnector.java
index 57ee95c0ea..5a4260af48 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnector.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnector.java
@@ -58,14 +58,28 @@ import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFac
public class GravitinoSystemConnector implements Connector {
private final GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory;
+ private final GravitinoSystemTableFactory systemTableFactory;
/**
* Constructs a new GravitinoSystemConnector.
*
* @param gravitinoStoredProcedureFactory the factory for creating stored procedures
+ * @param systemTableFactory the registry of system tables to expose
*/
- public GravitinoSystemConnector(GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory) {
+ public GravitinoSystemConnector(
+ GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory,
+ GravitinoSystemTableFactory systemTableFactory) {
this.gravitinoStoredProcedureFactory = gravitinoStoredProcedureFactory;
+ this.systemTableFactory = systemTableFactory;
+ }
+
+ /**
+ * Retrieves the registry of system tables this connector exposes.
+ *
+ * @return the system table factory
+ */
+ protected GravitinoSystemTableFactory getSystemTableFactory() {
+ return systemTableFactory;
}
@Override
@@ -86,7 +100,7 @@ public class GravitinoSystemConnector implements Connector {
}
protected ConnectorMetadata createMetadata() {
- return new GravitinoSystemConnectorMetadata();
+ return new GravitinoSystemConnectorMetadata(systemTableFactory);
}
@Override
@@ -106,7 +120,7 @@ public class GravitinoSystemConnector implements Connector {
}
protected ConnectorPageSourceProvider createPageSourceProvider() {
- return new DatasourceProvider();
+ return new DatasourceProvider(systemTableFactory);
}
/** The transaction handle for Gravitino system connector. */
@@ -118,6 +132,17 @@ public class GravitinoSystemConnector implements Connector {
/** The datasource provider. */
public static class DatasourceProvider implements ConnectorPageSourceProvider {
+ private final GravitinoSystemTableFactory systemTableFactory;
+
+ /**
+ * Constructs a new DatasourceProvider.
+ *
+ * @param systemTableFactory the registry the page data is read from
+ */
+ public DatasourceProvider(GravitinoSystemTableFactory systemTableFactory) {
+ this.systemTableFactory = systemTableFactory;
+ }
+
@Override
public ConnectorPageSource createPageSource(
ConnectorTransactionHandle transaction,
@@ -129,7 +154,16 @@ public class GravitinoSystemConnector implements Connector {
SchemaTableName tableName =
((GravitinoSystemConnectorMetadata.SystemTableHandle) table).getName();
- return createPageSource(GravitinoSystemTableFactory.loadPageData(tableName));
+ Page page = systemTableFactory.loadPageData(tableName);
+
+ // Project the page down to the requested columns. Trino only expects the columns it asked
+ // for, so handing it the whole row breaks any query that is not a SELECT *.
+ int[] channels = new int[columns.size()];
+ for (int i = 0; i < channels.length; i++) {
+ channels[i] =
+ ((GravitinoSystemConnectorMetadata.SystemColumnHandle) columns.get(i)).getIndex();
+ }
+ return createPageSource(page.getColumns(channels));
}
protected ConnectorPageSource createPageSource(Page page) {
@@ -161,16 +195,31 @@ public class GravitinoSystemConnector implements Connector {
/** The split. */
public abstract static class Split implements ConnectorSplit {
+ // The system table data lives on the coordinator only: the catalog load loop runs there, and
+ // the registration state it records is never replicated to workers. Set once by the
+ // coordinator's GravitinoConnectorFactory.create(), which necessarily runs before any query
+ // can reach the scheduler, and read by createSplit() below to bake into every split it
+ // creates. It cannot be relied on directly by isRemotelyAccessible()/getAddresses(): Trino
+ // serializes splits to JSON and may evaluate those methods after deserializing one on a
+ // worker JVM, where this static field was never set. Carrying the address as a serialized
+ // instance field instead makes the pinning survive that trip.
+ private static volatile HostAddress currentCoordinatorAddress;
+
protected final SchemaTableName tableName;
+ private final HostAddress coordinatorAddress;
/**
- * Constructs a new Split with the specified table name.
+ * Constructs a new Split with the specified table name and coordinator address.
*
* @param tableName the table name
+ * @param coordinatorAddress the host and port of the Trino coordinator, null if unknown
*/
@JsonCreator
- public Split(@JsonProperty("tableName") SchemaTableName tableName) {
+ public Split(
+ @JsonProperty("tableName") SchemaTableName tableName,
+ @JsonProperty("coordinatorAddress") HostAddress coordinatorAddress) {
this.tableName = tableName;
+ this.coordinatorAddress = coordinatorAddress;
}
/**
@@ -183,14 +232,43 @@ public class GravitinoSystemConnector implements Connector {
return tableName;
}
+ /**
+ * Retrieves the coordinator address this split is pinned to.
+ *
+ * @return the host and port of the Trino coordinator, null if unknown
+ */
+ @JsonProperty
+ public HostAddress getCoordinatorAddress() {
+ return coordinatorAddress;
+ }
+
+ /**
+ * Sets the coordinator address that new system table splits are pinned to.
+ *
+ * @param address the host and port of the Trino coordinator
+ */
+ public static void setCoordinatorAddress(HostAddress address) {
+ currentCoordinatorAddress = address;
+ }
+
+ /**
+ * Retrieves the coordinator address recorded by {@link #setCoordinatorAddress(HostAddress)} in
+ * this JVM, for {@code createSplit()} implementations to bake into new splits.
+ *
+ * @return the host and port of the Trino coordinator, null if unknown in this JVM
+ */
+ public static HostAddress getCurrentCoordinatorAddress() {
+ return currentCoordinatorAddress;
+ }
+
@Override
public boolean isRemotelyAccessible() {
- return true;
+ return coordinatorAddress == null;
}
@Override
public List<HostAddress> getAddresses() {
- return Collections.emptyList();
+ return coordinatorAddress == null ? Collections.emptyList() : List.of(coordinatorAddress);
}
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnectorMetadata.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnectorMetadata.java
index faeb7f35b7..1a95100401 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnectorMetadata.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnectorMetadata.java
@@ -38,6 +38,17 @@ import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTableFac
/** An implementation of Apache Gravitino System connector Metadata */
public class GravitinoSystemConnectorMetadata implements ConnectorMetadata {
+ private final GravitinoSystemTableFactory systemTableFactory;
+
+ /**
+ * Constructs a new GravitinoSystemConnectorMetadata.
+ *
+ * @param systemTableFactory the registry of system tables to expose
+ */
+ public GravitinoSystemConnectorMetadata(GravitinoSystemTableFactory systemTableFactory) {
+ this.systemTableFactory = systemTableFactory;
+ }
+
@Override
public List<String> listSchemaNames(ConnectorSession session) {
return List.of(GravitinoSystemTable.SYSTEM_TABLE_SCHEMA_NAME);
@@ -45,7 +56,7 @@ public class GravitinoSystemConnectorMetadata implements ConnectorMetadata {
@Override
public List<SchemaTableName> listTables(ConnectorSession session, Optional<String> schemaName) {
- return GravitinoSystemTableFactory.SYSTEM_TABLES.keySet().stream().toList();
+ return systemTableFactory.listTableNames();
}
@Override
@@ -54,16 +65,14 @@ public class GravitinoSystemConnectorMetadata implements ConnectorMetadata {
SchemaTableName tableName,
Optional<ConnectorTableVersion> startVersion,
Optional<ConnectorTableVersion> endVersion) {
- return GravitinoSystemTableFactory.SYSTEM_TABLES.get(tableName) != null
- ? new SystemTableHandle(tableName)
- : null;
+ return systemTableFactory.tableExists(tableName) ? new SystemTableHandle(tableName) : null;
}
@Override
public ConnectorTableMetadata getTableMetadata(
ConnectorSession session, ConnectorTableHandle table) {
SchemaTableName tableName = ((SystemTableHandle) table).name;
- return GravitinoSystemTableFactory.getTableMetaData(tableName);
+ return systemTableFactory.getTableMetaData(tableName);
}
@Override
@@ -71,8 +80,7 @@ public class GravitinoSystemConnectorMetadata implements ConnectorMetadata {
ConnectorSession session, ConnectorTableHandle tableHandle) {
SchemaTableName tableName = ((SystemTableHandle) tableHandle).name;
Map<String, ColumnHandle> columnHandles = new HashMap<>();
- List<ColumnMetadata> columns =
- GravitinoSystemTableFactory.getTableMetaData(tableName).getColumns();
+ List<ColumnMetadata> columns = systemTableFactory.getTableMetaData(tableName).getColumns();
for (int i = 0; i < columns.size(); i++) {
columnHandles.put(columns.get(i).getName(), new SystemColumnHandle(i));
}
@@ -83,7 +91,8 @@ public class GravitinoSystemConnectorMetadata implements ConnectorMetadata {
public ColumnMetadata getColumnMetadata(
ConnectorSession session, ConnectorTableHandle tableHandle, ColumnHandle columnHandle) {
SchemaTableName tableName = ((SystemTableHandle) tableHandle).name;
- return GravitinoSystemTableFactory.getTableMetaData(tableName)
+ return systemTableFactory
+ .getTableMetaData(tableName)
.getColumns()
.get(((SystemColumnHandle) columnHandle).index);
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/AlterCatalogStoredProcedure.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/AlterCatalogStoredProcedure.java
index 55f479ca56..43f53933e9 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/AlterCatalogStoredProcedure.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/AlterCatalogStoredProcedure.java
@@ -136,15 +136,15 @@ public class AlterCatalogStoredProcedure extends GravitinoStoredProcedure {
.alterCatalog(catalogName, changes.toArray(changes.toArray(new CatalogChange[0])));
catalogConnectorManager.loadMetalakeSync();
- catalogConnectorContext =
- catalogConnectorManager.getCatalogConnector(
- catalogConnectorManager.getTrinoCatalogName(metalake, catalogName));
+ String trinoCatalogName = catalogConnectorManager.getTrinoCatalogName(metalake, catalogName);
+ catalogConnectorContext = catalogConnectorManager.getCatalogConnector(trinoCatalogName);
if (catalogConnectorContext == null
|| catalogConnectorContext.getCatalog().getLastModifiedTime()
== oldCatalog.getLastModifiedTime()) {
throw new TrinoException(
GravitinoErrorCode.GRAVITINO_OPERATION_FAILED,
- "Update catalog failed due to the reloading process fails");
+ "Update catalog failed due to the reloading process fails. "
+ + catalogConnectorManager.describeRegistrationFailure(metalake, trinoCatalogName));
}
LOG.info("Alter catalog %s in metalake %s successfully.", catalogName, metalake);
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/CreateCatalogStoredProcedure.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/CreateCatalogStoredProcedure.java
index 48c67c729c..2bc7180d8a 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/CreateCatalogStoredProcedure.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/CreateCatalogStoredProcedure.java
@@ -37,6 +37,7 @@ import org.apache.gravitino.exceptions.CatalogAlreadyExistsException;
import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.trino.connector.GravitinoErrorCode;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorManager;
+import org.apache.gravitino.trino.connector.catalog.CatalogRegister;
import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTable;
/**
@@ -114,11 +115,12 @@ public class CreateCatalogStoredProcedure extends GravitinoStoredProcedure {
catalogName, Catalog.Type.RELATIONAL, provider, "Trino created", properties);
catalogConnectorManager.loadMetalakeSync();
- if (!catalogConnectorManager.catalogConnectorExist(
- catalogConnectorManager.getTrinoCatalogName(metalake, catalogName))) {
+ String trinoCatalogName = catalogConnectorManager.getTrinoCatalogName(metalake, catalogName);
+ if (!catalogConnectorManager.catalogConnectorExist(trinoCatalogName)) {
throw new TrinoException(
GravitinoErrorCode.GRAVITINO_OPERATION_FAILED,
- "Create catalog failed due to the loading process fails");
+ "Create catalog failed due to the loading process fails. "
+ + catalogConnectorManager.describeRegistrationFailure(metalake, trinoCatalogName));
}
LOG.info("Create catalog %s in metalake %s successfully.", catalogName, metalake);
@@ -132,9 +134,14 @@ public class CreateCatalogStoredProcedure extends GravitinoStoredProcedure {
GravitinoErrorCode.GRAVITINO_CATALOG_ALREADY_EXISTS,
"Catalog " + NameIdentifier.of(metalake, catalogName) + " already exists in the server.");
} catch (Exception e) {
+ // The failure can come from a CREATE CATALOG the load loop ran, whose message may carry the
+ // credentials the statement embedded, so it is masked before reaching the caller.
throw new TrinoException(
GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION,
- "Create catalog failed. " + (StringUtils.isEmpty(e.getMessage()) ? "" : e.getMessage()),
+ "Create catalog failed. "
+ + (StringUtils.isEmpty(e.getMessage())
+ ? ""
+ : CatalogRegister.redactSecrets(e.getMessage())),
e);
}
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/DropCatalogStoredProcedure.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/DropCatalogStoredProcedure.java
index c6646de1f0..eea2fd7815 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/DropCatalogStoredProcedure.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/DropCatalogStoredProcedure.java
@@ -33,6 +33,7 @@ import org.apache.gravitino.exceptions.NoSuchMetalakeException;
import org.apache.gravitino.trino.connector.GravitinoErrorCode;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorManager;
+import org.apache.gravitino.trino.connector.catalog.CatalogRegister;
import org.apache.gravitino.trino.connector.system.table.GravitinoSystemTable;
/**
@@ -101,6 +102,18 @@ public class DropCatalogStoredProcedure extends GravitinoStoredProcedure {
GravitinoErrorCode.GRAVITINO_CATALOG_NOT_EXISTS,
"Catalog " + NameIdentifier.of(metalake, catalogName) + " not exists.");
}
+ // Refresh before returning: the catalog left a state row behind when its registration
+ // failed, and catalog_status would keep reporting a catalog that no longer exists until
+ // the next poll of the load loop. The drop itself has already succeeded, so a refresh
+ // that does not complete must not be reported as its failure; the scheduled poll will
+ // catch up.
+ try {
+ catalogConnectorManager.loadMetalakeSync();
+ } catch (Exception e) {
+ LOG.warn(
+ "Dropped catalog %s in metalake %s, but refreshing the registration state failed: %s",
+ catalogName, metalake, CatalogRegister.describe(e));
+ }
LOG.info(
"Drop catalog %s in metalake %s from server (no local connector) successfully.",
catalogName, metalake);
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTable.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTable.java
index eb2328b0b5..136ec9290c 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTable.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTable.java
@@ -18,8 +18,13 @@
*/
package org.apache.gravitino.trino.connector.system.table;
+import static io.trino.spi.type.VarcharType.VARCHAR;
+
import io.trino.spi.Page;
+import io.trino.spi.block.BlockBuilder;
import io.trino.spi.connector.ConnectorTableMetadata;
+import java.time.Instant;
+import javax.annotation.Nullable;
/** Gravitino System table interfaces */
public abstract class GravitinoSystemTable {
@@ -40,4 +45,34 @@ public abstract class GravitinoSystemTable {
* @return a Page object containing all the table data
*/
public abstract Page loadPageData();
+
+ /**
+ * Appends a string to a VARCHAR column, writing a null when the value is absent.
+ *
+ * @param builder the column builder to append to
+ * @param value the value to append, may be null
+ */
+ protected static void writeNullableString(BlockBuilder builder, @Nullable String value) {
+ if (value == null) {
+ builder.appendNull();
+ } else {
+ VARCHAR.writeString(builder, value);
+ }
+ }
+
+ /**
+ * Appends a timestamp to a VARCHAR column as an ISO-8601 UTC string, writing a null when the
+ * timestamp is unset. Timestamps are rendered as strings because the block encoding of
+ * TimestampType differs across the supported Trino versions.
+ *
+ * @param builder the column builder to append to
+ * @param timeMs the time in milliseconds since the epoch, 0 when unset
+ */
+ protected static void writeTime(BlockBuilder builder, long timeMs) {
+ if (timeMs == 0) {
+ builder.appendNull();
+ } else {
+ VARCHAR.writeString(builder, Instant.ofEpochMilli(timeMs).toString());
+ }
+ }
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableCatalog.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableCatalog.java
index aac74a4762..55e4376ee9 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableCatalog.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableCatalog.java
@@ -45,6 +45,8 @@ public class GravitinoSystemTableCatalog extends GravitinoSystemTable {
public static final SchemaTableName TABLE_NAME =
new SchemaTableName(SYSTEM_TABLE_SCHEMA_NAME, "catalog");
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
private static final ConnectorTableMetadata TABLE_METADATA =
new ConnectorTableMetadata(
TABLE_NAME,
@@ -54,14 +56,18 @@ public class GravitinoSystemTableCatalog extends GravitinoSystemTable {
ColumnMetadata.builder().setName("properties").setType(VARCHAR).build()));
private final CatalogConnectorManager catalogConnectorManager;
+ private final String metalake;
/**
* Constructs a new GravitinoSystemTableCatalog.
*
* @param catalogConnectorManager the manager for catalog connectors
+ * @param metalake the metalake to report on
*/
- public GravitinoSystemTableCatalog(CatalogConnectorManager catalogConnectorManager) {
+ public GravitinoSystemTableCatalog(
+ CatalogConnectorManager catalogConnectorManager, String metalake) {
this.catalogConnectorManager = catalogConnectorManager;
+ this.metalake = metalake;
}
@Override
@@ -69,14 +75,21 @@ public class GravitinoSystemTableCatalog extends GravitinoSystemTable {
List<GravitinoCatalog> gravitinoCatalogs = new ArrayList<>();
// retrieve catalogs form the Gravitino server with the configuration metalakes,
// the catalogConnectorManager does not manager catalogs in worker nodes
- catalogConnectorManager
- .getUsedMetalakes()
+ // Only the metalake this connector is configured with: the manager is shared by every entry
+ // catalog in this Trino.
+ catalogConnectorManager.getUsedMetalakes().stream()
+ .filter(metalake::equals)
.forEach(
(metalakeName) -> {
GravitinoMetalake metalake = catalogConnectorManager.getMetalake(metalakeName);
Catalog[] catalogs = metalake.listCatalogsInfo();
for (Catalog catalog : catalogs) {
- if (catalogConnectorManager.skipCatalog(catalog.name())) {
+ // Must match against the same Trino-qualified name the load loop skips against
+ // (quoted "metalake.catalog" in multi-metalake mode), or a skip pattern written
+ // against the qualified name never matches here.
+ String trinoCatalogName =
+ catalogConnectorManager.getTrinoCatalogName(metalakeName, catalog.name());
+ if (catalogConnectorManager.skipCatalog(trinoCatalogName)) {
continue;
}
if (catalog.type() == Catalog.Type.RELATIONAL) {
@@ -98,7 +111,7 @@ public class GravitinoSystemTableCatalog extends GravitinoSystemTable {
try {
VARCHAR.writeString(
propertyColumnBuilder,
- new ObjectMapper().writeValueAsString(new TreeMap<>(catalog.getProperties())));
+ OBJECT_MAPPER.writeValueAsString(new TreeMap<>(catalog.getProperties())));
} catch (JsonProcessingException e) {
throw new TrinoException(
GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT, "Invalid property format", e); //
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableCatalogStatus.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableCatalogStatus.java
new file mode 100644
index 0000000000..de4ed697c7
--- /dev/null
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableCatalogStatus.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.trino.connector.system.table;
+
+import static io.trino.spi.type.BigintType.BIGINT;
+import static io.trino.spi.type.VarcharType.VARCHAR;
+
+import io.trino.spi.Page;
+import io.trino.spi.block.BlockBuilder;
+import io.trino.spi.connector.ColumnMetadata;
+import io.trino.spi.connector.ConnectorTableMetadata;
+import io.trino.spi.connector.SchemaTableName;
+import java.util.List;
+import org.apache.gravitino.trino.connector.catalog.CatalogConnectorManager;
+import org.apache.gravitino.trino.connector.catalog.CatalogRegistrationState;
+
+/**
+ * An implementation of the catalog status system table.
+ *
+ * <p>It reports why every Apache Gravitino catalog is or is not registered in Trino, so that a
+ * catalog missing from SHOW CATALOGS can be diagnosed without reading the coordinator log.
+ */
+public class GravitinoSystemTableCatalogStatus extends GravitinoSystemTable {
+
+ /** The name of the catalog status system table. */
+ public static final SchemaTableName TABLE_NAME =
+ new SchemaTableName(SYSTEM_TABLE_SCHEMA_NAME, "catalog_status");
+
+ private static final ConnectorTableMetadata TABLE_METADATA =
+ new ConnectorTableMetadata(
+ TABLE_NAME,
+ List.of(
+ ColumnMetadata.builder().setName("metalake").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("catalog_name").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("trino_catalog_name").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("provider").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("status").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("last_error").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("last_attempt_time").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("last_success_time").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("failure_count").setType(BIGINT).build()));
+
+ private final CatalogConnectorManager catalogConnectorManager;
+ private final String metalake;
+
+ /**
+ * Constructs a new GravitinoSystemTableCatalogStatus.
+ *
+ * @param catalogConnectorManager the manager for catalog connectors
+ * @param metalake the metalake to report on
+ */
+ public GravitinoSystemTableCatalogStatus(
+ CatalogConnectorManager catalogConnectorManager, String metalake) {
+ this.catalogConnectorManager = catalogConnectorManager;
+ this.metalake = metalake;
+ }
+
+ @Override
+ public Page loadPageData() {
+ // Take a snapshot first, the load loop writes these states concurrently and the column
+ // builders must all end up with the same number of positions.
+ // The load loop is shared by every entry catalog in this Trino, so report only the metalake
+ // this connector is configured with.
+ List<CatalogRegistrationState> states =
+ catalogConnectorManager.getCatalogRegistrationStates(metalake);
+ int size = states.size();
+
+ BlockBuilder metalakeColumnBuilder = VARCHAR.createBlockBuilder(null, size);
+ BlockBuilder catalogNameColumnBuilder = VARCHAR.createBlockBuilder(null, size);
+ BlockBuilder trinoCatalogNameColumnBuilder = VARCHAR.createBlockBuilder(null, size);
+ BlockBuilder providerColumnBuilder = VARCHAR.createBlockBuilder(null, size);
+ BlockBuilder statusColumnBuilder = VARCHAR.createBlockBuilder(null, size);
+ BlockBuilder lastErrorColumnBuilder = VARCHAR.createBlockBuilder(null, size);
+ BlockBuilder lastAttemptTimeColumnBuilder = VARCHAR.createBlockBuilder(null, size);
+ BlockBuilder lastSuccessTimeColumnBuilder = VARCHAR.createBlockBuilder(null, size);
+ BlockBuilder failureCountColumnBuilder = BIGINT.createBlockBuilder(null, size);
+
+ for (CatalogRegistrationState state : states) {
+ VARCHAR.writeString(metalakeColumnBuilder, state.getMetalake());
+ VARCHAR.writeString(catalogNameColumnBuilder, state.getCatalogName());
+ VARCHAR.writeString(trinoCatalogNameColumnBuilder, state.getTrinoCatalogName());
+ writeNullableString(providerColumnBuilder, state.getProvider());
+ VARCHAR.writeString(statusColumnBuilder, state.getStatus().name());
+ writeNullableString(lastErrorColumnBuilder, state.getLastError());
+ writeTime(lastAttemptTimeColumnBuilder, state.getLastAttemptTimeMs());
+ writeTime(lastSuccessTimeColumnBuilder, state.getLastSuccessTimeMs());
+ BIGINT.writeLong(failureCountColumnBuilder, state.getFailureCount());
+ }
+
+ return new Page(
+ size,
+ metalakeColumnBuilder.build(),
+ catalogNameColumnBuilder.build(),
+ trinoCatalogNameColumnBuilder.build(),
+ providerColumnBuilder.build(),
+ statusColumnBuilder.build(),
+ lastErrorColumnBuilder.build(),
+ lastAttemptTimeColumnBuilder.build(),
+ lastSuccessTimeColumnBuilder.build(),
+ failureCountColumnBuilder.build());
+ }
+
+ @Override
+ public ConnectorTableMetadata getTableMetaData() {
+ return TABLE_METADATA;
+ }
+}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableFactory.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableFactory.java
index 4995e69821..4b41c8d623 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableFactory.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableFactory.java
@@ -23,6 +23,7 @@ import io.trino.spi.Page;
import io.trino.spi.connector.ConnectorTableMetadata;
import io.trino.spi.connector.SchemaTableName;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import org.apache.gravitino.trino.connector.catalog.CatalogConnectorManager;
@@ -30,25 +31,39 @@ import org.apache.gravitino.trino.connector.catalog.CatalogConnectorManager;
public class GravitinoSystemTableFactory {
private final CatalogConnectorManager catalogConnectorManager;
- /** Map of all registered system tables, keyed by their schema-qualified names. */
- public static final Map<SchemaTableName, GravitinoSystemTable> SYSTEM_TABLES = new HashMap<>();
+ private final String metalake;
+
+ // Per instance, not static: the tables are bound to one CatalogConnectorManager, and only the
+ // manager on the coordinator runs the load loop that fills in the registration state. A shared
+ // registry would let any other connector in the JVM take it over.
+ private final Map<SchemaTableName, GravitinoSystemTable> systemTables = new HashMap<>();
/**
* Constructs a new GravitinoSystemTableFactory.
*
* @param catalogConnectorManager the manager for catalog connectors
+ * @param metalake the metalake this connector is configured with; the tables only report on it,
+ * so that two entry catalogs pointed at different metalakes do not report each other's state
*/
- public GravitinoSystemTableFactory(CatalogConnectorManager catalogConnectorManager) {
+ public GravitinoSystemTableFactory(
+ CatalogConnectorManager catalogConnectorManager, String metalake) {
this.catalogConnectorManager = catalogConnectorManager;
+ this.metalake = metalake;
registerSystemTables();
}
/** Register all the system tables */
private void registerSystemTables() {
- SYSTEM_TABLES.put(
+ systemTables.put(
GravitinoSystemTableCatalog.TABLE_NAME,
- new GravitinoSystemTableCatalog(catalogConnectorManager));
+ new GravitinoSystemTableCatalog(catalogConnectorManager, metalake));
+ systemTables.put(
+ GravitinoSystemTableCatalogStatus.TABLE_NAME,
+ new GravitinoSystemTableCatalogStatus(catalogConnectorManager, metalake));
+ systemTables.put(
+ GravitinoSystemTableLoadStatus.TABLE_NAME,
+ new GravitinoSystemTableLoadStatus(catalogConnectorManager, metalake));
}
/**
@@ -58,9 +73,9 @@ public class GravitinoSystemTableFactory {
* @return the page containing the table's data
* @throws IllegalArgumentException if the table does not exist
*/
- public static Page loadPageData(SchemaTableName tableName) {
- Preconditions.checkArgument(SYSTEM_TABLES.containsKey(tableName), "table does not exist");
- return SYSTEM_TABLES.get(tableName).loadPageData();
+ public Page loadPageData(SchemaTableName tableName) {
+ Preconditions.checkArgument(systemTables.containsKey(tableName), "table does not exist");
+ return systemTables.get(tableName).loadPageData();
}
/**
@@ -70,8 +85,27 @@ public class GravitinoSystemTableFactory {
* @return the table metadata
* @throws IllegalArgumentException if the table does not exist
*/
- public static ConnectorTableMetadata getTableMetaData(SchemaTableName tableName) {
- Preconditions.checkArgument(SYSTEM_TABLES.containsKey(tableName), "table does not exist");
- return SYSTEM_TABLES.get(tableName).getTableMetaData();
+ public ConnectorTableMetadata getTableMetaData(SchemaTableName tableName) {
+ Preconditions.checkArgument(systemTables.containsKey(tableName), "table does not exist");
+ return systemTables.get(tableName).getTableMetaData();
+ }
+
+ /**
+ * Lists the names of every registered system table.
+ *
+ * @return the schema-qualified table names
+ */
+ public List<SchemaTableName> listTableNames() {
+ return List.copyOf(systemTables.keySet());
+ }
+
+ /**
+ * Checks whether a system table is registered.
+ *
+ * @param tableName the schema-qualified name of the table
+ * @return true if the table exists, false otherwise
+ */
+ public boolean tableExists(SchemaTableName tableName) {
+ return systemTables.containsKey(tableName);
}
}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableLoadStatus.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableLoadStatus.java
new file mode 100644
index 0000000000..df87741e35
--- /dev/null
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableLoadStatus.java
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.trino.connector.system.table;
+
+import static io.trino.spi.type.BigintType.BIGINT;
+import static io.trino.spi.type.BooleanType.BOOLEAN;
+import static io.trino.spi.type.VarcharType.VARCHAR;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.airlift.log.Logger;
+import io.trino.spi.Page;
+import io.trino.spi.block.BlockBuilder;
+import io.trino.spi.connector.ColumnMetadata;
+import io.trino.spi.connector.ConnectorTableMetadata;
+import io.trino.spi.connector.SchemaTableName;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+import org.apache.gravitino.trino.connector.catalog.CatalogConnectorManager;
+import org.apache.gravitino.trino.connector.catalog.CatalogConnectorManager.LoadOutcome;
+
+/**
+ * An implementation of the load status system table.
+ *
+ * <p>It reports the health of the loop that registers Apache Gravitino catalogs into Trino. A
+ * failure that prevents the loop from listing catalogs at all, such as an unreachable Gravitino
+ * server, has no catalog to attach itself to and is only visible here.
+ */
+public class GravitinoSystemTableLoadStatus extends GravitinoSystemTable {
+
+ private static final Logger LOG = Logger.get(GravitinoSystemTableLoadStatus.class);
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ /** The name of the load status system table. */
+ public static final SchemaTableName TABLE_NAME =
+ new SchemaTableName(SYSTEM_TABLE_SCHEMA_NAME, "load_status");
+
+ private static final ConnectorTableMetadata TABLE_METADATA =
+ new ConnectorTableMetadata(
+ TABLE_NAME,
+ List.of(
+ ColumnMetadata.builder().setName("trino_reachable").setType(BOOLEAN).build(),
+ ColumnMetadata.builder().setName("last_attempt_time").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("last_success_time").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("consecutive_failures").setType(BIGINT).build(),
+ ColumnMetadata.builder().setName("last_error").setType(VARCHAR).build(),
+ ColumnMetadata.builder().setName("metalake_errors").setType(VARCHAR).build()));
+
+ private final CatalogConnectorManager catalogConnectorManager;
+ private final String metalake;
+
+ /**
+ * Constructs a new GravitinoSystemTableLoadStatus.
+ *
+ * @param catalogConnectorManager the manager for catalog connectors
+ * @param metalake the metalake to report errors for
+ */
+ public GravitinoSystemTableLoadStatus(
+ CatalogConnectorManager catalogConnectorManager, String metalake) {
+ this.catalogConnectorManager = catalogConnectorManager;
+ this.metalake = metalake;
+ }
+
+ @Override
+ public Page loadPageData() {
+ BlockBuilder trinoReachableColumnBuilder = BOOLEAN.createBlockBuilder(null, 1);
+ BlockBuilder lastAttemptTimeColumnBuilder = VARCHAR.createBlockBuilder(null, 1);
+ BlockBuilder lastSuccessTimeColumnBuilder = VARCHAR.createBlockBuilder(null, 1);
+ BlockBuilder consecutiveFailuresColumnBuilder = BIGINT.createBlockBuilder(null, 1);
+ BlockBuilder lastErrorColumnBuilder = VARCHAR.createBlockBuilder(null, 1);
+ BlockBuilder metalakeErrorsColumnBuilder = VARCHAR.createBlockBuilder(null, 1);
+
+ // Read once so that every field of the row below comes from the same attempt: reading them
+ // through separate calls could otherwise mix a fresh success time with a stale error from a
+ // load that completed in between the calls.
+ LoadOutcome loadOutcome = catalogConnectorManager.getLoadOutcome();
+
+ BOOLEAN.writeBoolean(trinoReachableColumnBuilder, loadOutcome.isTrinoReachable());
+ writeTime(lastAttemptTimeColumnBuilder, catalogConnectorManager.getLastLoadAttemptTimeMs());
+ writeTime(lastSuccessTimeColumnBuilder, loadOutcome.getLastSuccessTimeMs());
+ BIGINT.writeLong(consecutiveFailuresColumnBuilder, loadOutcome.getConsecutiveFailures());
+ writeNullableString(lastErrorColumnBuilder, loadOutcome.getLastError());
+
+ // The load loop itself is shared by every entry catalog, so the columns above are global.
+ // Only the per metalake errors are narrowed to the metalake this connector reports on.
+ Map<String, String> allErrors = loadOutcome.getMetalakeErrors();
+ Map<String, String> metalakeErrors =
+ allErrors.containsKey(metalake) ? Map.of(metalake, allErrors.get(metalake)) : Map.of();
+ if (metalakeErrors.isEmpty()) {
+ metalakeErrorsColumnBuilder.appendNull();
+ } else {
+ try {
+ VARCHAR.writeString(
+ metalakeErrorsColumnBuilder,
+ OBJECT_MAPPER.writeValueAsString(new TreeMap<>(metalakeErrors)));
+ } catch (JsonProcessingException e) {
+ // Degrade rather than fail: this table is what a user reads while diagnosing a broken
+ // load loop, and one unserializable column must not take last_error down with it.
+ LOG.warn(e, "Failed to serialize the metalake errors");
+ VARCHAR.writeString(metalakeErrorsColumnBuilder, new TreeMap<>(metalakeErrors).toString());
+ }
+ }
+
+ return new Page(
+ 1,
+ trinoReachableColumnBuilder.build(),
+ lastAttemptTimeColumnBuilder.build(),
+ lastSuccessTimeColumnBuilder.build(),
+ consecutiveFailuresColumnBuilder.build(),
+ lastErrorColumnBuilder.build(),
+ metalakeErrorsColumnBuilder.build());
+ }
+
+ @Override
+ public ConnectorTableMetadata getTableMetaData() {
+ return TABLE_METADATA;
+ }
+}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
index c42b3e761d..73b1192169 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
@@ -46,6 +46,16 @@ public class TestGravitinoConfig {
assertEquals(metalake, config.getMetalake());
}
+ @Test
+ public void testMetalakeIsTrimmed() {
+ GravitinoConfig config =
+ new GravitinoConfig(ImmutableMap.of("gravitino.metalake", " user_001 "));
+
+ // The system tables filter by metalake name, so a stray space in the catalog properties file
+ // must not make this value stop matching the name the load loop records states under.
+ assertEquals("user_001", config.getMetalake());
+ }
+
@Test
public void testMissingConfig() {
String gravitinoUrl = "http://127.0.0.1:8000";
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnector.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnector.java
index fecc1fd9cc..e0a7cf4a79 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnector.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnector.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.trino.connector;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import com.google.common.base.Preconditions;
import io.trino.testing.DistributedQueryRunner;
@@ -282,7 +283,10 @@ public abstract class TestGravitinoConnector extends AbstractGravitinoConnectorT
assertQueryFails(
"call gravitino.system.create_catalog("
+ "catalog=>'memory1', provider=>'memory', properties => Map(array['trino.bypass.unknown-direct-key'], array['10']))",
- format("Create catalog failed. Create catalog failed due to the loading process fails"));
+ // The message must carry the reason the registration failed, not just the fact that it
+ // did. (?s) lets .* span the newlines of the underlying configuration error.
+ "(?s)Create catalog failed. Create catalog failed due to the loading process fails\\."
+ + ".*unknown-direct-key.*");
assertThat(computeActual("show catalogs").getOnlyColumnAsSet()).doesNotContain("memory1");
assertUpdate(
@@ -306,6 +310,93 @@ public abstract class TestGravitinoConnector extends AbstractGravitinoConnectorT
assertEquals(row.getField(2), "{\"max_ttl\":\"10\"}");
}
+ @Test
+ public void testCatalogStatusSystemTable() throws Exception {
+ MaterializedResult result =
+ computeActual(
+ "select metalake, catalog_name, trino_catalog_name, provider, status, last_error,"
+ + " failure_count from gravitino.system.catalog_status");
+ assertEquals(result.getRowCount(), 1);
+ MaterializedRow row = result.getMaterializedRows().get(0);
+ assertEquals(row.getField(1), "memory");
+ assertEquals(row.getField(2), "memory");
+ assertEquals(row.getField(3), "memory");
+ assertEquals(row.getField(4), "REGISTERED");
+ assertNull(row.getField(5));
+ assertEquals(row.getField(6), 0L);
+ }
+
+ @Test
+ public void testCatalogStatusSystemTableWithReorderedColumns() throws Exception {
+ // page.getColumns() honors the requested order; a projection that sorted or de-duplicated
+ // channels would return correct looking data in the wrong columns.
+ MaterializedResult result =
+ computeActual("select status, catalog_name, status from gravitino.system.catalog_status");
+ assertEquals(result.getRowCount(), 1);
+ MaterializedRow row = result.getMaterializedRows().get(0);
+ assertEquals(row.getField(0), "REGISTERED");
+ assertEquals(row.getField(1), "memory");
+ assertEquals(row.getField(2), "REGISTERED");
+ }
+
+ @Test
+ public void testStatusSystemTablesWithNoProjectedColumns() throws Exception {
+ // count(*) projects no column at all, so the page is built with zero channels and only its
+ // position count carries the answer. A table that sized its page from the projected columns
+ // would report no rows here while returning them for every other query.
+ assertEquals(computeScalar("select count(*) from gravitino.system.catalog_status"), 1L);
+ assertEquals(computeScalar("select count(*) from gravitino.system.load_status"), 1L);
+ assertEquals(computeScalar("select count(*) from gravitino.system.catalog"), 1L);
+ }
+
+ @Test
+ public void testCatalogStatusReportsARegistrationFailure() throws Exception {
+ // An unknown bypass key makes the inner connector reject its configuration, so the catalog
+ // exists in Gravitino but its CREATE CATALOG in Trino fails: a real registration failure
+ // rather than a simulated state.
+ assertQueryFails(
+ "call gravitino.system.create_catalog("
+ + "catalog=>'memory_failed', provider=>'memory',"
+ + " properties => Map(array['trino.bypass.unknown-direct-key'], array['10']))",
+ "(?s)Create catalog failed. Create catalog failed due to the loading process fails\\..*");
+ assertThat(computeActual("show catalogs").getOnlyColumnAsSet()).doesNotContain("memory_failed");
+
+ MaterializedResult result =
+ computeActual(
+ "select status, last_error, failure_count from gravitino.system.catalog_status"
+ + " where catalog_name = 'memory_failed'");
+ assertEquals(result.getRowCount(), 1);
+ MaterializedRow row = result.getMaterializedRows().get(0);
+ assertEquals(row.getField(0), "FAILED");
+ assertThat((String) row.getField(1)).contains("unknown-direct-key");
+ assertEquals(row.getField(2), 1L);
+
+ // Leave the shared query runner as it was found, or the load loop keeps retrying this catalog
+ // and the other status table tests see an extra row.
+ assertUpdate(
+ "call gravitino.system.drop_catalog(catalog => 'memory_failed', ignore_not_exist => true)");
+ assertEquals(
+ computeActual(
+ "select 1 from gravitino.system.catalog_status"
+ + " where catalog_name = 'memory_failed'")
+ .getRowCount(),
+ 0);
+ }
+
+ @Test
+ public void testLoadStatusSystemTable() throws Exception {
+ MaterializedResult result =
+ computeActual(
+ "select trino_reachable, consecutive_failures, last_error, metalake_errors"
+ + " from gravitino.system.load_status");
+ assertEquals(result.getRowCount(), 1);
+ MaterializedRow row = result.getMaterializedRows().get(0);
+ assertEquals(row.getField(0), true);
+ assertEquals(row.getField(1), 0L);
+ assertNull(row.getField(2));
+ assertNull(row.getField(3));
+ }
+
private TableName createTestTable(String fullTableName) throws Exception {
TableName tableName = new TableName(fullTableName);
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryInit.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryInit.java
new file mode 100644
index 0000000000..70cb7f09c6
--- /dev/null
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryInit.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.trino.connector;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.common.collect.ImmutableMap;
+import io.trino.spi.HostAddress;
+import io.trino.spi.Node;
+import io.trino.spi.NodeManager;
+import io.trino.spi.TrinoException;
+import io.trino.spi.connector.ConnectorContext;
+import java.nio.file.Path;
+import java.util.Map;
+import org.apache.gravitino.client.GravitinoAdminClient;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+public class TestGravitinoConnectorFactoryInit {
+
+ @TempDir private static Path catalogStoreDir;
+
+ private static Map<String, String> config(String catalogStoreDirectory) {
+ return ImmutableMap.of(
+ "gravitino.uri", "http://127.0.0.1:8090",
+ "gravitino.metalake", "test",
+ "gravitino.trino.skip-version-validation", "true",
+ "catalog.config-dir", catalogStoreDirectory,
+ "discovery.uri", "http://127.0.0.1:8080");
+ }
+
+ @Test
+ public void testFailedStartCanRecover() {
+ GravitinoConnectorFactory factory =
+ new GravitinoConnectorFactory(mock(GravitinoAdminClient.class));
+
+ // A catalog store directory that does not exist makes CatalogRegister.init() fail, so the
+ // whole initialization fails.
+ assertThrows(
+ TrinoException.class,
+ () ->
+ factory.create(
+ "gravitino", config("/nonexistent-gravitino-catalog-dir"), mockContext()));
+
+ // The startup did not complete, so a connector handed out afterwards would run against a
+ // load loop that never started.
+ assertFalse(factory.isCatalogConnectorManagerStartTriggered());
+
+ // Once the configuration is fixed, the next create() starts over and succeeds.
+ assertNotNull(factory.create("gravitino", config(catalogStoreDir.toString()), mockContext()));
+ assertTrue(factory.isCatalogConnectorManagerStartTriggered());
+ }
+
+ @SuppressWarnings("deprecation")
+ private static ConnectorContext mockContext() {
+ ConnectorContext context = mock(ConnectorContext.class);
+ when(context.getSpiVersion()).thenReturn("435");
+ Node node = mock(Node.class);
+ when(node.isCoordinator()).thenReturn(true);
+ when(node.getHostAndPort()).thenReturn(HostAddress.fromParts("127.0.0.1", 8080));
+ NodeManager nodeManager = mock(NodeManager.class);
+ when(nodeManager.getCurrentNode()).thenReturn(node);
+ when(context.getNodeManager()).thenReturn(nodeManager);
+ return context;
+ }
+}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.java
index cc189815df..7123554efe 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.java
@@ -18,20 +18,25 @@
*/
package org.apache.gravitino.trino.connector;
+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.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
+import io.trino.spi.HostAddress;
import io.trino.spi.connector.ConnectorContext;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import org.apache.gravitino.client.GravitinoAdminClient;
+import org.apache.gravitino.trino.connector.catalog.CatalogConnectorManager;
+import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -84,6 +89,11 @@ public class TestGravitinoConnectorFactoryStart {
protected boolean isCoordinator(ConnectorContext connectorContext) {
return true;
}
+
+ @Override
+ protected HostAddress getCurrentNodeAddress(ConnectorContext connectorContext) {
+ return HostAddress.fromParts("127.0.0.1", 1);
+ }
}
private static CoordinatorFactory newFactory() {
@@ -144,16 +154,55 @@ public class TestGravitinoConnectorFactoryStart {
}
@Test
- public void testStartIsAttemptedOnlyOnce() {
+ public void testFailedStartCanRecover() {
CoordinatorFactory factory = newFactory();
Map<String, String> brokenConfig = staticConfig();
brokenConfig.put("catalog.config-dir", "/not/exists/catalog");
assertThrows(Exception.class, () -> factory.create("gravitino", brokenConfig, mockContext()));
- // Everything that makes start() fail is a configuration error, so the next create() must not
- // try again: a second init() would open another connection and abandon the first one.
- assertNotNull(factory.create("gravitino", brokenConfig, mockContext()));
+ // The startup did not complete, so the next create() must not skip it and hand out a
+ // connector whose load loop never started.
+ assertFalse(factory.isCatalogConnectorManagerStartTriggered());
+
+ // The failure is a configuration error, so it is the fixed configuration that recovers it.
+ assertNotNull(factory.create("gravitino", staticConfig(), mockContext()));
+ assertTrue(factory.isCatalogConnectorManagerStartTriggered());
+ }
+
+ @Test
+ public void testFailedStartKeepsTheConnectorsADynamicCatalogAlreadyCreated() {
+ CoordinatorFactory factory = newFactory();
+
+ // The coordinator restarted and Trino loaded a Gravitino-created catalog first, which builds
+ // and publishes the shared manager.
+ assertThrows(Exception.class, () -> factory.create("catalog", dynamicConfig(), mockContext()));
+ CatalogConnectorManager manager = factory.getCatalogConnectorManager();
+ assertNotNull(manager);
+
+ Map<String, String> brokenConfig = staticConfig();
+ brokenConfig.put("catalog.config-dir", "/not/exists/catalog");
+ assertThrows(Exception.class, () -> factory.create("gravitino", brokenConfig, mockContext()));
+
+ // The manager is shared with the dynamic catalogs that are already installed in Trino, so a
+ // failed startup must not take it, its Gravitino client or its executor down with it.
+ assertSame(manager, factory.getCatalogConnectorManager());
+ assertFalse(factory.isCatalogConnectorManagerStartTriggered());
+ assertNotNull(factory.create("gravitino", staticConfig(), mockContext()));
+ assertSame(manager, factory.getCatalogConnectorManager());
+ }
+
+ @Test
+ public void testStaticConnectorPinsSplitsToTheCoordinator() {
+ CoordinatorFactory factory = newFactory();
+
+ assertNotNull(factory.create("gravitino", staticConfig(), mockContext()));
+
+ // The registration state the system tables report lives only on the coordinator, so its
+ // splits must be pinned to the address CoordinatorFactory reports for this node.
+ assertEquals(
+ HostAddress.fromParts("127.0.0.1", 1),
+ GravitinoSystemConnector.Split.getCurrentCoordinatorAddress());
}
@Test
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java
index 33a8047a67..b6a0df05f1 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java
@@ -21,9 +21,13 @@ package org.apache.gravitino.trino.connector.catalog;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
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;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -31,10 +35,15 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import io.trino.spi.TrinoException;
import io.trino.spi.connector.ConnectorContext;
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Optional;
+import org.apache.gravitino.Audit;
import org.apache.gravitino.Catalog;
import org.apache.gravitino.client.GravitinoAdminClient;
import org.apache.gravitino.client.GravitinoMetalake;
@@ -44,6 +53,8 @@ import org.apache.gravitino.trino.connector.GravitinoConfig;
import org.apache.gravitino.trino.connector.GravitinoErrorCode;
import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
public class TestCatalogConnectorManager {
@@ -103,9 +114,9 @@ public class TestCatalogConnectorManager {
() ->
manager.createCatalogConnectorContext(
"test1", otherConnectorConfig, mockContext()));
- assertEquals(GravitinoErrorCode.GRAVITINO_OPERATION_FAILED.toErrorCode(), error.getErrorCode());
- assertTrue(error.getMessage().contains("Failed to create connector"));
- assertTrue(error.getCause().getMessage().contains("Multiple metalakes are not supported"));
+ assertEquals(
+ GravitinoErrorCode.GRAVITINO_UNSUPPORTED_OPERATION.toErrorCode(), error.getErrorCode());
+ assertTrue(error.getMessage().contains("Multiple metalakes are not supported"));
}
@Test
@@ -149,11 +160,980 @@ public class TestCatalogConnectorManager {
assertFalse(manager.skipCatalog("b2"));
}
+ @Test
+ public void testSuccessfulRegistrationIsRecorded() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.REGISTERED, state.getStatus());
+ assertEquals("test", state.getMetalake());
+ assertEquals("memory", state.getCatalogName());
+ assertEquals("memory", state.getTrinoCatalogName());
+ assertEquals("memory", state.getProvider());
+ assertNull(state.getLastError());
+ assertEquals(0, state.getFailureCount());
+ assertTrue(state.getLastSuccessTimeMs() > 0);
+
+ assertTrue(manager.isTrinoReachable());
+ assertNull(manager.getLoadOutcome().getLastError());
+ assertEquals(0, manager.getLoadOutcome().getConsecutiveFailures());
+ assertTrue(manager.getMetalakeErrors().isEmpty());
+ }
+
+ @Test
+ public void testRegistrationFailureIsRecorded() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ doThrow(
+ new TrinoException(
+ GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR,
+ "Access Denied: Cannot create catalog memory"))
+ .when(fixture.catalogRegister)
+ .registerCatalog(any(), any());
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.FAILED, state.getStatus());
+ assertTrue(state.getLastError().contains("Access Denied"));
+ assertEquals(1, state.getFailureCount());
+ assertEquals(0, state.getLastSuccessTimeMs());
+
+ // A second failing round must accumulate rather than reset the failure count.
+ manager.loadMetalakeSync();
+ state = singleState(manager);
+ assertEquals(2, state.getFailureCount());
+ assertEquals(0, state.getLastSuccessTimeMs());
+ }
+
+ @Test
+ public void testRegistrationFailureIsReportedByStoredProcedureMessage() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ doThrow(
+ new TrinoException(
+ GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR,
+ "Access Denied: Cannot create catalog memory"))
+ .when(fixture.catalogRegister)
+ .registerCatalog(any(), any());
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ String description = manager.describeRegistrationFailure("test", "memory");
+ assertTrue(description.contains("FAILED"));
+ assertTrue(description.contains("Access Denied"));
+ }
+
+ @Test
+ public void testNonRelationalCatalogIsRecorded() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("files", "hadoop", Catalog.Type.FILESET));
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.UNSUPPORTED, state.getStatus());
+ assertTrue(state.getLastError().contains("FILESET"));
+ }
+
+ @Test
+ public void testUnsupportedProviderIsRecorded() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("other", "unknown", Catalog.Type.RELATIONAL));
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.UNSUPPORTED, state.getStatus());
+ assertTrue(state.getLastError().contains("unknown"));
+ assertEquals("unknown", state.getProvider());
+ }
+
+ @Test
+ public void testFailureBeforeProviderIsKnownKeepsPreviousProvider() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+ assertEquals("memory", singleState(manager).getProvider());
+
+ // The next attempt fails before the provider can even be read off the catalog.
+ Mockito.doThrow(new RuntimeException("Connection reset"))
+ .when(fixture.metalake)
+ .loadCatalog("memory");
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.FAILED, state.getStatus());
+ // The provider a previous successful attempt discovered must not be blanked out.
+ assertEquals("memory", state.getProvider());
+ }
+
+ @Test
+ public void testSkippedCatalogIsRecorded() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+
+ CatalogConnectorManager manager =
+ fixture.createManager(ImmutableMap.of("gravitino.trino.skip-catalog-patterns", "mem.*"));
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.SKIPPED, state.getStatus());
+ assertTrue(state.getLastError().contains("skip-catalog-patterns"));
+ }
+
+ @Test
+ public void testStaleStateIsPruned() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog first = mockCatalog("a", "memory", Catalog.Type.RELATIONAL);
+ Catalog second = mockCatalog("b", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(first, second);
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+ assertEquals(2, manager.getCatalogRegistrationStates().size());
+
+ // The second catalog is dropped in the Gravitino server, its state must not linger.
+ fixture.withCatalogs(first);
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals("a", state.getCatalogName());
+ }
+
+ @Test
+ public void testListCatalogsFailureIsRecordedPerMetalake() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+ assertEquals(CatalogRegistrationState.Status.REGISTERED, singleState(manager).getStatus());
+
+ Mockito.doThrow(new RuntimeException("Connection refused"))
+ .when(fixture.metalake)
+ .listCatalogs();
+ manager.loadMetalakeSync();
+
+ Map<String, String> metalakeErrors = manager.getMetalakeErrors();
+ assertEquals(1, metalakeErrors.size());
+ assertTrue(metalakeErrors.get("test").contains("Connection refused"));
+ // A transient listing failure must not turn a healthy catalog into a failed one.
+ assertEquals(CatalogRegistrationState.Status.REGISTERED, singleState(manager).getStatus());
+ }
+
+ @Test
+ public void testUnreachableServerIsRecordedInLoadStatus() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ when(fixture.client.loadMetalake(any())).thenThrow(new RuntimeException("Connection refused"));
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogConnectorManager.LoadOutcome loadOutcome = manager.getLoadOutcome();
+ assertNotNull(loadOutcome.getLastError());
+ assertTrue(loadOutcome.getLastError().contains("Connection refused"));
+ assertEquals(1, loadOutcome.getConsecutiveFailures());
+ assertEquals(0, loadOutcome.getLastSuccessTimeMs());
+ assertTrue(manager.getLastLoadAttemptTimeMs() > 0);
+ assertTrue(manager.getCatalogRegistrationStates().isEmpty());
+ }
+
+ @Test
+ public void testUnreachableTrinoIsRecordedInLoadStatus() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ when(fixture.catalogRegister.isTrinoReachable()).thenReturn(false);
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ assertFalse(manager.isTrinoReachable());
+ String lastError = manager.getLoadOutcome().getLastError();
+ assertNotNull(lastError);
+ assertTrue(lastError.contains("The Trino server is not reachable"));
+ assertTrue(manager.getCatalogRegistrationStates().isEmpty());
+ }
+
+ @Test
+ public void testCatalogRecoversFromFailure() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ doThrow(new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Access Denied"))
+ .when(fixture.catalogRegister)
+ .registerCatalog(any(), any());
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+ assertEquals(CatalogRegistrationState.Status.FAILED, singleState(manager).getStatus());
+
+ // The underlying problem is fixed; the row must not stay stuck on FAILED.
+ Mockito.reset(fixture.catalogRegister);
+ when(fixture.catalogRegister.isTrinoReachable()).thenReturn(true);
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.REGISTERED, state.getStatus());
+ assertNull(state.getLastError());
+ assertEquals(0, state.getFailureCount());
+ assertTrue(state.getLastSuccessTimeMs() > 0);
+ }
+
+ @Test
+ public void testFailureAfterSuccessKeepsLastSuccessTime() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+ long successTime = singleState(manager).getLastSuccessTimeMs();
+ assertTrue(successTime > 0);
+
+ doThrow(new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Access Denied"))
+ .when(fixture.catalogRegister)
+ .registerCatalog(any(), any());
+ manager.loadMetalakeSync();
+
+ // A catalog that regressed must keep telling the user when it last worked.
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.FAILED, state.getStatus());
+ assertEquals(1, state.getFailureCount());
+ assertEquals(successTime, state.getLastSuccessTimeMs());
+ }
+
+ @Test
+ public void testUnsupportedCatalogKeepsLastSuccessTime() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(catalog);
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+ long successTime = singleState(manager).getLastSuccessTimeMs();
+
+ // The provider changes to one the connector does not support.
+ when(catalog.provider()).thenReturn("unknown");
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.UNSUPPORTED, state.getStatus());
+ assertEquals(successTime, state.getLastSuccessTimeMs());
+ }
+
+ @Test
+ public void testSkippedCatalogSurvivesPruning() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+
+ CatalogConnectorManager manager =
+ fixture.createManager(ImmutableMap.of("gravitino.trino.skip-catalog-patterns", "mem.*"));
+ manager.loadMetalakeSync();
+ manager.loadMetalakeSync();
+
+ // The row must not flicker away on the second iteration.
+ assertEquals(CatalogRegistrationState.Status.SKIPPED, singleState(manager).getStatus());
+ }
+
+ @Test
+ public void testMetalakeErrorClearsOnRecovery() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+
+ Mockito.doThrow(new RuntimeException("Connection refused"))
+ .when(fixture.metalake)
+ .listCatalogs();
+ manager.loadMetalakeSync();
+ assertEquals(1, manager.getMetalakeErrors().size());
+ // A metalake that cannot be listed is not a healthy loop.
+ assertNotNull(manager.getLoadOutcome().getLastError());
+ assertEquals(0, manager.getLoadOutcome().getLastSuccessTimeMs());
+
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ manager.loadMetalakeSync();
+
+ assertTrue(manager.getMetalakeErrors().isEmpty());
+ CatalogConnectorManager.LoadOutcome loadOutcome = manager.getLoadOutcome();
+ assertNull(loadOutcome.getLastError());
+ assertEquals(0, loadOutcome.getConsecutiveFailures());
+ assertTrue(loadOutcome.getLastSuccessTimeMs() > 0);
+ }
+
+ @Test
+ public void testUnloadFailureKeepsCatalogVisibleInState() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ // Trino has the connector, so the manager will try to unload it when it disappears.
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getMetalake()).thenReturn(fixture.metalake);
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+ doThrow(new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Access Denied"))
+ .when(fixture.catalogRegister)
+ .unregisterCatalog(any());
+ Mockito.doReturn(new String[0]).when(fixture.metalake).listCatalogs();
+ manager.loadMetalakeSync();
+
+ // The catalog is gone from Gravitino but still registered in Trino: the state must say so
+ // rather than disappear.
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.FAILED, state.getStatus());
+ assertTrue(state.getLastError().contains("could not be unregistered"));
+ }
+
+ @Test
+ public void testUnloadFailureKeepsStateWhenMetalakeVanishes() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager =
+ fixture.createManager(ImmutableMap.of("gravitino.use-single-metalake", "false"));
+ manager.loadMetalakeSync();
+
+ // Trino has the connector, so the manager will try to unload it when the metalake disappears.
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getMetalake()).thenReturn(fixture.metalake);
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+ doThrow(new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Access Denied"))
+ .when(fixture.catalogRegister)
+ .unregisterCatalog(any());
+ Mockito.doReturn(new GravitinoMetalake[0]).when(fixture.client).listMetalakes();
+
+ manager.loadMetalakeSync();
+
+ // The whole metalake is gone but the catalog is still registered in Trino: pruning the
+ // metalake's state must not take the failure it just recorded with it.
+ assertTrue(manager.catalogConnectorExist("memory"));
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.FAILED, state.getStatus());
+ assertTrue(state.getLastError().contains("The metalake was removed"));
+ }
+
+ @Test
+ public void testRefreshFailureKeepsRegisteredCatalogRegistered() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ // Trino loaded the catalog Gravitino registered, so it is live from now on.
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+
+ Mockito.doThrow(new RESTException("simulated: the server rejected the load"))
+ .when(fixture.metalake)
+ .loadCatalog("memory");
+ manager.loadMetalakeSync();
+
+ // The catalog is still registered and queryable, so a failed refresh must not flip it to
+ // FAILED and hide that it is usable.
+ assertTrue(manager.catalogConnectorExist("memory"));
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.REGISTERED, state.getStatus());
+ assertNull(state.getLastError());
+ }
+
+ @Test
+ public void testUnknownCatalogTypeIsRecordedAsUnsupported() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+
+ // The client library cannot map this catalog's type, e.g. DTOConverters.toCatalog throwing
+ // for a type it does not know. That is a "not supported", not a registration failure.
+ Mockito.doThrow(new UnsupportedOperationException("Unsupported catalog type: UNKNOWN"))
+ .when(fixture.metalake)
+ .loadCatalog("memory");
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.UNSUPPORTED, state.getStatus());
+ assertTrue(state.getLastError().contains("Unsupported catalog type"));
+ assertFalse(manager.catalogConnectorExist("memory"));
+ }
+
+ @Test
+ public void testUnchangedCatalogIsNotReRegistered() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ Audit audit = mock(Audit.class);
+ Instant modifiedTime = Instant.ofEpochMilli(1000L);
+ when(audit.createTime()).thenReturn(modifiedTime);
+ when(audit.lastModifiedTime()).thenReturn(modifiedTime);
+ when(catalog.auditInfo()).thenReturn(audit);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ // Trino holds a connector built from the very same version the server reports.
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getCatalog())
+ .thenReturn(
+ new GravitinoCatalog(
+ "test", "memory", "memory", ImmutableMap.of(), modifiedTime.toEpochMilli()));
+ Mockito.clearInvocations(fixture.catalogRegister);
+
+ manager.loadMetalakeSync();
+
+ // Nothing changed, so the connector must be left alone rather than dropped and rebuilt.
+ verify(fixture.catalogRegister, never()).unregisterCatalog(any());
+ verify(fixture.catalogRegister, never()).registerCatalog(any(), any());
+ assertTrue(manager.catalogConnectorExist("memory"));
+ assertEquals(CatalogRegistrationState.Status.REGISTERED, singleState(manager).getStatus());
+ }
+
+ @Test
+ public void testUpdatedCatalogIsReRegistered() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ // Trino holds a connector built from an older version than the one the server reports.
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+ Mockito.clearInvocations(fixture.catalogRegister);
+
+ manager.loadMetalakeSync();
+
+ // The old connector is dropped and the new definition registered in its place.
+ verify(fixture.catalogRegister, times(1)).unregisterCatalog("memory");
+ verify(fixture.catalogRegister, times(1)).registerCatalog(Mockito.eq("memory"), any());
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.REGISTERED, state.getStatus());
+ assertNull(state.getLastError());
+ }
+
+ @Test
+ public void testDeletedCatalogWithConnectorIsRemoved() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getMetalake()).thenReturn(fixture.metalake);
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+
+ // The catalog is deleted in Gravitino and unregisters cleanly from Trino.
+ Mockito.doReturn(new String[0]).when(fixture.metalake).listCatalogs();
+ manager.loadMetalakeSync();
+
+ verify(fixture.catalogRegister, times(1)).unregisterCatalog("memory");
+ assertFalse(manager.catalogConnectorExist("memory"));
+ assertTrue(manager.getCatalogRegistrationStates().isEmpty());
+ assertNull(manager.getLoadOutcome().getLastError());
+ }
+
+ @Test
+ public void testVanishedMetalakeCleansUpItsConnectors() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager =
+ fixture.createManager(ImmutableMap.of("gravitino.use-single-metalake", "false"));
+ manager.loadMetalakeSync();
+
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getMetalake()).thenReturn(fixture.metalake);
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+ assertTrue(manager.getUsedMetalakes().contains("test"));
+
+ // The metalake is deleted in Gravitino and its catalog unregisters cleanly from Trino.
+ Mockito.doReturn(new GravitinoMetalake[0]).when(fixture.client).listMetalakes();
+ manager.loadMetalakeSync();
+
+ verify(fixture.catalogRegister, times(1)).unregisterCatalog("memory");
+ assertFalse(manager.catalogConnectorExist("memory"));
+ assertTrue(manager.getCatalogRegistrationStates().isEmpty());
+ assertTrue(manager.getMetalakeErrors().isEmpty());
+ // getUsedMetalakes() reads the cached metalake handles, so an empty set is what proves the
+ // deleted metalake was dropped from the cache too.
+ assertTrue(manager.getUsedMetalakes().isEmpty());
+ }
+
+ @Test
+ public void testCatalogStatesAreFilteredPerMetalake() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+
+ // A second metalake loaded by the same manager, which every entry catalog shares.
+ GravitinoMetalake devMetalake = mock(GravitinoMetalake.class);
+ when(devMetalake.name()).thenReturn("dev");
+ Catalog devCatalog = mockCatalog("sandbox", "memory", Catalog.Type.RELATIONAL);
+ Mockito.doReturn(new String[] {"sandbox"}).when(devMetalake).listCatalogs();
+ Mockito.doReturn(devCatalog).when(devMetalake).loadCatalog("sandbox");
+ Mockito.doReturn(new GravitinoMetalake[] {fixture.metalake, devMetalake})
+ .when(fixture.client)
+ .listMetalakes();
+
+ CatalogConnectorManager manager =
+ fixture.createManager(ImmutableMap.of("gravitino.use-single-metalake", "false"));
+ manager.loadMetalakeSync();
+
+ assertEquals(2, manager.getCatalogRegistrationStates().size());
+
+ // Each entry catalog's system tables read through this filter, so it must not leak the other
+ // metalake's rows.
+ List<CatalogRegistrationState> testStates = manager.getCatalogRegistrationStates("test");
+ assertEquals(1, testStates.size());
+ assertEquals("memory", testStates.get(0).getCatalogName());
+ List<CatalogRegistrationState> devStates = manager.getCatalogRegistrationStates("dev");
+ assertEquals(1, devStates.size());
+ assertEquals("sandbox", devStates.get(0).getCatalogName());
+ }
+
+ @Test
+ public void testSkipPatternMatchesQualifiedCatalogName() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+
+ // In multi metalake mode the catalog is registered under its qualified Trino name, and that
+ // is the name the skip patterns are matched against.
+ CatalogConnectorManager manager =
+ fixture.createManager(
+ ImmutableMap.of(
+ "gravitino.use-single-metalake",
+ "false",
+ "gravitino.trino.skip-catalog-patterns",
+ ".*test\\.memory.*"),
+ // The qualified name Trino sees in multi metalake mode, quotes included.
+ (metalakeName, catalog) -> "\"" + metalakeName + "." + catalog + "\"");
+ assertTrue(manager.skipCatalog(manager.getTrinoCatalogName("test", "memory")));
+
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.SKIPPED, state.getStatus());
+ assertTrue(state.getLastError().contains("skip-catalog-patterns"));
+ verify(fixture.catalogRegister, never()).registerCatalog(any(), any());
+ }
+
+ @Test
+ public void testRecordedErrorRedactsSecrets() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ // What a driver that echoes the failing CREATE CATALOG back would report.
+ doThrow(
+ new TrinoException(
+ GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR,
+ "Query failed: CREATE CATALOG memory USING gravitino WITH ("
+ + "\"trino.bypass.password\"='hunter2')"))
+ .when(fixture.catalogRegister)
+ .registerCatalog(any(), any());
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ // The exception keeps its own message; the text the status tables report does not.
+ CatalogRegistrationState state = singleState(manager);
+ assertFalse(state.getLastError().contains("hunter2"));
+ assertTrue(state.getLastError().contains("\"trino.bypass.password\"='***'"));
+ }
+
+ @Test
+ public void testRepeatedUnreachableTrinoKeepsItsOwnMessage() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ when(fixture.catalogRegister.isTrinoReachable()).thenReturn(false);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+
+ // The second attempt reports the same message as the first, which is the branch that logs a
+ // repeated failure. It carries no cause, and rendering one anyway would fail there.
+ manager.loadMetalakeSync();
+ manager.loadMetalakeSync();
+
+ CatalogConnectorManager.LoadOutcome outcome = manager.getLoadOutcome();
+ assertTrue(outcome.getLastError().contains("The Trino server is not reachable"));
+ assertEquals(2, outcome.getConsecutiveFailures());
+ }
+
+ @Test
+ public void testMetalakeFailureAggregationKeepsItsOwnMessage() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Mockito.doThrow(new RESTException("simulated: listing failed"))
+ .when(fixture.metalake)
+ .listCatalogs();
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+
+ manager.loadMetalakeSync();
+
+ // The aggregated failure has no single cause of its own, and load_status must report it
+ // rather than whatever went wrong while trying to log it.
+ CatalogConnectorManager.LoadOutcome outcome = manager.getLoadOutcome();
+ assertTrue(outcome.getLastError().contains("1 of 1 metalakes failed"));
+ assertTrue(outcome.getLastError().contains("simulated: listing failed"));
+ }
+
+ @Test
+ public void testLiveCatalogBecomingUnsupportedIsUnregistered() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getMetalake()).thenReturn(fixture.metalake);
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+
+ // The catalog was dropped and recreated under the same name with a provider this connector
+ // cannot serve.
+ when(catalog.provider()).thenReturn("unsupported-provider");
+ manager.loadMetalakeSync();
+
+ // Leaving it registered would keep Trino serving a catalog the status table calls
+ // UNSUPPORTED.
+ verify(fixture.catalogRegister, times(1)).unregisterCatalog("memory");
+ assertFalse(manager.catalogConnectorExist("memory"));
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.UNSUPPORTED, state.getStatus());
+ assertTrue(state.getLastError().contains("unsupported-provider"));
+ }
+
+ @Test
+ public void testLiveCatalogMatchingSkipPatternIsUnregistered() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getMetalake()).thenReturn(fixture.metalake);
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+
+ // The operator added a skip pattern that now matches a catalog Trino already serves.
+ manager.updateConfig(
+ fixture.config(ImmutableMap.of("gravitino.trino.skip-catalog-patterns", "mem.*")));
+ manager.loadMetalakeSync();
+
+ verify(fixture.catalogRegister, times(1)).unregisterCatalog("memory");
+ assertFalse(manager.catalogConnectorExist("memory"));
+ assertEquals(CatalogRegistrationState.Status.SKIPPED, singleState(manager).getStatus());
+ }
+
+ @Test
+ public void testSkippedCatalogUnregisterFailureIsNotReportedAsDeletion() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getMetalake()).thenReturn(fixture.metalake);
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+ doThrow(new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Access Denied"))
+ .when(fixture.catalogRegister)
+ .unregisterCatalog(any());
+
+ manager.updateConfig(
+ fixture.config(ImmutableMap.of("gravitino.trino.skip-catalog-patterns", "mem.*")));
+ manager.loadMetalakeSync();
+
+ // The catalog still exists in Gravitino, so its owner must not be told it was deleted.
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.FAILED, state.getStatus());
+ assertTrue(state.getLastError().contains("skip-catalog-patterns"));
+ assertFalse(state.getLastError().contains("deleted in Gravitino"));
+ }
+
+ @Test
+ public void testUnchangedCatalogKeepsItsSuccessTime() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ Audit audit = mock(Audit.class);
+ Instant modifiedTime = Instant.ofEpochMilli(1000L);
+ when(audit.createTime()).thenReturn(modifiedTime);
+ when(audit.lastModifiedTime()).thenReturn(modifiedTime);
+ when(catalog.auditInfo()).thenReturn(audit);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getCatalog())
+ .thenReturn(
+ new GravitinoCatalog(
+ "test", "memory", "memory", ImmutableMap.of(), modifiedTime.toEpochMilli()));
+ long registeredAt = singleState(manager).getLastSuccessTimeMs();
+
+ Thread.sleep(5);
+ manager.loadMetalakeSync();
+
+ // A poll that found nothing to do is not a new registration: advancing the time here would
+ // make last_success_time say nothing more than last_attempt_time already does.
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(registeredAt, state.getLastSuccessTimeMs());
+ // The poll still happened, so the row must not look like a catalog the loop stopped visiting.
+ assertTrue(state.getLastAttemptTimeMs() > registeredAt);
+ assertEquals(CatalogRegistrationState.Status.REGISTERED, state.getStatus());
+ }
+
+ @Test
+ public void testTrinoBecomingUnreachableIsReported() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+ assertTrue(manager.isTrinoReachable());
+
+ // The coordinator restarted, or the connection behind the register died. A reachability that
+ // was latched on the first success would keep the loop issuing statements over it and report
+ // every catalog failing separately instead of the one reason they all did.
+ when(fixture.catalogRegister.isTrinoReachable()).thenReturn(false);
+ when(fixture.catalogRegister.getLastConnectionError()).thenReturn("Connection reset");
+ manager.loadMetalakeSync();
+
+ assertFalse(manager.isTrinoReachable());
+ CatalogConnectorManager.LoadOutcome outcome = manager.getLoadOutcome();
+ assertFalse(outcome.isTrinoReachable());
+ assertTrue(outcome.getLastError().contains("The Trino server is not reachable"));
+ assertTrue(outcome.getLastError().contains("Connection reset"));
+ }
+
+ @Test
+ public void testUnsupportedUnregisterFailureKeepsTheCatalogVisible() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getMetalake()).thenReturn(fixture.metalake);
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+
+ when(catalog.provider()).thenReturn("unsupported-provider");
+ doThrow(new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Access Denied"))
+ .when(fixture.catalogRegister)
+ .unregisterCatalog(any());
+ manager.loadMetalakeSync();
+
+ // Reporting it as merely UNSUPPORTED would hide that Trino is still serving it.
+ assertTrue(manager.catalogConnectorExist("memory"));
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.FAILED, state.getStatus());
+ assertTrue(state.getLastError().contains("could not be unregistered"));
+ }
+
+ @Test
+ public void testUnreachableTrinoReportsNoMetalakeErrors() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Mockito.doThrow(new RESTException("simulated: listing failed"))
+ .when(fixture.metalake)
+ .listCatalogs();
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+ assertFalse(manager.getLoadOutcome().getMetalakeErrors().isEmpty());
+
+ // Trino goes away. This cycle touches no metalake at all, so the errors left over from the
+ // previous one say nothing about it.
+ when(fixture.catalogRegister.isTrinoReachable()).thenReturn(false);
+ manager.loadMetalakeSync();
+
+ CatalogConnectorManager.LoadOutcome outcome = manager.getLoadOutcome();
+ assertFalse(outcome.isTrinoReachable());
+ assertTrue(outcome.getMetalakeErrors().isEmpty());
+ }
+
+ @Test
+ public void testUnreachableTrinoDoesNotQuoteStaleMetalakeErrors() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Mockito.doThrow(new RESTException("simulated: listing failed"))
+ .when(fixture.metalake)
+ .listCatalogs();
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+ assertTrue(manager.describeRegistrationFailure("test", "memory").contains("listing failed"));
+
+ when(fixture.catalogRegister.isTrinoReachable()).thenReturn(false);
+ manager.loadMetalakeSync();
+
+ // The stored procedure and the load status table must not describe the same attempt
+ // differently: this one stopped at the reachability check and touched no metalake.
+ assertTrue(manager.getMetalakeErrors().isEmpty());
+ assertFalse(manager.describeRegistrationFailure("test", "memory").contains("listing failed"));
+ }
+
+ @Test
+ public void testCatalogObservedRegisteredAfterAFailureGetsASuccessTime() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ Audit audit = mock(Audit.class);
+ Instant modifiedTime = Instant.ofEpochMilli(1000L);
+ when(audit.createTime()).thenReturn(modifiedTime);
+ when(audit.lastModifiedTime()).thenReturn(modifiedTime);
+ when(catalog.auditInfo()).thenReturn(audit);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+
+ // A live connector whose row is FAILED, e.g. an unregistration that did not go through.
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getMetalake()).thenReturn(fixture.metalake);
+ when(context.getCatalog())
+ .thenReturn(
+ new GravitinoCatalog(
+ "test", "memory", "memory", ImmutableMap.of(), modifiedTime.toEpochMilli()));
+ when(catalog.provider()).thenReturn("unsupported-provider");
+ doThrow(new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Access Denied"))
+ .when(fixture.catalogRegister)
+ .unregisterCatalog(any());
+ manager.loadMetalakeSync();
+ assertEquals(CatalogRegistrationState.Status.FAILED, singleState(manager).getStatus());
+ assertEquals(0, singleState(manager).getLastSuccessTimeMs());
+
+ // The catalog is supported again. Nothing changed, so no re-registration runs, but the
+ // catalog is demonstrably registered and must not report that it never succeeded.
+ when(catalog.provider()).thenReturn("memory");
+ manager.loadMetalakeSync();
+
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.REGISTERED, state.getStatus());
+ assertTrue(state.getLastSuccessTimeMs() > 0);
+ }
+
+ @Test
+ public void testReloadFailureAfterUnregisterIsRecordedAsFailed() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+
+ // Trino already has a live connector for this catalog, built from an older version.
+ CatalogConnectorContext context =
+ manager.createCatalogConnectorContext(
+ "memory", createConnectorConfig(catalogConfigJson("test", "memory")), mockContext());
+ when(context.getCatalog())
+ .thenReturn(new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L));
+
+ // The Gravitino server now reports a newer version, so the load loop takes the reload path:
+ // reloadCatalog() unregisters the old connector before attempting to re-register it.
+ Audit audit = mock(Audit.class);
+ when(audit.createTime()).thenReturn(Instant.now());
+ when(audit.lastModifiedTime()).thenReturn(Instant.now());
+ when(catalog.auditInfo()).thenReturn(audit);
+
+ doThrow(new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Access Denied"))
+ .when(fixture.catalogRegister)
+ .registerCatalog(any(), any());
+
+ manager.loadMetalakeSync();
+
+ // The old connector is genuinely gone from Trino now; the state must say FAILED with the
+ // real cause instead of assuming the catalog is still usable.
+ assertFalse(manager.catalogConnectorExist("memory"));
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.FAILED, state.getStatus());
+ assertTrue(state.getLastError().contains("Access Denied"));
+ }
+
+ @Test
+ public void testTrinoConnectionErrorIsReported() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ when(fixture.catalogRegister.isTrinoReachable()).thenReturn(false);
+ when(fixture.catalogRegister.getLastConnectionError())
+ .thenReturn("Authentication failed: Access Denied");
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ // "Waiting for Trino" alone would read the same for a misconfiguration that never resolves.
+ assertFalse(manager.isTrinoReachable());
+ CatalogConnectorManager.LoadOutcome loadOutcome = manager.getLoadOutcome();
+ assertTrue(loadOutcome.getLastError().contains("Authentication failed"));
+ assertEquals(1, loadOutcome.getConsecutiveFailures());
+ }
+
+ @Test
+ public void testErrorMessageFallsBackWhenNoMessageIsPresent() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+ doThrow(new IllegalStateException())
+ .when(fixture.catalogRegister)
+ .registerCatalog(any(), any());
+
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
+
+ // An exception with no message must not produce a null or empty last_error.
+ CatalogRegistrationState state = singleState(manager);
+ assertEquals(CatalogRegistrationState.Status.FAILED, state.getStatus());
+ assertTrue(state.getLastError().contains("IllegalStateException"));
+ }
+
+ @Test
+ public void testStateOfAVanishedMetalakeIsPruned() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ fixture.withCatalogs(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL));
+
+ // Multi metalake mode, so the used metalakes come from listMetalakes().
+ CatalogConnectorManager manager =
+ fixture.createManager(ImmutableMap.of("gravitino.use-single-metalake", "false"));
+ manager.loadMetalakeSync();
+ assertEquals(1, manager.getCatalogRegistrationStates().size());
+
+ // The metalake is deleted in Gravitino: its catalog rows must not linger as REGISTERED.
+ Mockito.doReturn(new GravitinoMetalake[0]).when(fixture.client).listMetalakes();
+ manager.loadMetalakeSync();
+
+ assertTrue(manager.getCatalogRegistrationStates().isEmpty());
+ assertTrue(manager.getMetalakeErrors().isEmpty());
+ }
+
@Test
public void testRefreshIcebergRestUriCachesDiscoveredUri() throws Exception {
GravitinoAdminClient client = mock(GravitinoAdminClient.class);
CatalogRegister catalogRegister = mock(CatalogRegister.class);
- when(catalogRegister.isTrinoStarted()).thenReturn(true);
+ when(catalogRegister.isTrinoReachable()).thenReturn(true);
when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));
when(client.icebergRestServiceUri("test"))
.thenReturn(Optional.of("http://irc-host:9001/iceberg"));
@@ -178,7 +1158,7 @@ public class TestCatalogConnectorManager {
throws Exception {
GravitinoAdminClient client = mock(GravitinoAdminClient.class);
CatalogRegister catalogRegister = mock(CatalogRegister.class);
- when(catalogRegister.isTrinoStarted()).thenReturn(true);
+ when(catalogRegister.isTrinoReachable()).thenReturn(true);
when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));
when(client.icebergRestServiceUri("test"))
.thenThrow(new RESTException("simulated: endpoint not found on an older server"));
@@ -221,7 +1201,7 @@ public class TestCatalogConnectorManager {
public void testIcebergRestRoutingDisabledSkipsDiscovery() throws Exception {
GravitinoAdminClient client = mock(GravitinoAdminClient.class);
CatalogRegister catalogRegister = mock(CatalogRegister.class);
- when(catalogRegister.isTrinoStarted()).thenReturn(true);
+ when(catalogRegister.isTrinoReachable()).thenReturn(true);
when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));
CatalogConnectorManager manager =
@@ -244,7 +1224,7 @@ public class TestCatalogConnectorManager {
public void testConfiguredIcebergRestUriSkipsDiscovery() throws Exception {
GravitinoAdminClient client = mock(GravitinoAdminClient.class);
CatalogRegister catalogRegister = mock(CatalogRegister.class);
- when(catalogRegister.isTrinoStarted()).thenReturn(true);
+ when(catalogRegister.isTrinoReachable()).thenReturn(true);
when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));
CatalogConnectorManager manager =
@@ -267,7 +1247,7 @@ public class TestCatalogConnectorManager {
public void testIcebergRestDiscoveryRetriesAndRecovers() throws Exception {
GravitinoAdminClient client = mock(GravitinoAdminClient.class);
CatalogRegister catalogRegister = mock(CatalogRegister.class);
- when(catalogRegister.isTrinoStarted()).thenReturn(true);
+ when(catalogRegister.isTrinoReachable()).thenReturn(true);
when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));
when(client.icebergRestServiceUri("test"))
.thenThrow(new RESTException("simulated discovery failure"))
@@ -291,33 +1271,68 @@ public class TestCatalogConnectorManager {
}
@Test
- public void testPropsWithSecrets() {
- Catalog catalog = mock(Catalog.class);
- SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);
+ public void testRegistrationCarriesNoSecrets() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
when(catalog.properties()).thenReturn(Map.of("visible", "v1", "shared", "from-props"));
- when(catalog.supportsSecrets()).thenReturn(supportsSecrets);
- when(supportsSecrets.getSecrets())
- .thenReturn(Map.of("jdbc-password", "secret", "shared", "from-secret"));
+ when(catalog.supportsSecrets().getSecrets())
+ .thenReturn(Map.of("jdbc-password", "hunter2", "shared", "from-secret"));
+ fixture.withCatalogs(catalog);
- Map<String, String> merged = CatalogConnectorManager.propsWithSecrets(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+ manager.loadMetalakeSync();
- assertEquals("v1", merged.get("visible"));
- assertEquals("secret", merged.get("jdbc-password"));
- assertEquals("from-secret", merged.get("shared"));
+ // The registered definition is what the CREATE CATALOG statement carries and what Trino
+ // persists as a catalog properties file, so no secret may be in it.
+ ArgumentCaptor<GravitinoCatalog> registered = ArgumentCaptor.forClass(GravitinoCatalog.class);
+ verify(fixture.catalogRegister).registerCatalog(eq("memory"), registered.capture());
+ Map<String, String> properties = registered.getValue().getProperties();
+ assertEquals("v1", properties.get("visible"));
+ assertEquals("from-props", properties.get("shared"));
+ assertFalse(properties.containsKey("jdbc-password"));
+ assertFalse(properties.toString().contains("hunter2"));
}
@Test
- public void testPropsWithSecretsNullProps() {
+ public void testConnectorContextResolvesSecrets() throws Exception {
+ LoadFixture fixture = new LoadFixture();
+ Catalog catalog = mockCatalog("memory", "memory", Catalog.Type.RELATIONAL);
+ when(catalog.properties()).thenReturn(Map.of("visible", "v1", "shared", "from-props"));
+ when(catalog.supportsSecrets().getSecrets())
+ .thenReturn(Map.of("jdbc-password", "hunter2", "shared", "from-secret"));
+ fixture.withCatalogs(catalog);
+ CatalogConnectorManager manager = fixture.createManager(ImmutableMap.of());
+
+ // What Trino hands back to the node when it loads the catalog that was registered without
+ // secrets.
+ manager.createCatalogConnectorContext(
+ "memory",
+ createConnectorConfig(
+ GravitinoCatalog.toJson(
+ new GravitinoCatalog(
+ "test",
+ "memory",
+ "memory",
+ Map.of("visible", "v1", "shared", "from-props"),
+ 0L))),
+ mockContext());
+
+ // The node resolves them against the server, and a secret wins over a visible property of
+ // the same name the way the merge at registration time used to.
+ ArgumentCaptor<GravitinoCatalog> built = ArgumentCaptor.forClass(GravitinoCatalog.class);
+ verify(fixture.catalogFactory).createCatalogConnectorContextBuilder(built.capture());
+ Map<String, String> properties = built.getValue().getProperties();
+ assertEquals("v1", properties.get("visible"));
+ assertEquals("hunter2", properties.get("jdbc-password"));
+ assertEquals("from-secret", properties.get("shared"));
+ }
+
+ @Test
+ public void testVisiblePropsHandlesNullProperties() {
Catalog catalog = mock(Catalog.class);
- SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);
when(catalog.properties()).thenReturn(null);
- when(catalog.supportsSecrets()).thenReturn(supportsSecrets);
- when(supportsSecrets.getSecrets()).thenReturn(Map.of("jdbc-password", "secret"));
-
- Map<String, String> merged = CatalogConnectorManager.propsWithSecrets(catalog);
- assertEquals("secret", merged.get("jdbc-password"));
- assertEquals(1, merged.size());
+ assertTrue(CatalogConnectorManager.visibleProps(catalog).isEmpty());
}
private CatalogConnectorManager createManager(ImmutableMap<String, String> configMap)
@@ -338,7 +1353,15 @@ public class TestCatalogConnectorManager {
singleMetalakeMode
? null
: (metalake, catalog) -> String.format("\"%s.%s\"", metalake, catalog));
- manager.config(new GravitinoConfig(configMap), mock(GravitinoAdminClient.class));
+ // Building a connector resolves the catalog's secrets against the server, so the client has
+ // to answer for the metalake it is asked about.
+ GravitinoAdminClient client = mock(GravitinoAdminClient.class);
+ GravitinoMetalake metalake = mock(GravitinoMetalake.class);
+ Mockito.doReturn(metalake).when(client).loadMetalake(any());
+ Mockito.doReturn(mockCatalog("memory", "memory", Catalog.Type.RELATIONAL))
+ .when(metalake)
+ .loadCatalog(any());
+ manager.config(new GravitinoConfig(configMap), client);
return manager;
}
@@ -374,4 +1397,79 @@ public class TestCatalogConnectorManager {
private static ConnectorContext mockContext() {
return mock(ConnectorContext.class);
}
+
+ private static CatalogRegistrationState singleState(CatalogConnectorManager manager) {
+ List<CatalogRegistrationState> states = manager.getCatalogRegistrationStates();
+ assertEquals(1, states.size());
+ return states.get(0);
+ }
+
+ private static Catalog mockCatalog(String name, String provider, Catalog.Type type) {
+ Catalog catalog = mock(Catalog.class);
+ when(catalog.name()).thenReturn(name);
+ when(catalog.provider()).thenReturn(provider);
+ when(catalog.type()).thenReturn(type);
+ when(catalog.properties()).thenReturn(ImmutableMap.of());
+ SupportsSecrets supportsSecrets = mock(SupportsSecrets.class);
+ when(supportsSecrets.getSecrets()).thenReturn(Map.of());
+ when(catalog.supportsSecrets()).thenReturn(supportsSecrets);
+ Audit audit = mock(Audit.class);
+ when(audit.createTime()).thenReturn(Instant.now());
+ when(audit.lastModifiedTime()).thenReturn(null);
+ when(catalog.auditInfo()).thenReturn(audit);
+ return catalog;
+ }
+
+ /** Wires up a manager whose load loop can be driven with {@code loadMetalakeSync()}. */
+ private static class LoadFixture {
+ private final CatalogRegister catalogRegister = mock(CatalogRegister.class);
+ private final GravitinoAdminClient client = mock(GravitinoAdminClient.class);
+ private final GravitinoMetalake metalake = mock(GravitinoMetalake.class);
+ private final CatalogConnectorFactory catalogFactory = mock(CatalogConnectorFactory.class);
+
+ LoadFixture() throws Exception {
+ when(catalogRegister.isTrinoReachable()).thenReturn(true);
+ when(metalake.name()).thenReturn("test");
+ when(client.loadMetalake(any())).thenReturn(metalake);
+ Mockito.doReturn(new GravitinoMetalake[] {metalake}).when(client).listMetalakes();
+ when(catalogFactory.getSupportedCatalogProviders()).thenReturn(ImmutableSet.of("memory"));
+ CatalogConnectorContext.Builder builder = mock(CatalogConnectorContext.Builder.class);
+ when(catalogFactory.createCatalogConnectorContextBuilder(any())).thenReturn(builder);
+ when(builder.withMetalake(any())).thenReturn(builder);
+ when(builder.withContext(any())).thenReturn(builder);
+ when(builder.build()).thenReturn(mock(CatalogConnectorContext.class));
+ }
+
+ void withCatalogs(Catalog... catalogs) {
+ String[] names = new String[catalogs.length];
+ for (int i = 0; i < catalogs.length; i++) {
+ names[i] = catalogs[i].name();
+ Mockito.doReturn(catalogs[i]).when(metalake).loadCatalog(names[i]);
+ }
+ Mockito.doReturn(names).when(metalake).listCatalogs();
+ }
+
+ CatalogConnectorManager createManager(Map<String, String> extraConfig) {
+ return createManager(extraConfig, (metalakeName, catalog) -> catalog);
+ }
+
+ CatalogConnectorManager createManager(
+ Map<String, String> extraConfig,
+ CatalogConnectorManager.TrinoCatalogNameHandler nameHandler) {
+ CatalogConnectorManager manager =
+ new CatalogConnectorManager(catalogRegister, catalogFactory, nameHandler);
+ manager.config(config(extraConfig), client);
+ return manager;
+ }
+
+ /** The manager configuration this fixture builds, so a test can re-apply a changed one. */
+ GravitinoConfig config(Map<String, String> extraConfig) {
+ Map<String, String> defaults = new HashMap<>();
+ defaults.put("gravitino.uri", "http://127.0.0.1:8090");
+ defaults.put("gravitino.metalake", "test");
+ defaults.put("gravitino.use-single-metalake", "true");
+ defaults.putAll(extraConfig);
+ return new GravitinoConfig(ImmutableMap.copyOf(defaults));
+ }
+ }
}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
index b850f587f8..b99b766d40 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
@@ -22,8 +22,10 @@ import static org.apache.gravitino.trino.connector.GravitinoErrorCode.GRAVITINO_
import static org.apache.gravitino.trino.connector.GravitinoErrorCode.GRAVITINO_MISSING_CONFIG;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.startsWith;
@@ -40,6 +42,7 @@ import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
+import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@@ -492,10 +495,11 @@ public class TestCatalogRegister {
}
@Test
- public void testRegisterCatalogRedactsSecretsFromSqlExceptionMessage() throws Exception {
- // Regression test: some JDBC drivers echo the failing statement back in a SQLException
- // message. registerCatalog must redact that message the same way it redacts its own success
- // log, so a failed CREATE CATALOG never surfaces the embedded credential to the caller.
+ public void testRegisterCatalogPassesTheDriverFailureOnUnchanged() throws Exception {
+ // The driver's exception travels to the caller with its type, message and stack intact:
+ // redacting it here would have to rebuild every level of the cause chain as a different
+ // exception type. Whatever a message carries is masked where it is rendered instead, which
+ // for the load loop is CatalogConnectorManager.toErrorMessage().
String secretValue = "hunter2";
Statement statement = mock(Statement.class);
when(statement.execute(eq("SHOW CATALOGS"))).thenReturn(true);
@@ -529,13 +533,114 @@ public class TestCatalogRegister {
assertThrows(
TrinoException.class, () -> catalogRegister.registerCatalog("hive_catalog", catalog));
- // The original driver SQLException carrying the credential is two levels down the cause
- // chain: registerCatalog's generic wrapper -> executeSql's generic wrapper -> the redacted
- // SQLException. No exception in that chain may still carry the raw secret.
+ // registerCatalog's generic wrapper -> executeSql's generic wrapper -> the driver exception.
+ Throwable driverFailure = e.getCause().getCause();
+ assertInstanceOf(SQLException.class, driverFailure);
+ assertTrue(driverFailure.getMessage().contains(secretValue));
+ }
+
+ @Test
+ public void testRegisterCatalogKeepsTheDeepCause() throws Exception {
+ // The reason a registration failed usually sits at the bottom of the chain, e.g. a
+ // connector's own configuration validation error, and that is what the status tables end up
+ // reporting.
+ Statement statement = mock(Statement.class);
+ when(statement.execute(eq("SHOW CATALOGS"))).thenReturn(true);
+ ResultSet resultSet = mock(ResultSet.class);
+ when(statement.getResultSet()).thenReturn(resultSet);
+ when(resultSet.next()).thenReturn(false);
+
+ RuntimeException deepCause =
+ new RuntimeException("Configuration property 'unknown-direct-key' was not used");
+ SQLException sqlException =
+ new SQLException("Query failed: Failed to create connector: memory1", null, 0, deepCause);
+ when(statement.execute(startsWith("CREATE CATALOG"))).thenThrow(sqlException);
+
+ Connection connection = mock(Connection.class);
+ when(connection.createStatement()).thenReturn(statement);
+
+ CatalogRegister catalogRegister = new CatalogRegister();
+ catalogRegister.setConfigForTesting(
+ new GravitinoConfig(
+ ImmutableMap.of(
+ "gravitino.uri", "http://127.0.0.1:8090", "gravitino.metalake", "test")));
+ setPrivateField(catalogRegister, "connection", connection);
+ setPrivateField(catalogRegister, "catalogStoreDirectory", tempDir.toString());
+
+ Catalog mockCatalog =
+ TestGravitinoCatalog.mockCatalog(
+ "hive_catalog", "hive", "test catalog", Catalog.Type.RELATIONAL, Map.of());
+ GravitinoCatalog catalog = new GravitinoCatalog("test", mockCatalog);
+
+ TrinoException e =
+ assertThrows(
+ TrinoException.class, () -> catalogRegister.registerCatalog("hive_catalog", catalog));
+
+ boolean deepCauseSurvived = false;
for (Throwable t = e; t != null; t = t.getCause()) {
- assertFalse(String.valueOf(t.getMessage()).contains(secretValue));
+ if (String.valueOf(t.getMessage()).contains("unknown-direct-key")) {
+ deepCauseSurvived = true;
+ }
}
- assertTrue(e.getCause().getCause().getMessage().contains("***"));
+ assertTrue(deepCauseSurvived, "the deep cause must reach the caller");
+ }
+
+ @Test
+ public void testDescribeMasksSecretsThroughTheWholeCauseChain() {
+ // What a Jackson parse failure on the catalog JSON looks like: the source it echoes is the
+ // very payload that carries the resolved secrets.
+ RuntimeException deepCause =
+ new RuntimeException(
+ "Unexpected end-of-input at [Source: (String)\"{\"properties\":"
+ + "{\"jdbc-password\":\"hunter2\"}}\"; line: 1]");
+ Exception failure =
+ new IllegalStateException("Failed on \"trino.bypass.password\"='letmein'", deepCause);
+
+ String described = CatalogRegister.describe(failure);
+
+ assertFalse(described.contains("hunter2"));
+ assertFalse(described.contains("letmein"));
+ assertTrue(described.contains("\"jdbc-password\":\"***\""));
+ assertTrue(described.contains("\"trino.bypass.password\"='***'"));
+ // The rendering keeps what makes it useful: the types, the chain and the frames.
+ assertTrue(described.contains("IllegalStateException"));
+ assertTrue(described.contains("Caused by"));
+ assertTrue(described.contains("testDescribeMasksSecretsThroughTheWholeCauseChain"));
+ }
+
+ @Test
+ public void testDescribeTerminatesOnACauseCycle() {
+ // Java permits A -> B -> A. The JDK's own stack trace printer stops at the repeated node,
+ // which is why rendering the throwable needs no cycle guard of its own.
+ Exception first = new IllegalStateException("first");
+ Exception second = new IllegalStateException("second", first);
+ first.initCause(second);
+
+ String described =
+ assertTimeoutPreemptively(Duration.ofSeconds(10), () -> CatalogRegister.describe(first));
+
+ assertTrue(described.contains("CIRCULAR REFERENCE"));
+ }
+
+ @Test
+ public void testReachabilityIsProbedOnEveryCall() throws Exception {
+ Statement statement = mock(Statement.class);
+ when(statement.execute("SELECT 1"))
+ .thenReturn(true)
+ .thenThrow(new SQLException("Connection reset"));
+ Connection connection = mock(Connection.class);
+ when(connection.createStatement()).thenReturn(statement);
+
+ CatalogRegister catalogRegister = new CatalogRegister();
+ setPrivateField(catalogRegister, "connection", connection);
+
+ // A reachability latched on the first success would keep the load loop issuing statements
+ // over a connection that stopped working, and report every catalog failing separately
+ // instead of the one reason they all did.
+ assertTrue(catalogRegister.isTrinoReachable());
+ assertNull(catalogRegister.getLastConnectionError());
+ assertFalse(catalogRegister.isTrinoReachable());
+ assertEquals("Connection reset", catalogRegister.getLastConnectionError());
}
private static void setPrivateField(Object target, String fieldName, Object value)
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/system/TestGravitinoSystemConnector.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/system/TestGravitinoSystemConnector.java
index 11b5538b08..ce44f5a1be 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/system/TestGravitinoSystemConnector.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/system/TestGravitinoSystemConnector.java
@@ -18,7 +18,10 @@
*/
package org.apache.gravitino.trino.connector.system;
+import io.trino.spi.HostAddress;
import io.trino.spi.Page;
+import io.trino.spi.connector.SchemaTableName;
+import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
@@ -64,4 +67,38 @@ public class TestGravitinoSystemConnector {
Assertions.assertTrue(pageSource.isFinished());
}
}
+
+ @Test
+ public void testSplitIsRemotelyAccessibleUntilTheCoordinatorIsKnown() {
+ // Without a known coordinator the split keeps the original, unpinned behaviour.
+ GravitinoSystemConnector.Split split = mockSplit(null);
+
+ Assertions.assertTrue(split.isRemotelyAccessible());
+ Assertions.assertTrue(split.getAddresses().isEmpty());
+ }
+
+ @Test
+ public void testSplitIsPinnedToTheCoordinator() {
+ // The system tables are only populated on the coordinator, so a split must never be
+ // scheduled onto a worker. The address is baked into the split itself (as createSplit()
+ // does, reading Split.getCurrentCoordinatorAddress()) so the pinning survives the split
+ // being serialized to, and deserialized on, a different JVM.
+ HostAddress coordinator = HostAddress.fromParts("127.0.0.1", 8080);
+ GravitinoSystemConnector.Split split = mockSplit(coordinator);
+
+ Assertions.assertFalse(split.isRemotelyAccessible());
+ Assertions.assertEquals(List.of(coordinator), split.getAddresses());
+ }
+
+ private static final SchemaTableName TABLE_NAME = new SchemaTableName("system", "catalog");
+
+ private static GravitinoSystemConnector.Split mockSplit(HostAddress coordinatorAddress) {
+ // Mocked rather than subclassed: ConnectorSplit's abstract members differ across the
+ // supported Trino SPI versions, and this test compiles against all of them.
+ return Mockito.mock(
+ GravitinoSystemConnector.Split.class,
+ Mockito.withSettings()
+ .useConstructor(TABLE_NAME, coordinatorAddress)
+ .defaultAnswer(Mockito.CALLS_REAL_METHODS));
+ }
}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/system/table/TestGravitinoSystemStatusTables.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/system/table/TestGravitinoSystemStatusTables.java
new file mode 100644
index 0000000000..c8984861e6
--- /dev/null
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/system/table/TestGravitinoSystemStatusTables.java
@@ -0,0 +1,319 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.trino.connector.system.table;
+
+import static io.trino.spi.type.BigintType.BIGINT;
+import static io.trino.spi.type.BooleanType.BOOLEAN;
+import static io.trino.spi.type.VarcharType.VARCHAR;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import com.google.common.collect.ImmutableMap;
+import io.trino.spi.Page;
+import io.trino.spi.block.Block;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.gravitino.Audit;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.client.GravitinoMetalake;
+import org.apache.gravitino.trino.connector.catalog.CatalogConnectorManager;
+import org.apache.gravitino.trino.connector.catalog.CatalogRegistrationState;
+import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
+import org.junit.jupiter.api.Test;
+
+public class TestGravitinoSystemStatusTables {
+
+ @Test
+ public void testCatalogTableReportsOnlyItsOwnMetalakeInMultiMetalakeMode() {
+ // gravitino.system.catalog must report only its entry catalog's metalake, not every metalake
+ // the manager happens to have loaded.
+ CatalogConnectorManager manager = mock(CatalogConnectorManager.class);
+ when(manager.getUsedMetalakes()).thenReturn(Set.of("prod", "dev"));
+
+ GravitinoMetalake prodMetalake = mock(GravitinoMetalake.class);
+ Catalog prodCatalog = mock(Catalog.class);
+ when(prodCatalog.name()).thenReturn("memory");
+ when(prodCatalog.provider()).thenReturn("memory");
+ when(prodCatalog.type()).thenReturn(Catalog.Type.RELATIONAL);
+ when(prodCatalog.properties()).thenReturn(Map.of());
+ Audit audit = mock(Audit.class);
+ when(audit.createTime()).thenReturn(Instant.now());
+ when(prodCatalog.auditInfo()).thenReturn(audit);
+ when(prodMetalake.listCatalogsInfo()).thenReturn(new Catalog[] {prodCatalog});
+ when(manager.getMetalake("prod")).thenReturn(prodMetalake);
+ when(manager.getTrinoCatalogName("prod", "memory")).thenReturn("memory");
+ when(manager.skipCatalog("memory")).thenReturn(false);
+
+ // "dev" is a used metalake too, but this table instance is scoped to "prod" and must not
+ // even look at "dev": leaving its mock unstubbed means any access throws or returns null,
+ // which would surface as a test failure instead of silently leaking dev's catalogs in.
+
+ Page page = new GravitinoSystemTableCatalog(manager, "prod").loadPageData();
+
+ assertEquals(1, page.getPositionCount());
+ assertEquals("memory", varchar(page, 0));
+ }
+
+ @Test
+ public void testCatalogStatusTableRendersRegisteredCatalog() {
+ GravitinoCatalog catalog =
+ new GravitinoCatalog("test", "memory", "memory", ImmutableMap.of(), 0L);
+ CatalogRegistrationState state = CatalogRegistrationState.succeeded(catalog, "memory");
+
+ Page page = loadCatalogStatusPage(List.of(state));
+
+ assertEquals(1, page.getPositionCount());
+ assertEquals(9, page.getChannelCount());
+ assertEquals("test", varchar(page, 0));
+ assertEquals("memory", varchar(page, 1));
+ assertEquals("memory", varchar(page, 2));
+ assertEquals("memory", varchar(page, 3));
+ assertEquals("REGISTERED", varchar(page, 4));
+ // last_error is null for a registered catalog, last_success_time is set.
+ assertTrue(page.getBlock(5).isNull(0));
+ assertFalse(page.getBlock(7).isNull(0));
+ assertEquals(0, BIGINT.getLong(page.getBlock(8), 0));
+ }
+
+ @Test
+ public void testCatalogStatusTableRendersFailedCatalog() {
+ CatalogRegistrationState state =
+ CatalogRegistrationState.failed(
+ "test", "memory", "memory", null, "Access Denied: Cannot create catalog memory");
+
+ Page page = loadCatalogStatusPage(List.of(state));
+
+ assertEquals("FAILED", varchar(page, 4));
+ assertTrue(varchar(page, 5).contains("Access Denied"));
+ // The provider is unknown on this path, and the catalog was never registered.
+ assertTrue(page.getBlock(3).isNull(0));
+ assertTrue(page.getBlock(7).isNull(0));
+ assertEquals(1, BIGINT.getLong(page.getBlock(8), 0));
+ }
+
+ @Test
+ public void testCatalogStatusTableIsEmptyWhenNoCatalogWasSeen() {
+ Page page = loadCatalogStatusPage(List.of());
+ assertEquals(0, page.getPositionCount());
+ }
+
+ @Test
+ public void testLoadStatusTableRendersHealthyLoop() {
+ CatalogConnectorManager manager = mock(CatalogConnectorManager.class);
+ when(manager.getLastLoadAttemptTimeMs()).thenReturn(1000L);
+ when(manager.getLoadOutcome())
+ .thenReturn(new CatalogConnectorManager.LoadOutcome(true, 1000L, null, 0L, Map.of()));
+
+ Page page = new GravitinoSystemTableLoadStatus(manager, "test").loadPageData();
+
+ assertEquals(1, page.getPositionCount());
+ assertEquals(6, page.getChannelCount());
+ assertTrue(BOOLEAN.getBoolean(page.getBlock(0), 0));
+ assertEquals("1970-01-01T00:00:01Z", varchar(page, 1));
+ assertEquals(0, BIGINT.getLong(page.getBlock(3), 0));
+ assertTrue(page.getBlock(4).isNull(0));
+ assertTrue(page.getBlock(5).isNull(0));
+ }
+
+ @Test
+ public void testLoadStatusTableRendersUnreachableServer() {
+ CatalogConnectorManager manager = mock(CatalogConnectorManager.class);
+ when(manager.getLastLoadAttemptTimeMs()).thenReturn(2000L);
+ when(manager.getLoadOutcome())
+ .thenReturn(
+ new CatalogConnectorManager.LoadOutcome(
+ true, 0L, "Connection refused", 3L, Map.of("test", "Connection refused")));
+
+ Page page = new GravitinoSystemTableLoadStatus(manager, "test").loadPageData();
+
+ // last_success_time stays null while the server is unreachable.
+ assertTrue(page.getBlock(2).isNull(0));
+ assertEquals(3, BIGINT.getLong(page.getBlock(3), 0));
+ assertEquals("Connection refused", varchar(page, 4));
+ assertEquals("{\"test\":\"Connection refused\"}", varchar(page, 5));
+ }
+
+ @Test
+ public void testLoadStatusTableReportsOnlyItsOwnMetalakeErrors() {
+ CatalogConnectorManager manager = mock(CatalogConnectorManager.class);
+ when(manager.getLastLoadAttemptTimeMs()).thenReturn(2000L);
+ when(manager.getLoadOutcome())
+ .thenReturn(
+ new CatalogConnectorManager.LoadOutcome(
+ true,
+ 0L,
+ "1 of 2 metalakes failed",
+ 1L,
+ Map.of("test", "Connection refused", "dev", "Access Denied")));
+
+ Page page = new GravitinoSystemTableLoadStatus(manager, "test").loadPageData();
+
+ // The loop-wide fields describe the shared load loop, but metalake_errors is narrowed to the
+ // metalake this entry catalog reports on.
+ assertEquals("1 of 2 metalakes failed", varchar(page, 4));
+ assertEquals("{\"test\":\"Connection refused\"}", varchar(page, 5));
+ }
+
+ // A healthy loop and a failing one, with every field distinguishable so that a row combining
+ // the two is recognizable on sight.
+ private static final CatalogConnectorManager.LoadOutcome HEALTHY_OUTCOME =
+ new CatalogConnectorManager.LoadOutcome(true, 5000L, null, 0L, Map.of());
+ private static final CatalogConnectorManager.LoadOutcome FAILING_OUTCOME =
+ new CatalogConnectorManager.LoadOutcome(
+ false, 0L, "Connection refused", 3L, Map.of("test", "Connection refused"));
+
+ @Test
+ public void testLoadStatusRowComesFromASingleLoadAttempt() {
+ CatalogConnectorManager manager = mock(CatalogConnectorManager.class);
+ when(manager.getLastLoadAttemptTimeMs()).thenReturn(2000L);
+ // Every read reports a different attempt, the way a load loop completing between two reads
+ // would. Rendering must therefore read the outcome exactly once.
+ AtomicInteger reads = new AtomicInteger();
+ when(manager.getLoadOutcome())
+ .thenAnswer(
+ invocation -> reads.getAndIncrement() % 2 == 0 ? HEALTHY_OUTCOME : FAILING_OUTCOME);
+
+ Page page = new GravitinoSystemTableLoadStatus(manager, "test").loadPageData();
+
+ verify(manager, times(1)).getLoadOutcome();
+ assertConsistentLoadStatusRow(page);
+ }
+
+ @Test
+ public void testLoadStatusIsConsistentWhileTheLoopFailsAndRecovers() throws Exception {
+ CatalogConnectorManager manager = mock(CatalogConnectorManager.class);
+ when(manager.getLastLoadAttemptTimeMs()).thenReturn(2000L);
+ // The load loop keeps flipping between failing and recovering underneath the readers.
+ AtomicBoolean failing = new AtomicBoolean();
+ when(manager.getLoadOutcome())
+ .thenAnswer(invocation -> failing.get() ? FAILING_OUTCOME : HEALTHY_OUTCOME);
+
+ GravitinoSystemTableLoadStatus table = new GravitinoSystemTableLoadStatus(manager, "test");
+ int readerCount = 4;
+ int rendersPerReader = 200;
+ ExecutorService executor = Executors.newFixedThreadPool(readerCount + 1);
+ CountDownLatch start = new CountDownLatch(1);
+ AtomicBoolean stop = new AtomicBoolean();
+ try {
+ executor.submit(
+ () -> {
+ start.await();
+ while (!stop.get()) {
+ failing.set(!failing.get());
+ }
+ return null;
+ });
+
+ List<Future<?>> readers = new ArrayList<>();
+ for (int i = 0; i < readerCount; i++) {
+ readers.add(
+ executor.submit(
+ () -> {
+ start.await();
+ for (int render = 0; render < rendersPerReader; render++) {
+ assertConsistentLoadStatusRow(table.loadPageData());
+ }
+ return null;
+ }));
+ }
+
+ start.countDown();
+ for (Future<?> reader : readers) {
+ reader.get(60, TimeUnit.SECONDS);
+ }
+ } finally {
+ stop.set(true);
+ executor.shutdownNow();
+ }
+ }
+
+ /** Asserts that the row describes one load attempt rather than fields taken from two. */
+ private static void assertConsistentLoadStatusRow(Page page) {
+ assertEquals(1, page.getPositionCount());
+ boolean healthy = page.getBlock(4).isNull(0);
+ if (healthy) {
+ assertTrue(BOOLEAN.getBoolean(page.getBlock(0), 0));
+ assertEquals("1970-01-01T00:00:05Z", varchar(page, 2));
+ assertEquals(0, BIGINT.getLong(page.getBlock(3), 0));
+ // No error, so nothing may claim a metalake produced one.
+ assertTrue(page.getBlock(5).isNull(0));
+ } else {
+ assertFalse(BOOLEAN.getBoolean(page.getBlock(0), 0));
+ assertTrue(page.getBlock(2).isNull(0));
+ assertEquals(3, BIGINT.getLong(page.getBlock(3), 0));
+ assertEquals("Connection refused", varchar(page, 4));
+ assertEquals("{\"test\":\"Connection refused\"}", varchar(page, 5));
+ }
+ }
+
+ @Test
+ public void testEachFactoryOwnsItsTables() {
+ // The registry used to be static, so a second connector in the same JVM took it over and the
+ // system tables reported another manager's state. Each factory must now stand alone.
+ CatalogConnectorManager first = mock(CatalogConnectorManager.class);
+ when(first.getCatalogRegistrationStates("prod"))
+ .thenReturn(
+ List.of(
+ CatalogRegistrationState.succeeded(
+ new GravitinoCatalog("prod", "memory", "memory", ImmutableMap.of(), 0L),
+ "memory")));
+ CatalogConnectorManager second = mock(CatalogConnectorManager.class);
+ when(second.getCatalogRegistrationStates("prod")).thenReturn(List.of());
+
+ GravitinoSystemTableFactory firstFactory = new GravitinoSystemTableFactory(first, "prod");
+ GravitinoSystemTableFactory secondFactory = new GravitinoSystemTableFactory(second, "prod");
+
+ assertEquals(
+ 1,
+ firstFactory.loadPageData(GravitinoSystemTableCatalogStatus.TABLE_NAME).getPositionCount());
+ assertEquals(
+ 0,
+ secondFactory
+ .loadPageData(GravitinoSystemTableCatalogStatus.TABLE_NAME)
+ .getPositionCount());
+ assertTrue(firstFactory.tableExists(GravitinoSystemTableLoadStatus.TABLE_NAME));
+ assertEquals(3, firstFactory.listTableNames().size());
+ }
+
+ private static Page loadCatalogStatusPage(List<CatalogRegistrationState> states) {
+ CatalogConnectorManager manager = mock(CatalogConnectorManager.class);
+ when(manager.getCatalogRegistrationStates("test")).thenReturn(states);
+ return new GravitinoSystemTableCatalogStatus(manager, "test").loadPageData();
+ }
+
+ private static String varchar(Page page, int channel) {
+ Block block = page.getBlock(channel);
+ return VARCHAR.getSlice(block, 0).toStringUtf8();
+ }
+}