You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "diqiu50 (via GitHub)" <gi...@apache.org> on 2026/08/21 06:11:40 UTC
[PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
diqiu50 opened a new pull request, #12547:
URL: https://github.com/apache/gravitino/pull/12547
### What changes were proposed in this pull request?
Record the registration state of every catalog and the health of the load loop, and expose both through two system tables: `gravitino.system.catalog_status` and `gravitino.system.load_status`. Errors now report the root cause rather than the outer wrapper, and the stored procedures carry that reason too.
### Why are the changes needed?
A catalog that fails to register produces no user-visible error and never appears in `SHOW CATALOGS`. The only way to find out why is to read the coordinator log.
Fix: #12546
### Does this PR introduce _any_ user-facing change?
Two new system tables, documented in `docs/trino-connector/supported-catalog.md` along with a troubleshooting section. No configuration or API changes.
### How was this patch tested?
Unit and query-level tests covering every status, loop failures and page rendering; the suite passes on Trino 435 through 478. Integration test `jdbc-mysql/00015_catalog_status` verifies both tables against a real Gravitino server and Trino container.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#discussion_r3841978011
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -186,14 +216,102 @@ private void loadMetalake() {
LOG.debug("Load metalake: {}", usedMetalake);
loadCatalogs(metalake);
} catch (Exception e) {
- LOG.error("Load Metalake {} failed.", usedMetalake, e);
+ recordMetalakeError(usedMetalake, e);
}
}
- } catch (Exception e) {
- LOG.error("Error when loading metalake", e);
+
+ pruneMissingMetalakes(usedMetalakes);
+
+ if (metalakeErrors.isEmpty()) {
+ lastSuccessfulLoadTimeMs = System.currentTimeMillis();
+ 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
+ // rows behind. Without this they keep reporting REGISTERED for catalogs that no longer exist.
+ catalogStates.values().removeIf(state -> !usedMetalakes.contains(state.getMetalake()));
+ metalakeErrors.keySet().removeIf(metalakeName -> !usedMetalakes.contains(metalakeName));
Review Comment:
You should also clear `metalakes`, `catalogConnectors` and all registerd catalogs that belong to the deleted metalake.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#issuecomment-5367413894
<!-- coverage-report -->
### Code Coverage Report
|Overall Project|67.7% **`-0.15%`**|:green_circle:|
|:-|:-|:-:|
|Files changed|50.61%|:red_circle:|
<br>
|Module|Coverage||
|:-|:-|:-:|
|aliyun|1.72%|:red_circle:|
|api|49.14%|:green_circle:|
|authorization-common|85.96%|:green_circle:|
|authorization-ranger|4.38%|:red_circle:|
|aws|42.04%|:green_circle:|
|azure|2.47%|:red_circle:|
|catalog-common|9.92%|:red_circle:|
|catalog-fileset|79.77%|:green_circle:|
|catalog-glue|68.95%|:green_circle:|
|catalog-hive|82.96%|:green_circle:|
|catalog-jdbc-common|45.7%|:green_circle:|
|catalog-jdbc-doris|82.44%|:green_circle:|
|catalog-jdbc-mysql|79.33%|:green_circle:|
|catalog-jdbc-postgresql|83.39%|:green_circle:|
|catalog-jdbc-starrocks|79.16%|:green_circle:|
|catalog-kafka|77.01%|:green_circle:|
|catalog-lakehouse-generic|59.18%|:green_circle:|
|catalog-lakehouse-hudi|79.1%|:green_circle:|
|catalog-lakehouse-iceberg|85.86%|:green_circle:|
|catalog-lakehouse-paimon|84.23%|:green_circle:|
|catalog-model|77.72%|:green_circle:|
|cli|44.48%|:green_circle:|
|client-java|78.58%|:green_circle:|
|common|52.39%|:green_circle:|
|core|83.57%|:green_circle:|
|filesystem-hadoop3|77.28%|:green_circle:|
|flink|0.0%|:red_circle:|
|flink-common|48.68%|:green_circle:|
|flink-runtime|0.0%|:red_circle:|
|gcp|14.12%|:red_circle:|
|hadoop-auth|68.0%|:green_circle:|
|hadoop-common|12.7%|:red_circle:|
|hive-metastore-common|53.4%|:green_circle:|
|iceberg-aliyun-bundle|0.0%|:red_circle:|
|iceberg-common|64.75%|:green_circle:|
|iceberg-rest-server|75.0%|:green_circle:|
|idp-basic|85.98%|:green_circle:|
|integration-test-common|0.0%|:red_circle:|
|jobs|62.92%|:green_circle:|
|lance-common|31.63%|:red_circle:|
|lance-rest-server|63.47%|:green_circle:|
|lineage|53.02%|:green_circle:|
|optimizer|83.24%|:green_circle:|
|optimizer-api|21.95%|:red_circle:|
|server|87.57%|:green_circle:|
|server-common|79.57%|:green_circle:|
|spark|28.57%|:red_circle:|
|spark-common|45.89%|:green_circle:|
|tencent|69.84%|:green_circle:|
|trino-connector|47.17% **`+0.83%`**|:green_circle:|
<details>
<summary>Files</summary>
|Module|File|Coverage||
|:-|:-|:-|:-:|
|trino-connector|[GravitinoSystemTable.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTable.java)|100.0%|:green_circle:|
||[GravitinoSystemTableCatalogStatus.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableCatalogStatus.java)|97.92%|:green_circle:|
||[CatalogRegistrationState.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegistrationState.java)|95.56%|:green_circle:|
||[GravitinoSystemTableLoadStatus.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableLoadStatus.java)|92.5%|:green_circle:|
||[CatalogConnectorManager.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java)|77.32%|:green_circle:|
||[GravitinoSystemConnector.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnector.java)|35.29%|:red_circle:|
||[GravitinoConnectorFactory.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java)|18.89%|:red_circle:|
||[CatalogRegister.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java)|0.87%|:red_circle:|
||[AlterCatalogStoredProcedure.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/AlterCatalogStoredProcedure.java)|0.0%|:red_circle:|
||[CreateCatalogStoredProcedure.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/storedprocedure/CreateCatalogStoredProcedure.java)|0.0%|:red_circle:|
||[GravitinoSystemTableFactory.java](https://github.com/diqiu50/gravitino/blob/d2d8c19c5410485870aafa2d44b6abea297e761c/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableFactory.java)|0.0%|:red_circle:|
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#issuecomment-5392946800
The current tests cover the basic rendering and several individual states well, but the state-transition matrix is not complete yet. Please add coverage for the following cases before merge:
1. **Existing registered connector + refresh failure.** Put a real `CatalogConnectorContext` in the manager, then make `metalake.loadCatalog()` fail. Also cover an unregister failure. Assert that `catalog_status`, `catalogConnectorExist()`, and the expected `SHOW CATALOGS` presence remain consistent. The current tests mostly exercise catalogs that were never added to `catalogConnectors`, so they do not cover the production lifecycle of an already registered catalog.
2. **Unknown catalog type conversion.** Make `metalake.loadCatalog()` throw `UnsupportedOperationException("Unsupported catalog type: ...")` and verify that the row is reported as `UNSUPPORTED`, not `FAILED`.
3. **Reload and delete transitions with an existing connector.** Cover: unchanged refresh, successful reload, unregister-success/register-failure, successful deletion, and unregister failure. Verify status, failure count, last-success time, connector-map membership, and registration/unregistration calls for every transition.
4. **Deleted metalake cleanup.** Extend `testStateOfAVanishedMetalakeIsPruned` to create registered connector contexts and verify cleanup of `catalogStates`, `metalakeErrors`, `metalakes`, `catalogConnectors`, and the Trino catalogs, rather than checking only the first two maps.
5. **Multi-metalake isolation.** Use two entry catalogs/factories sharing the same `CatalogConnectorManager`, with catalogs and errors in both metalakes. Verify that `system.catalog`, `catalog_status`, and the per-metalake part of `load_status` expose only the entry catalog's metalake. Include a skip pattern that matches the qualified Trino catalog name.
6. **Atomic load-status snapshot.** Read `load_status` concurrently with a failing/recovering refresh and assert that one row cannot combine fields from two different load attempts.
7. **Initialization recovery.** Change the factory test from "fails twice" to "first initialization fails, the underlying condition is fixed, and the second create succeeds". Also verify that the failed manager/JDBC connection/driver/executor is cleaned up.
8. **Query/integration coverage.** Add `count(*)`/zero-projected-column coverage, query the status tables after an actual registration failure, and run at least one coordinator + separate worker scenario to verify that status-table splits are served by the coordinator.
The key invariant is that `catalog_status`, `load_status`, manager connector membership, and `SHOW CATALOGS` must describe the same state after every failure and recovery transition.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#discussion_r3913107159
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -206,12 +238,126 @@ private void loadMetalake() {
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);
+ }
}
+
+ catalogStates.values().removeIf(state -> !usedMetalakes.contains(state.getMetalake()));
Review Comment:
This unconditional pruning also removes the FAILED state recorded just above when unregistering a catalog from a vanished metalake fails. The connector then remains visible in `SHOW CATALOGS`, but `catalog_status` loses its diagnostic row and `load_status` can report success. Retain states while their Trino connector still exists, as the per-catalog pruning path already does.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java:
##########
@@ -134,7 +133,6 @@ public Connector create(
// 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;
Review Comment:
The manager is published before `start()` succeeds, and the start-attempt flag remains true if `start()` throws. A later static `create()` therefore skips startup and returns a system connector even though no load task was scheduled—the new tests explicitly exercise that dead-connector path. Preserve and rethrow the initialization failure, or discard/close the failed manager so creation cannot succeed with a stopped load loop.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java:
##########
@@ -350,7 +350,10 @@ public String getURI() {
* @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();
Review Comment:
The new whitespace-normalization behavior has no corresponding test in `TestGravitinoConfig`. Add a case with leading/trailing whitespace to lock down the returned canonical metalake and prevent this system-table filtering fix from regressing.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java:
##########
@@ -348,15 +364,35 @@ static String redactSecrets(String createCatalogCommand) {
// 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.
+ // log line downstream. Every level of the cause chain is rebuilt with its message redacted,
+ // rather than discarded outright, so a deep cause unrelated to credentials (e.g. a connector's
+ // own configuration validation error) still reaches the caller.
private static SQLException redactedSqlException(SQLException e) {
- String message = e.getMessage() == null ? null : redactSecrets(e.getMessage());
- SQLException redacted = new SQLException(message, e.getSQLState(), e.getErrorCode());
+ Throwable redactedCause = e.getCause() == null ? null : redactThrowableChain(e.getCause());
+ SQLException redacted =
+ new SQLException(
+ e.getMessage() == null ? null : redactSecrets(e.getMessage()),
+ e.getSQLState(),
+ e.getErrorCode(),
+ redactedCause);
redacted.setStackTrace(e.getStackTrace());
return redacted;
}
+ private static Throwable redactThrowableChain(Throwable t) {
+ // Guards against a cause cycle the same way toErrorMessage() in CatalogConnectorManager does.
+ Throwable cause = t.getCause();
+ Throwable redactedCause = (cause == null || cause == t) ? null : redactThrowableChain(cause);
Review Comment:
This guard handles only a throwable whose cause is itself. Java also permits multi-node cycles such as A → B → A, which recurse here until `StackOverflowError` instead of producing the intended redacted exception. Track visited throwables by identity (or rebuild the chain iteratively) and stop at any repeated node.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "diqiu50 (via GitHub)" <gi...@apache.org>.
diqiu50 merged PR #12547:
URL: https://github.com/apache/gravitino/pull/12547
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#discussion_r3841961350
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -212,67 +330,170 @@ public GravitinoMetalake retrieveMetalake(String metalakeName) {
}
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("Failed to list catalogs in metalake {}.", metalake.name(), e);
+ // 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);
+
+ // 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 catalogs. catalogs: {}.", metalake.name(), catalogNames);
+ LOG.debug("Load metalake {}'s catalogs. catalogs: {}.", 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("Failed to remove catalog {}.", entry.getKey(), e);
+ // The catalog is gone from Gravitino but 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.
+ GravitinoCatalog catalog = entry.getValue().getCatalog();
+ recordCatalogState(
+ CatalogRegistrationState.failed(
+ metalakeName,
+ catalog.getName(),
+ entry.getKey(),
+ catalog.getProvider(),
+ "The catalog was deleted in Gravitino but could not be unregistered from Trino: "
+ + 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);
- GravitinoCatalog gravitinoCatalog = new GravitinoCatalog(metalake.name(), catalog);
- 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 {} in metalake {}: {}",
- catalogName,
- metalake.name(),
- e.getMessage());
- } catch (Exception e) {
- LOG.error(
- "Failed to load metalake {}'s catalog {}.", metalake.name(), catalogName, e);
- }
+ for (String catalogName : catalogNames) {
+ String trinoCatalogName = getTrinoCatalogName(metalakeName, catalogName);
+ // 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);
Review Comment:
If a catalog that has been registered and can be seen via `SHOW CATALOGs` fails to load catalog info in a
certain rounds, the status will be marked as `FAILED`
However, as the doc says
- `REGISTERED` means it can be shown by `SHOW CATALOG`
- `FAILED` means it fails to register.
So we need to handle the case where a catalog has been registered successfully and fails to refresh.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#discussion_r3841838795
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -212,67 +330,170 @@ public GravitinoMetalake retrieveMetalake(String metalakeName) {
}
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("Failed to list catalogs in metalake {}.", metalake.name(), e);
+ // 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);
+
+ // 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 catalogs. catalogs: {}.", metalake.name(), catalogNames);
+ LOG.debug("Load metalake {}'s catalogs. catalogs: {}.", 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("Failed to remove catalog {}.", entry.getKey(), e);
+ // The catalog is gone from Gravitino but 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.
+ GravitinoCatalog catalog = entry.getValue().getCatalog();
+ recordCatalogState(
+ CatalogRegistrationState.failed(
+ metalakeName,
+ catalog.getName(),
+ entry.getKey(),
+ catalog.getProvider(),
+ "The catalog was deleted in Gravitino but could not be unregistered from Trino: "
+ + 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);
- GravitinoCatalog gravitinoCatalog = new GravitinoCatalog(metalake.name(), catalog);
- 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 {} in metalake {}: {}",
- catalogName,
- metalake.name(),
- e.getMessage());
- } catch (Exception e) {
- LOG.error(
- "Failed to load metalake {}'s catalog {}.", metalake.name(), catalogName, e);
- }
+ for (String catalogName : catalogNames) {
+ String trinoCatalogName = getTrinoCatalogName(metalakeName, catalogName);
+ // 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);
Review Comment:
**[Confirmed bug]** An `UnsupportedOperationException` thrown by `metalake.loadCatalog()` for a catalog type the client library doesn't recognize is now recorded as `FAILED` (with escalating `failure_count` and an ERROR log) instead of being handled as `UNSUPPORTED`.
`DTOConverters.toCatalog` (clients/client-java) throws `UnsupportedOperationException("Unsupported catalog type: " + catalog.type())` for a catalog type it doesn't map. The old code caught this specifically and logged a WARN with no persisted state. This new loop wraps `metalake.loadCatalog(catalogName)` inside the same try whose only catch is the generic `catch (Exception e)` below, which calls `recordCatalogState(CatalogRegistrationState.failed(...))`. Because the type/provider checks run only *after* `loadCatalog()` succeeds, this catalog is permanently misreported as FAILED (not UNSUPPORTED) in `gravitino.system.catalog_status`, defeating the PR's own goal of letting users self-diagnose via that table.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableCatalog.java:
##########
@@ -54,23 +56,29 @@ 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
public Page loadPageData() {
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);
Review Comment:
**[Confirmed bug, a few lines below]** `loadPageData()` calls `catalogConnectorManager.skipCatalog(catalog.name())` (unchanged line just below this hunk) with the bare Gravitino catalog name, while the load loop (`CatalogConnectorManager.loadCatalogs`) matches skip patterns against the Trino-qualified name via `skipCatalog(trinoCatalogName)`.
In multi-metalake mode, `getTrinoCatalogName` returns a quoted `"metalake.catalog"` form. If `gravitino.trino.skip-catalog-patterns` is written against that qualified form (e.g. `prod\..*`), the load loop correctly skips/unregisters matching catalogs (and now reports them SKIPPED in catalog_status), but this table still evaluates `skipCatalog()` against the bare catalog name, which never matches a metalake-qualified pattern — so `gravitino.system.catalog` keeps listing a catalog that is actually SKIPPED and absent from `SHOW CATALOGS`, misleading a user into thinking it is usable.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -310,6 +531,7 @@ private void unloadCatalog(GravitinoCatalog catalog) {
String catalogFullName = getTrinoCatalogName(catalog);
catalogRegister.unregisterCatalog(catalogFullName);
catalogConnectors.remove(catalogFullName);
+ catalogStates.remove(catalogFullName);
Review Comment:
**[Confirmed bug]** A catalog that newly starts matching `gravitino.trino.skip-catalog-patterns` has its just-recorded `SKIPPED` state deleted in the very same load cycle by this method, which unconditionally removes the `catalogStates` entry.
When a previously-REGISTERED catalog starts matching a skip pattern: (1) the load loop calls `recordCatalogState(skipped(...))` for it; (2) since it's now excluded from `catalogNames`, the unload loop sees it still in `catalogConnectors` and calls `unloadCatalog(...)`; (3) `unloadCatalog()` unregisters it from Trino correctly but also does `catalogStates.remove(catalogFullName)` here, wiping the SKIPPED row just written in step 1. For that one refresh cycle, `gravitino.system.catalog_status` has no row at all for the catalog, contradicting the PR's own documentation claim that catalog_status "covers every catalog the connector considered, including the ones catalog filters out." It reappears correctly on the next tick.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableLoadStatus.java:
##########
@@ -0,0 +1,131 @@
+/*
+ * 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.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.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * 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 = LoggerFactory.getLogger(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_started").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 trinoStartedColumnBuilder = 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);
+
+ BOOLEAN.writeBoolean(trinoStartedColumnBuilder, catalogConnectorManager.isTrinoStarted());
Review Comment:
**[Plausible]** `loadPageData()` makes six independent, unsynchronized reads of `CatalogConnectorManager` (`isTrinoStarted`, `getLastLoadAttemptTimeMs`, `getLastSuccessfulLoadTimeMs`, `getConsecutiveLoadFailures`, `getLastLoadError`, `getMetalakeErrors`) that the load loop updates as a group, with no atomic snapshot.
The background load loop writes these separate fields sequentially over the course of one cycle. A query thread landing mid-cycle can read `trino_started=true` (already updated) together with a stale `last_error` from the previous failed cycle and a `consecutive_load_failures` count not yet reset, producing a self-contradictory `load_status` row. Notably, `GravitinoSystemTableCatalogStatus` explicitly takes a single snapshot via `getCatalogRegistrationStates()` for exactly this reason, but that discipline wasn't applied here.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java:
##########
@@ -52,8 +53,6 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
public static final String DEFAULT_CONNECTOR_NAME = "gravitino";
@SuppressWarnings("UnusedVariable")
Review Comment:
**[Confirmed]** `@SuppressWarnings("UnusedVariable")` is left on this field after the field it originally annotated (the deleted `gravitinoSystemTableFactory` field) was removed by this diff; `catalogConnectorManager` is actively assigned and read and is not unused.
This stale suppression now silences an unused-variable warning that would never fire for this field, and misleads a reviewer into thinking the field is intentionally write-only. Should simply be deleted.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -186,14 +216,102 @@ private void loadMetalake() {
LOG.debug("Load metalake: {}", usedMetalake);
loadCatalogs(metalake);
} catch (Exception e) {
- LOG.error("Load Metalake {} failed.", usedMetalake, e);
+ recordMetalakeError(usedMetalake, e);
}
}
- } catch (Exception e) {
- LOG.error("Error when loading metalake", e);
+
+ pruneMissingMetalakes(usedMetalakes);
+
+ if (metalakeErrors.isEmpty()) {
+ lastSuccessfulLoadTimeMs = System.currentTimeMillis();
+ 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
+ // rows behind. Without this they keep reporting REGISTERED for catalogs that no longer exist.
+ catalogStates.values().removeIf(state -> !usedMetalakes.contains(state.getMetalake()));
+ metalakeErrors.keySet().removeIf(metalakeName -> !usedMetalakes.contains(metalakeName));
+ }
+
+ private void recordLoadSuccess() {
+ if (lastLoadError != null) {
+ LOG.info("The Gravitino catalog load loop recovered.");
+ }
+ lastLoadError = null;
+ consecutiveLoadFailures.set(0);
+ }
+
+ private void recordLoadFailure(String message, Throwable cause) {
+ boolean changed = !Objects.equals(lastLoadError, message);
+ lastLoadError = message;
+ consecutiveLoadFailures.incrementAndGet();
+ if (!changed) {
+ LOG.debug("Failed to load catalogs from the Gravitino server: {}", message, cause);
+ } else if (trinoStarted) {
+ LOG.error("Failed to load catalogs from the Gravitino server: {}", message, cause);
+ } else {
+ // Trino not being up yet is the normal state during startup, not an error.
+ LOG.info("{}", message);
+ }
+ }
+
+ 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 {} failed: {}", metalakeName, message, cause);
+ } else {
+ LOG.debug("Load metalake {} failed: {}", metalakeName, message, cause);
+ }
+ }
+
+ private static String toErrorMessage(Throwable e) {
Review Comment:
**[Plausible simplification]** `toErrorMessage(Throwable)` hand-rolls a bounded (`MAX_CAUSE_DEPTH=32`) root-cause walk with ad hoc cycle detection, duplicating Guava's `Throwables.getRootCause()`, which is already used elsewhere in the codebase and has proper cycle detection.
A cause chain longer than 32 links (unlikely but possible with deeply wrapped exceptions) is silently truncated at an arbitrary depth instead of reaching the true root, producing a less useful error message in catalog_status/load_status than Guava's well-tested implementation would. Replacing this loop with `Throwables.getRootCause(e)` removes the hand-rolled code and its arbitrary bound.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -382,6 +604,100 @@ public String getTrinoCatalogName(GravitinoCatalog catalog) {
return getTrinoCatalogName(catalog.getMetalake(), catalog.getName());
}
+ /**
+ * Retrieves a snapshot of the registration state of every Gravitino catalog seen by the load
+ * loop.
+ *
+ * @return the registration states
+ */
+ public List<CatalogRegistrationState> getCatalogRegistrationStates() {
Review Comment:
**[Plausible efficiency]** `getCatalogRegistrationStates()` does `List.copyOf(catalogStates.values())` over ALL metalakes' catalog states on every call, but its only caller (`GravitinoSystemTableCatalogStatus.loadPageData`) immediately discards everything outside the current connector's own metalake.
On every query against `gravitino.system.catalog_status`, a Trino cluster with many entry catalogs/metalakes and many catalogs per metalake copies the entire cluster-wide catalog-state collection just to keep the subset belonging to one metalake — cost scales with total cluster-wide catalog count rather than the querying connector's own. Filtering while streaming `catalogStates.values()` directly, or exposing a metalake-scoped accessor, would avoid materializing the full collection per query.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnector.java:
##########
@@ -183,14 +217,33 @@ public SchemaTableName getTableName() {
return tableName;
}
+ // 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 the scheduler through isRemotelyAccessible() and
+ // getAddresses() below. On a real worker JVM it is never set and the split keeps the previous
+ // remotely accessible behaviour; in a single JVM test runner the static is shared with the
+ // coordinator, which is harmless because only the coordinator's scheduler reads it.
+ private static volatile HostAddress coordinatorAddress;
Review Comment:
**[Plausible / CLAUDE.md violation]** This new static field `coordinatorAddress` is declared after the instance field `tableName`, the constructor, and the `getTableName()` method in the `Split` class, violating the project's Class Member Ordering rule (static constants → static fields → instance fields → constructors → methods).
This newly added static field sits after an instance field, a constructor, and a method instead of being grouped with the class's other fields before the constructor — a direct, quotable violation of the stated ordering rule in CLAUDE.md.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegistrationState.java:
##########
@@ -0,0 +1,299 @@
+/*
+ * 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 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;
+
+ private CatalogRegistrationState(
+ String metalake,
+ String catalogName,
+ String trinoCatalogName,
+ String provider,
+ Status status,
+ String lastError,
+ long lastAttemptTimeMs,
+ long lastSuccessTimeMs,
+ long failureCount) {
+ 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;
+ }
+
+ /**
+ * 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(
Review Comment:
**[Plausible simplification]** The four static factories (`succeeded`, `failed`, `skipped`, `unsupported`) are ~90% identical, each calling the same 9-arg private constructor and differing only in the `Status` literal and a couple of field values.
Adding a 10th field to this class requires editing the same field list in all four factories plus `withHistoryOf`'s reconstruction, with no compiler assistance if one call site is missed since the diffs all look alike — a copy-paste-and-forget-one-field bug is easy to introduce and hard to catch in review. A shared private helper taking `(metalake, catalogName, trinoCatalogName, provider, status, reason)` would collapse three of the four factories to one-line callers.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/table/GravitinoSystemTableCatalogStatus.java:
##########
@@ -0,0 +1,125 @@
+/*
+ * 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().stream()
+ .filter(state -> state.getMetalake().equals(metalake))
Review Comment:
**[Plausible]** This metalake scoping filter compares the raw `gravitino.metalake` connector-config string via `.equals()` against canonical metalake names collected by the load loop, with no normalization of case or whitespace.
`GravitinoConnectorFactory.create()` passes `config.getMetalake()` (the literal config value) into `GravitinoSystemTableFactory`, used unmodified in the `.filter(state -> state.getMetalake().equals(metalake))` / `.filter(metalake::equals)` checks across all three per-metalake tables. If the configured value differs even slightly (trailing whitespace, case) from the canonical name recorded in `CatalogRegistrationState`/`getUsedMetalakes()`, every row is silently filtered out — `gravitino.system.catalog`, `catalog_status`, and `load_status.metalake_errors` all report empty/zero with no error, even while catalogs are actively failing to load.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#discussion_r3921979156
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -206,12 +238,149 @@ private void loadMetalake() {
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(System.currentTimeMillis(), null, 0);
+ }
+
+ private void recordLoadFailure(String message, Throwable cause) {
+ LoadOutcome previous = loadOutcome;
+ boolean changed = !Objects.equals(previous.lastError, message);
+ loadOutcome =
+ new LoadOutcome(previous.lastSuccessTimeMs, message, previous.consecutiveFailures + 1);
+ if (!changed) {
+ LOG.warn(
+ "Failed to load catalogs from the Gravitino server: %s%n%s",
+ message, CatalogRegister.describe(cause));
+ } else if (trinoStarted) {
+ LOG.error(
+ "Failed to load catalogs from the Gravitino server: %s%n%s",
+ message, CatalogRegister.describe(cause));
Review Comment:
`recordLoadFailure` is called with a null cause both while waiting for Trino and when aggregating metalake errors. On the first metalake failure this branch calls `CatalogRegister.describe(null)`, throws a `NullPointerException`, and the outer catch replaces the real `load_status.last_error` with that secondary failure; repeated startup failures hit the other logging branch in the same way. Guard the optional cause before rendering it.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java:
##########
@@ -146,16 +144,27 @@ public Connector create(
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) {
+ if (catalogConnectorManagerStartTriggered) {
+ // Discard the half-started manager instead of keeping it: leaving it published would
+ // let the next create() skip the startup and hand out a connector whose load loop
+ // never started. start() fails inside CatalogRegister.init(), before any catalog is
+ // registered in Trino, so closing it here leaves nothing behind, and the next create()
+ // can start over once the configuration is fixed.
+ catalogConnectorManager.shutdown();
+ catalogConnectorManager = null;
+ catalogConnectorManagerStartTriggered = false;
Review Comment:
A manager may already own live dynamic connectors when the static catalog arrives—the dynamic-first path is explicitly supported above. If `start()` then fails, shutting down and discarding that shared manager closes its Gravitino client and executor and loses its connector map while those dynamic connectors remain installed in Trino. Recovery should dispose only the failed startup resources or otherwise preserve/rebind existing dynamic connector contexts instead of unconditionally shutting down the manager.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -232,67 +401,197 @@ public GravitinoMetalake retrieveMetalake(String metalakeName) {
}
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);
+
+ // 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.", metalake.name(), catalogNames);
+ 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 gone from Gravitino but 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.
+ GravitinoCatalog catalog = entry.getValue().getCatalog();
+ recordCatalogState(
+ CatalogRegistrationState.failed(
+ metalakeName,
+ catalog.getName(),
+ entry.getKey(),
+ catalog.getProvider(),
+ "The catalog was deleted in Gravitino but could not be unregistered from Trino: "
+ + 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();
+ if (alreadyRegistered) {
+ // Reload catalogs that have been updated in Gravitino server.
+ reloadCatalog(gravitinoCatalog);
+ recordCatalogState(
+ CatalogRegistrationState.succeeded(gravitinoCatalog, trinoCatalogName), null);
Review Comment:
This records a fresh successful-registration timestamp even when `reloadCatalog()` returns without issuing any registration because the catalog is unchanged. Consequently `last_success_time` advances on every refresh and duplicates `last_attempt_time`, contrary to the documented meaning “last registered successfully.” Preserve the previous success time on the no-op path, for example by having `reloadCatalog` report whether it actually re-registered.
This issue also appears on line 496 of the same file.
##########
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_started").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 trinoStartedColumnBuilder = 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 the three fields below come from the same attempt: reading them through three
+ // 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(trinoStartedColumnBuilder, catalogConnectorManager.isTrinoStarted());
+ writeTime(lastAttemptTimeColumnBuilder, catalogConnectorManager.getLastLoadAttemptTimeMs());
Review Comment:
Only three fields are captured in `LoadOutcome`; `trinoStarted`, `last_attempt_time`, and `metalake_errors` are read from separate volatile/map state that the load loop mutates before publishing the outcome. A query racing a refresh can therefore return contradictory diagnostics (for example `last_error = NULL` with a non-null `metalake_errors`, or `trino_started = false` with the previous successful outcome). Publish all row fields together in one immutable completed-attempt snapshot.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#discussion_r3922031713
##########
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 |
+|----------------------|----------------------------------------------------------------------------------------------|
Review Comment:
Format the table.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -232,67 +401,197 @@ public GravitinoMetalake retrieveMetalake(String metalakeName) {
}
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);
+
+ // 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.", metalake.name(), catalogNames);
+ 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 gone from Gravitino but 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.
+ GravitinoCatalog catalog = entry.getValue().getCatalog();
+ recordCatalogState(
+ CatalogRegistrationState.failed(
+ metalakeName,
+ catalog.getName(),
+ entry.getKey(),
+ catalog.getProvider(),
+ "The catalog was deleted in Gravitino but could not be unregistered from Trino: "
+ + 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();
+ if (alreadyRegistered) {
+ // Reload catalogs that have been updated in Gravitino server.
+ reloadCatalog(gravitinoCatalog);
+ recordCatalogState(
+ CatalogRegistrationState.succeeded(gravitinoCatalog, trinoCatalogName), null);
+ } else if (catalog.type() != Catalog.Type.RELATIONAL) {
Review Comment:
[Confirmed correctness gap] The eligibility checks occur only after the alreadyRegistered branch. If a live catalog is deleted and recreated under the same name with an unsupported type/provider, it is reloaded (or treated as an unchanged REGISTERED catalog) instead of transitioning to UNSUPPORTED. testUnsupportedCatalogKeepsLastSuccessTime does not exercise this path because it never creates a live connector context, so alreadyRegistered remains false. Please determine the desired state before choosing reload/register/unload and add live REGISTERED -> UNSUPPORTED transition coverage.
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -232,67 +401,197 @@ public GravitinoMetalake retrieveMetalake(String metalakeName) {
}
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);
+
+ // 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.", metalake.name(), catalogNames);
+ 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 gone from Gravitino but 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.
+ GravitinoCatalog catalog = entry.getValue().getCatalog();
+ recordCatalogState(
+ CatalogRegistrationState.failed(
+ metalakeName,
+ catalog.getName(),
+ entry.getKey(),
+ catalog.getProvider(),
+ "The catalog was deleted in Gravitino but could not be unregistered from Trino: "
Review Comment:
This unload branch handles both deleted catalogs and live catalogs that now match skip-catalog-patterns, because catalogNameStrings excludes skipped names. If unregistering a skipped catalog fails, this overwrites SKIPPED with FAILED and incorrectly says the catalog was deleted in Gravitino. presentTrinoNames can distinguish the two causes. Please add a live REGISTERED -> SKIPPED test for both successful and failed unregister.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#discussion_r3827749553
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/system/GravitinoSystemConnector.java:
##########
@@ -183,14 +192,30 @@ public SchemaTableName getTableName() {
return tableName;
}
+ // 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. Splits are built in
+ // SplitManager.getSplits(), which also runs on the coordinator, so this is always set by the
+ // time it is read. It stays null on worker JVMs, where the behaviour is unchanged.
+ private static volatile HostAddress coordinatorAddress;
+
+ /**
+ * Sets the coordinator address that system table splits are pinned to.
+ *
+ * @param address the host and port of the Trino coordinator
+ */
+ public static void setCoordinatorAddress(HostAddress address) {
+ coordinatorAddress = address;
+ }
+
@Override
public boolean isRemotelyAccessible() {
- return true;
+ return coordinatorAddress == null;
}
Review Comment:
`Split.isRemotelyAccessible()` / `getAddresses()` rely on the static `coordinatorAddress`, but `Split` instances are serialized/deserialized across nodes via JSON (`@JsonCreator` only includes `tableName`). On worker JVMs the static field remains `null`, so splits become remotely accessible and lose the coordinator pinning, which can schedule system table reads on workers where `GravitinoSystemTableFactory.SYSTEM_TABLES` is never registered (and queries will fail with "table does not exist").
To make split pinning reliable, the coordinator address needs to be part of the split payload (an instance field serialized with the split), or otherwise deterministically derivable on every node.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#issuecomment-5392397980
@yuqi1129 can you please help to review this PR?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "diqiu50 (via GitHub)" <gi...@apache.org>.
diqiu50 commented on PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#issuecomment-5521897056
> The current tests cover the basic rendering and several individual states well, but the state-transition matrix is not complete yet. Please add coverage for the following cases before merge:
>
> 1. **Existing registered connector + refresh failure.** Put a real `CatalogConnectorContext` in the manager, then make `metalake.loadCatalog()` fail. Also cover an unregister failure. Assert that `catalog_status`, `catalogConnectorExist()`, and the expected `SHOW CATALOGS` presence remain consistent. The current tests mostly exercise catalogs that were never added to `catalogConnectors`, so they do not cover the production lifecycle of an already registered catalog.
> 2. **Unknown catalog type conversion.** Make `metalake.loadCatalog()` throw `UnsupportedOperationException("Unsupported catalog type: ...")` and verify that the row is reported as `UNSUPPORTED`, not `FAILED`.
> 3. **Reload and delete transitions with an existing connector.** Cover: unchanged refresh, successful reload, unregister-success/register-failure, successful deletion, and unregister failure. Verify status, failure count, last-success time, connector-map membership, and registration/unregistration calls for every transition.
> 4. **Deleted metalake cleanup.** Extend `testStateOfAVanishedMetalakeIsPruned` to create registered connector contexts and verify cleanup of `catalogStates`, `metalakeErrors`, `metalakes`, `catalogConnectors`, and the Trino catalogs, rather than checking only the first two maps.
> 5. **Multi-metalake isolation.** Use two entry catalogs/factories sharing the same `CatalogConnectorManager`, with catalogs and errors in both metalakes. Verify that `system.catalog`, `catalog_status`, and the per-metalake part of `load_status` expose only the entry catalog's metalake. Include a skip pattern that matches the qualified Trino catalog name.
> 6. **Atomic load-status snapshot.** Read `load_status` concurrently with a failing/recovering refresh and assert that one row cannot combine fields from two different load attempts.
> 7. **Initialization recovery.** Change the factory test from "fails twice" to "first initialization fails, the underlying condition is fixed, and the second create succeeds". Also verify that the failed manager/JDBC connection/driver/executor is cleaned up.
> 8. **Query/integration coverage.** Add `count(*)`/zero-projected-column coverage, query the status tables after an actual registration failure, and run at least one coordinator + separate worker scenario to verify that status-table splits are served by the coordinator.
>
> The key invariant is that `catalog_status`, `load_status`, manager connector membership, and `SHOW CATALOGS` must describe the same state after every failure and recovery transition.
Fixed all issues, manually test Query/integration coverage
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#12546] improvement(trino-connector): Report catalog registration status through system tables [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #12547:
URL: https://github.com/apache/gravitino/pull/12547#discussion_r3841967640
##########
trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java:
##########
@@ -212,67 +330,170 @@ public GravitinoMetalake retrieveMetalake(String metalakeName) {
}
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("Failed to list catalogs in metalake {}.", metalake.name(), e);
+ // 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);
+
+ // 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 catalogs. catalogs: {}.", metalake.name(), catalogNames);
+ LOG.debug("Load metalake {}'s catalogs. catalogs: {}.", 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("Failed to remove catalog {}.", entry.getKey(), e);
+ // The catalog is gone from Gravitino but 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.
+ GravitinoCatalog catalog = entry.getValue().getCatalog();
+ recordCatalogState(
+ CatalogRegistrationState.failed(
+ metalakeName,
+ catalog.getName(),
+ entry.getKey(),
+ catalog.getProvider(),
+ "The catalog was deleted in Gravitino but could not be unregistered from Trino: "
+ + 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);
- GravitinoCatalog gravitinoCatalog = new GravitinoCatalog(metalake.name(), catalog);
- 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 {} in metalake {}: {}",
- catalogName,
- metalake.name(),
- e.getMessage());
- } catch (Exception e) {
- LOG.error(
- "Failed to load metalake {}'s catalog {}.", metalake.name(), catalogName, e);
- }
+ for (String catalogName : catalogNames) {
+ String trinoCatalogName = getTrinoCatalogName(metalakeName, catalogName);
+ // 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);
+ GravitinoCatalog gravitinoCatalog = new GravitinoCatalog(metalakeName, catalog);
+ provider = gravitinoCatalog.getProvider();
+ if (catalogConnectors.containsKey(trinoCatalogName)) {
+ // Reload catalogs that have been updated in Gravitino server.
+ reloadCatalog(gravitinoCatalog);
+ recordCatalogState(
+ CatalogRegistrationState.succeeded(gravitinoCatalog, trinoCatalogName), null);
+ } else if (catalog.type() != Catalog.Type.RELATIONAL) {
+ recordCatalogState(
+ CatalogRegistrationState.unsupported(
+ metalakeName,
+ catalogName,
+ trinoCatalogName,
+ gravitinoCatalog.getProvider(),
+ String.format(
+ "Only relational catalogs are supported, the catalog type is %s",
+ catalog.type())),
+ null);
+ } else if (!catalogConnectorFactory
+ .getSupportedCatalogProviders()
+ .contains(gravitinoCatalog.getProvider())) {
+ recordCatalogState(
+ CatalogRegistrationState.unsupported(
+ metalakeName,
+ catalogName,
+ trinoCatalogName,
+ gravitinoCatalog.getProvider(),
+ String.format(
+ "The catalog provider %s is not supported, the supported providers are %s",
+ gravitinoCatalog.getProvider(),
+ catalogConnectorFactory.getSupportedCatalogProviders())),
+ null);
+ } else {
+ loadCatalog(gravitinoCatalog);
+ recordCatalogState(
+ CatalogRegistrationState.succeeded(gravitinoCatalog, trinoCatalogName), null);
+ }
+ } catch (Exception e) {
+ recordCatalogState(
Review Comment:
An unknown catalog type may be marked as failed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org