xiangfu0 commented on code in PR #20187:
URL: https://github.com/apache/pinot/pull/20187#discussion_r4699409791
##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java:
##########
@@ -2053,7 +2081,10 @@ public void addTable(TableConfig tableConfig,
List<StreamMetadata> streamMetadat
// Add table config
LOGGER.info("Adding table {}: Creating table config in the property
store", tableNameWithType);
- if (!ZKMetadataProvider.createTableConfig(_propertyStore, tableConfig)) {
+ if (requireRawNameAbsent) {
+ createFirstTableConfig(getOrBuildMultiWriteZkClient(),
PropertyPathBuilder.propertyStore(_helixClusterName),
+ tableConfig);
Review Comment:
`createFirstTableConfig` writes through the dedicated multi-write
`ZkClient`, but the read-back a few lines down
(`ZKMetadataProvider.getTableConfig(_propertyStore, ...)` followed by the
`checkState`) goes through the Helix manager's session. Those really are two
sessions; on a running controller I saw different session ids for them.
ZooKeeper only promises read-your-writes within a session, so the second
session can be served by a follower that hasn't applied the commit yet unless
it calls `sync()` first (see [consistency
guarantees](https://zookeeper.apache.org/doc/current/zookeeperProgrammers.html#ch_zkGuarantees)).
When that happens `getTableConfig` returns null, the `checkState` throws,
the catch block deletes the table that was just created, and LIKE returns a 500
with the new schema left behind. I couldn't reproduce it, because the tests run
a single ZK server where it can't happen, but on a 3 or 5 node ensemble with a
slow follower I'd expect it to fail now and then. The plain `addTable` path is
fine because it creates and reads through the same store.
Could the read-back use the same client that ran the multi, or the multi run
on the Helix session? The `IF NOT EXISTS` re-check in `executeCreateLike` after
a `TableAlreadyExistsException` has the same gap in the other direction: the
multi session saw the node, the Helix session may not have yet, and the
statement then returns 409 instead of the no-op.
##########
pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotDdlRestletResource.java:
##########
@@ -253,6 +262,249 @@ public Response executeDdl(
}
}
+ //
-------------------------------------------------------------------------------------------
+ // Table DDL: CREATE TABLE LIKE
+ //
-------------------------------------------------------------------------------------------
+
+ private Response executeCreateLike(CompiledCreateTableLike create, String
database, boolean dryRun,
+ HttpHeaders headers, Request httpRequest) {
+ if (TableNameBuilder.isTableResource(create.getRawTableName())
+ || TableNameBuilder.isTableResource(create.getSourceRawTableName())) {
+ throw badRequest("CREATE TABLE LIKE requires raw table names without
_OFFLINE or _REALTIME suffixes. "
+ + "Use TYPE OFFLINE or TYPE REALTIME to select a source variant.");
+ }
+ String targetName = translateTableNameForDdl(create.getDatabaseName() ==
null
+ ? create.getRawTableName()
+ : create.getDatabaseName() + "." + create.getRawTableName(), headers);
+ // An explicit source qualifier is independent of the target's
database/header. An unqualified
+ // source uses the request database, never the explicit target qualifier.
+ String sourceDatabase = create.getSourceDatabaseName();
+ if (sourceDatabase == null && headers != null) {
+ sourceDatabase = headers.getHeaderString(DATABASE);
+ }
+ String sourceName;
+ try {
+ sourceName =
DatabaseUtils.translateTableName(create.getSourceRawTableName(),
sourceDatabase);
+ } catch (DatabaseConflictException | IllegalArgumentException e) {
+ throw badRequest("Invalid source table reference: " + e.getMessage());
+ }
+
+ TableType sourceType = create.getTableType();
+ List<TableType> sourceTypes = sourceType == null
+ ? List.of(TableType.OFFLINE, TableType.REALTIME)
+ : List.of(sourceType);
+ for (TableType candidate : sourceTypes) {
+
ResourceUtils.checkPermissionAndAccess(TableNameBuilder.forType(candidate).tableNameWithType(sourceName),
+ httpRequest, headers, AccessType.READ,
Actions.Table.GET_TABLE_CONFIG, _accessControlFactory, LOGGER);
+ }
+ // LIKE creates a new raw-name identity. Its existence/no-op policy
considers both destination
+ // variants even with an explicit source TYPE, so authorize both before
looking at either.
+ for (TableType candidate : List.of(TableType.OFFLINE, TableType.REALTIME))
{
+
ResourceUtils.checkPermissionAndAccess(TableNameBuilder.forType(candidate).tableNameWithType(targetName),
+ httpRequest, headers, AccessType.CREATE, Actions.Table.CREATE_TABLE,
_accessControlFactory, LOGGER);
+ }
+ List<String> createdTables = new ArrayList<>(2);
+ DdlExecutionResponse response = new DdlExecutionResponse()
+ .setOperation(DdlOperation.CREATE_TABLE_LIKE)
+ .setDatabaseName(database)
+ .setTableName(targetName)
+ .setSourceTableName(sourceName)
+ .setDryRun(dryRun)
+ .setIfNotExists(create.isIfNotExists())
+ .setCreatedTables(createdTables);
+ Response existingTarget = existingCreateLikeTarget(create, targetName,
response);
+ if (existingTarget != null) {
+ return existingTarget;
+ }
+
+ if (_pinotHelixResourceManager.getLogicalTableConfig(sourceName) != null) {
+ throw badRequest("CREATE TABLE LIKE does not support a logical table as
its source: " + sourceName);
+ }
+ // Read templates, rather than resolved variables or decorator output, so
the new definition
+ // keeps its declarative settings and does not persist source-side
resolved credentials.
+ TableConfig offline = sourceType == TableType.REALTIME
+ ? null
+ : readCreateLikeTableConfig(sourceName, TableType.OFFLINE);
+ TableConfig realtime = sourceType == TableType.OFFLINE
+ ? null
+ : readCreateLikeTableConfig(sourceName, TableType.REALTIME);
+ if (offline == null && realtime == null) {
+ throw new ControllerApplicationException(LOGGER,
+ "Source table not found: " + sourceName + (sourceType == null ? "" :
" TYPE " + sourceType),
+ Response.Status.NOT_FOUND);
+ }
+ if ((offline != null && offline.isMaterializedView()) || (realtime != null
&& realtime.isMaterializedView())) {
+ throw badRequest("CREATE TABLE LIKE does not support a materialized view
as its source: " + sourceName);
+ }
+ Schema sourceSchema = readCreateLikeSchema(sourceName);
+ if (sourceSchema == null) {
+ throw new ControllerApplicationException(LOGGER, "Source schema not
found: " + sourceName,
+ Response.Status.NOT_FOUND);
+ }
+
+ TableConfigs copied;
+ try {
+ // TableConfig's copy constructor shares nested configs, maps, and
lists. Deep-copy the
+ // entire bundle before renaming, tuning, or validating it.
+ copied = JsonUtils.stringToObject(
+ new TableConfigs(sourceName, sourceSchema, offline,
realtime).toJsonString(), TableConfigs.class);
+ } catch (Exception e) {
+ throw new ControllerApplicationException(LOGGER, "Failed to copy source
table definition: " + sourceName,
+ Response.Status.INTERNAL_SERVER_ERROR, e);
+ }
+ copied.setTableName(targetName);
+ Schema schema = copied.getSchema();
+ Schema storedSchema = readCreateLikeSchema(targetName);
+ checkCreateLikeSchema(schema, storedSchema);
+ validateCreateLikeConfigs(copied, storedSchema);
+ response.setTableConfigs(toJson(copied));
+ if (dryRun) {
+ return Response.ok(response.setMessage("Dry run: validated CREATE TABLE
LIKE without persisting.")).build();
+ }
+
+ try {
+ if (storedSchema == null) {
+ try {
+ _pinotHelixResourceManager.addSchema(schema, false, false);
+ } catch (SchemaAlreadyExistsException e) {
+ Schema racedSchema = readCreateLikeSchema(targetName);
+ if (racedSchema == null) {
+ throw e;
+ }
+ checkCreateLikeSchema(schema, racedSchema);
+ }
+ }
+ // Recheck logical tables, materialized views and partially deleted
targets after the schema write.
+ Response racedTarget = existingCreateLikeTarget(create, targetName,
response);
+ if (racedTarget != null) {
+ return racedTarget;
+ }
+ TableConfig firstConfig = copied.getOffline() != null ?
copied.getOffline() : copied.getRealtime();
+ _pinotHelixResourceManager.addTableIfRawNameAbsent(firstConfig);
+ createdTables.add(firstConfig.getTableName());
+ // Only the request which created the OFFLINE half may add its REALTIME
sibling.
+ if (copied.getOffline() != null && copied.getRealtime() != null) {
+ _pinotHelixResourceManager.addTable(copied.getRealtime());
+ createdTables.add(copied.getRealtime().getTableName());
+ }
+ return Response.status(Response.Status.CREATED)
+ .entity(response.setMessage("Successfully created table " +
targetName + " LIKE " + sourceName)).build();
+ } catch (TableAlreadyExistsException e) {
+ if (createdTables.isEmpty() && create.isIfNotExists()) {
+ Response racedTarget = existingCreateLikeTarget(create, targetName,
response);
+ if (racedTarget != null) {
+ return racedTarget;
+ }
+ }
+ return createLikeFailure(response,
Response.Status.CONFLICT.getStatusCode(), e);
+ } catch (SchemaAlreadyExistsException e) {
+ return createLikeFailure(response,
Response.Status.CONFLICT.getStatusCode(), e);
+ } catch (ControllerApplicationException e) {
+ return createLikeFailure(response, e.getResponse().getStatus(), e);
+ } catch (Exception e) {
+ return createLikeFailure(response,
Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
+ }
+ }
+
+ @Nullable
+ private Schema readCreateLikeSchema(String rawTableName) {
+ try {
+ return _pinotHelixResourceManager.getSchemaStrict(rawTableName);
+ } catch (IOException | RuntimeException e) {
+ throw new ControllerApplicationException(LOGGER, "Failed to read schema:
" + rawTableName,
+ Response.Status.INTERNAL_SERVER_ERROR, e);
+ }
+ }
+
+ @Nullable
+ private TableConfig readCreateLikeTableConfig(String rawTableName, TableType
tableType) {
+ String tableNameWithType =
TableNameBuilder.forType(tableType).tableNameWithType(rawTableName);
+ try {
+ return _pinotHelixResourceManager.getRawTableConfig(tableNameWithType);
+ } catch (IOException | RuntimeException e) {
+ throw new ControllerApplicationException(LOGGER,
+ "Failed to read table config: " + tableNameWithType,
+ Response.Status.INTERNAL_SERVER_ERROR, e);
+ }
+ }
+
+ @Nullable
+ private Response existingCreateLikeTarget(CompiledCreateTableLike create,
String targetName,
+ DdlExecutionResponse response) {
+ if (_pinotHelixResourceManager.getLogicalTableConfig(targetName) != null) {
+ throw new ControllerApplicationException(LOGGER, "Logical table already
exists: " + targetName,
+ Response.Status.CONFLICT);
+ }
+ TableConfig offline = readCreateLikeTableConfig(targetName,
TableType.OFFLINE);
+ TableConfig realtime = readCreateLikeTableConfig(targetName,
TableType.REALTIME);
+ if ((offline != null && offline.isMaterializedView()) || (realtime != null
&& realtime.isMaterializedView())) {
+ throw badRequest("Cannot create table '" + targetName + "': a
materialized view already exists at this name.");
+ }
+ if (offline == null && realtime == null &&
!_pinotHelixResourceManager.hasOfflineTable(targetName)
+ && !_pinotHelixResourceManager.hasRealtimeTable(targetName)) {
+ return null;
+ }
+ if (create.isIfNotExists()) {
+ return Response.ok(response.setTableConfigs(null)
+ .setMessage("Table " + targetName + " already exists; CREATE IF NOT
EXISTS is a no-op.")).build();
+ }
+ throw new ControllerApplicationException(LOGGER, "Table " + targetName + "
already exists.",
+ Response.Status.CONFLICT);
+ }
+
+ private static void checkCreateLikeSchema(Schema copiedSchema, @Nullable
Schema storedSchema) {
+ if (storedSchema != null && !copiedSchema.equals(storedSchema)) {
+ throw new ControllerApplicationException(LOGGER,
+ "Schema '" + copiedSchema.getSchemaName() + "' already exists and
does not match the complete source schema.",
+ Response.Status.CONFLICT);
+ }
+ }
+
+ private void validateCreateLikeConfigs(TableConfigs copied, @Nullable Schema
storedSchema) {
+ try {
+ Schema schema = copied.getSchema();
+ TableConfig[] configs = {copied.getOffline(), copied.getRealtime()};
+ for (TableConfig tableConfig : configs) {
+ if (tableConfig != null) {
+ TableConfigTunerUtils.applyTunerConfigs(_pinotHelixResourceManager,
tableConfig, schema, Map.of());
+ }
+ }
+ boolean ignoreCase =
_pinotHelixResourceManager.getTableCache().isIgnoreCase();
+ if (storedSchema == null) {
+ // A new schema must pass the same admission rules as a POST to
/schemas.
+ SchemaUtils.validate(schema, List.of(), ignoreCase);
+ } else {
+ // A matching legacy schema still needs to be loadable, even when it
predates the admission rules.
+ checkCreateLikeSchema(schema, storedSchema);
+ SchemaUtils.validate(schema, ignoreCase);
+ }
+ for (TableConfig tableConfig : configs) {
+ if (tableConfig != null) {
+ validateTableConfig(schema, tableConfig);
+ PinotTableRestletResource.tableTasksValidation(tableConfig,
_pinotHelixTaskResourceManager);
+ }
+ }
+ if (copied.getOffline() != null && copied.getRealtime() != null) {
+ TableConfigUtils.verifyHybridTableConfigs(copied.getTableName(),
copied.getOffline(), copied.getRealtime());
+ }
+ } catch (ControllerApplicationException e) {
+ throw e;
+ } catch (IllegalArgumentException | IllegalStateException |
ConfigValidationException e) {
+ throw new ControllerApplicationException(LOGGER, "CREATE TABLE LIKE
validation failed: " + e.getMessage(),
+ Response.Status.BAD_REQUEST, e);
+ }
+ }
+
+ private static Response createLikeFailure(DdlExecutionResponse response, int
status, Exception cause) {
+ // Never delete by raw name here: a concurrent request may own a sibling
variant or schema.
+ // Preserve completed creates and report them even when a later variant
failed.
+ LOGGER.error("CREATE TABLE LIKE failed for {}; completed variants: {}",
response.getTableName(),
+ response.getCreatedTables(), cause);
+ response.setMessage("Failed to create table " + response.getTableName() +
": " + cause.getMessage()
+ + ". Completed variants: " + response.getCreatedTables());
+ return Response.status(status).entity(response).build();
+ }
Review Comment:
A failure in the write phase comes back as a `DdlExecutionResponse` with an
error status, while the same kind of failure caught before the write phase is
thrown as a `ControllerApplicationException` and gets the standard `{code,
error}` body. So a client sees two different 409 shapes depending on timing. I
tried both on a real controller: a duplicate target caught up front returns the
usual `error` message, but a 409 from `addTable` has no `error` field, so
Pinot's own `HttpClient.getErrorMessage` falls back to printing the whole
serialized response as the reason, full copied `tableConfigs` included.
I see why `createdTables` has to reach the caller on a partial failure.
Could the failure keep the standard error body and carry `createdTables` as an
extra field, or at least drop `tableConfigs` from it?
Two smaller things in the same place. This logs every failure at ERROR with
a stack trace, including ordinary 409 conflicts that
`ControllerApplicationException` would log at INFO. And when the first table
write fails, the schema this request created stays behind, but the response
only says `Completed variants: []`, so the caller isn't told there is a schema
to clean up.
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]