Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -495,10 +495,24 @@ public static ImmutablePair<TableConfig, Stat> getTableConfigWithStat(ZkHelixPro
@Nullable
public static ImmutablePair<TableConfig, Integer> getTableConfigWithVersion(
ZkHelixPropertyStore<ZNRecord> propertyStore, String tableNameWithType) {
return getTableConfigWithVersion(propertyStore, tableNameWithType, true, true);
}

/// @param replaceVariables Whether to replace environment variables and system properties with their actual values
/// @param applyDecorator Whether to apply the registered [TableConfigDecoratorRegistry] decorator
/// @return a pair of table config and current version from znRecord, null if table config does not exist.
///
/// Pass {@code replaceVariables=false, applyDecorator=false} to read the config exactly as stored — needed when the
/// config will be transformed and written back (e.g. config migration), so that resolved env vars / decorations are
/// not accidentally persisted.
@Nullable
public static ImmutablePair<TableConfig, Integer> getTableConfigWithVersion(
ZkHelixPropertyStore<ZNRecord> propertyStore, String tableNameWithType, boolean replaceVariables,
boolean applyDecorator) {
Stat tableConfigStat = new Stat();
TableConfig tableConfig = toTableConfig(
propertyStore.get(constructPropertyStorePathForResourceConfig(tableNameWithType), tableConfigStat,
AccessOption.PERSISTENT));
AccessOption.PERSISTENT), replaceVariables, applyDecorator);
if (tableConfig == null) {
return null;
}
Expand Down Expand Up @@ -587,7 +601,7 @@ private static TableConfig toTableConfig(@Nullable ZNRecord znRecord, boolean re
TableConfig tableConfig = TableConfigSerDeUtils.fromZNRecord(znRecord);
TableConfig processedTableConfig = replaceVariables
? ConfigUtils.applyConfigWithEnvVariablesAndSystemProperties(tableConfig) : tableConfig;
return applyDecorator ? TableConfigDecoratorRegistry.applyDecorator(processedTableConfig) : tableConfig;
return applyDecorator ? TableConfigDecoratorRegistry.applyDecorator(processedTableConfig) : processedTableConfig;
} catch (Exception e) {
LOGGER.error("Caught exception while creating table config from ZNRecord: {}", znRecord.getId(), e);
return null;
Expand All @@ -599,6 +613,33 @@ public static void setSchema(ZkHelixPropertyStore<ZNRecord> propertyStore, Schem
AccessOption.PERSISTENT);
}

/// Updates an existing schema only if its stored version still matches. A nonnegative version prevents recreating
/// a schema deleted after the migration read.
public static boolean setSchema(ZkHelixPropertyStore<ZNRecord> propertyStore, Schema schema, int expectedVersion) {
Preconditions.checkArgument(expectedVersion >= 0, "Expected schema version must be nonnegative");
try {
return propertyStore.set(constructPropertyStorePathForSchema(schema.getSchemaName()),
SchemaSerDeUtils.toZNRecord(schema), expectedVersion, AccessOption.PERSISTENT);
} catch (ZkBadVersionException e) {
return false;
}
}

/// Reads the stored schema together with its ZK version, without changing its representation.
@Nullable
public static ImmutablePair<Schema, Integer> getSchemaWithVersion(ZkHelixPropertyStore<ZNRecord> propertyStore,
String schemaName) {
try {
Stat stat = new Stat();
ZNRecord record =
propertyStore.get(constructPropertyStorePathForSchema(schemaName), stat, AccessOption.PERSISTENT);
return record != null ? ImmutablePair.of(SchemaSerDeUtils.fromZNRecord(record), stat.getVersion()) : null;
} catch (Exception e) {
LOGGER.error("Caught exception while getting schema: {}", schemaName, e);
return null;
}
}

@Nullable
public static Schema getSchema(ZkHelixPropertyStore<ZNRecord> propertyStore, String schemaName) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ public enum ControllerMeter implements AbstractMetrics.Meter {
CONTROLLER_PERIODIC_TASK_ERROR("periodicTaskError", false),
CONTROLLER_TABLE_SEGMENT_UPLOAD_ERROR("TableSegmentUploadError", false),
PERIODIC_TASK_ERROR("periodicTaskError", false),
// Recommendations count definitions needing an update on each scan, including warning-only scans.
CONFIG_MIGRATION_RECOMMENDED("configMigrationRecommended", false),
SCHEMA_MIGRATION_RECOMMENDED("schemaMigrationRecommended", false),
// Config migration: a table config or schema was upgraded to a newer version and persisted.
CONFIG_MIGRATION_SUCCESS("configMigrationSuccess", false),
// Config migration: a table's config/schema migration failed (validation, or lost the CAS race and will retry).
CONFIG_MIGRATION_FAILURE("configMigrationFailure", false),
NUMBER_TIMES_SCHEDULE_TASKS_CALLED("tasks", true),
NUMBER_TASKS_SUBMITTED("tasks", false),
NUMBER_SEGMENT_UPLOAD_TIMEOUT_EXCEEDED("SegmentUploadTimeouts", true),
Expand Down
74 changes: 74 additions & 0 deletions pinot-controller/CONFIG_MIGRATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<!--

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.

-->
# Stored table definition migration

The controller inspects physical table configs and their shared schemas every hour.
By default it only logs warnings and records recommendations; it does not change stored definitions.

The initial rules move legacy stream/batch ingestion properties into `ingestionConfig`, convert
schema `timeFieldSpec` to `dateTimeFieldSpecs`, and move schema-field `transformFunction` properties
into each affected table's `ingestionConfig.transformConfigs`. Existing table transforms take precedence.
Unsupported conversions are left unchanged. Modern definitions are no-ops, including ones without
migration markers. A later edit that reintroduces legacy fields is detected again.

After all cluster components have been upgraded and rollback requirements have been reviewed, enable
updates through the cluster configuration API:

```sh
curl -X POST 'http://localhost:9000/cluster/configs' \
-H 'Content-Type: application/json' \
-d '{"controller.config.migration.auto.update.enabled":"true"}'
```

This cluster flag controls both schema and table-config updates. Controllers pick up changes without
a restart; updates run on the next scan. Leave it unset, delete it, or set it to `false` for warning-only mode.
The scan schedule remains a controller setting: `controller.config.migration.frequencyPeriod=1h` by default,
or `-1s` to disable the scan entirely.

For manual updates, move `tableIndexConfig.streamConfigs` into
`ingestionConfig.streamIngestionConfig.streamConfigMaps` as a one-element list. Move
`segmentsConfig.segmentPushType` and `segmentPushFrequency` into
`ingestionConfig.batchIngestionConfig.segmentIngestionType` and `segmentIngestionFrequency`.
TIME fields require an equivalent DATE_TIME format, granularity, and transform; unsupported time
conversions require manual review rather than automatic rewriting.

For each nonempty, nonvirtual schema-field transform, add a table transform with the same `columnName`
and `transformFunction` unless that table already overrides the column. Both OFFLINE and REALTIME table
configs are checked before removing the shared schema transforms. TIME conversion transforms generated
by the preceding rule are moved the same way. Empty, virtual, and nested-child transforms are left unchanged.

The controller validates all candidates, checks every affected table's captured version, writes changed
table configs, and removes the schema transforms in one atomic ZooKeeper transaction. A failed validation
or version conflict leaves all stored definitions unchanged. Table creation atomically advances the
schema's ZooKeeper version without changing its contents, so a new table also invalidates an in-flight
migration plan. Ingestion metadata readers fetch schema before table config to avoid combining an old
table config with a schema whose transforms have already moved.
Transforms whose behavior would change through template resolution or decorators are left on the schema.

Recommendation meters are `CONFIG_MIGRATION_RECOMMENDED` per physical table and
`SCHEMA_MIGRATION_RECOMMENDED` per shared schema. They count recommendations on each scan, rather than
unique definitions. `CONFIG_MIGRATION_SUCCESS` counts successful writes and `CONFIG_MIGRATION_FAILURE`
counts failed validation or update attempts. Schemas are counted once across hybrid table halves per run.

Automatic updates validate candidates and use version-checked writes. Concurrent edits/deletions and
stored fields that cannot survive a typed round trip prevent the update. Resolved environment values
are used for table validation and runtime actions; raw templates remain in storage. Schema-transform
migrations coordinate table and schema writes; other rules retain their independent update paths.
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
import org.apache.pinot.controller.helix.core.minion.PinotHelixTaskResourceManager;
import org.apache.pinot.controller.helix.core.minion.PinotTaskManager;
import org.apache.pinot.controller.helix.core.minion.TaskMetricsEmitter;
import org.apache.pinot.controller.helix.core.periodictask.ConfigMigrationManager;
import org.apache.pinot.controller.helix.core.periodictask.ControllerPeriodicTask;
import org.apache.pinot.controller.helix.core.realtime.PinotLLCRealtimeSegmentManager;
import org.apache.pinot.controller.helix.core.realtime.SegmentCompletionConfig;
Expand Down Expand Up @@ -150,6 +151,7 @@
import org.apache.pinot.core.util.trace.ContinuousJfrStarter;
import org.apache.pinot.materializedview.consistency.MaterializedViewConsistencyManager;
import org.apache.pinot.segment.local.utils.TableConfigUtils;
import org.apache.pinot.segment.local.utils.migration.DefaultConfigMigrationRegistry;
import org.apache.pinot.segment.spi.partition.PartitionFunctionFactory;
import org.apache.pinot.spi.config.instance.InstanceConfigValidatorRegistry;
import org.apache.pinot.spi.config.table.TableConfig;
Expand Down Expand Up @@ -227,6 +229,7 @@ public abstract class BaseControllerStarter implements ServiceStartable {
protected LeadControllerManager _leadControllerManager;
protected List<ServiceStatus.ServiceStatusCallback> _serviceStatusCallbackList;
protected StaleInstancesCleanupTask _staleInstancesCleanupTask;
protected ConfigMigrationManager _configMigrationManager;
protected TaskMetricsEmitter _taskMetricsEmitter;
protected PoolingHttpClientConnectionManager _connectionManager;
protected TenantRebalancer _tenantRebalancer;
Expand Down Expand Up @@ -1141,6 +1144,10 @@ protected List<PeriodicTask> setupControllerPeriodicTasks() {
_staleInstancesCleanupTask =
new StaleInstancesCleanupTask(_helixResourceManager, _leadControllerManager, _config, _controllerMetrics);
periodicTasks.add(_staleInstancesCleanupTask);
_configMigrationManager =
new ConfigMigrationManager(_helixResourceManager, _leadControllerManager, _config, _controllerMetrics,
DefaultConfigMigrationRegistry.create());
periodicTasks.add(_configMigrationManager);
_taskMetricsEmitter =
new TaskMetricsEmitter(_helixResourceManager, _helixTaskResourceManager, _leadControllerManager, _config,
_controllerMetrics);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,13 @@ public static class ControllerPeriodicTasksConf {
public static final String STALE_INSTANCES_CLEANUP_TASK_INSTANCES_RETENTION_PERIOD =
"controller.stale.instances.cleanup.task.minOfflineTimeBeforeDeletionPeriod";

// Cluster config: applies to both schemas and table configs without restarting controllers.
public static final String CONFIG_MIGRATION_AUTO_UPDATE_ENABLED = "controller.config.migration.auto.update.enabled";
public static final String CONFIG_MIGRATION_FREQUENCY_PERIOD = "controller.config.migration.frequencyPeriod";
public static final String CONFIG_MIGRATION_INITIAL_DELAY_SECONDS =
"controller.config.migration.initialDelaySeconds";
public static final String CONFIG_MIGRATION_CRON_EXPRESSION = "controller.config.migration.cronExpression";

public static final String TASK_METRICS_EMITTER_FREQUENCY_PERIOD =
"controller.minion.task.metrics.emitter.frequencyPeriod";
public static final String TASK_METRICS_EMITTER_CRON_EXPRESSION =
Expand Down Expand Up @@ -326,6 +333,11 @@ public static long getRandomInitialDelayInSeconds() {
public static final String DEFAULT_SEGMENT_LEVEL_VALIDATION_INTERVAL_PERIOD = "24h";
public static final String DEFAULT_SEGMENT_RELOCATOR_FREQUENCY_PERIOD = "1h";

// Inspect stored definitions by default. Rewriting them requires explicit opt-in after upgrading all nodes,
// because the new format may not be accepted by a previous release during rollback.
public static final boolean DEFAULT_CONFIG_MIGRATION_AUTO_UPDATE_ENABLED = false;
public static final String DEFAULT_CONFIG_MIGRATION_FREQUENCY_PERIOD = "1h";

// Realtime Consumer Monitor
public static final String RT_CONSUMER_MONITOR_FREQUENCY_PERIOD =
"controller.realtimeConsumerMonitor.frequencyPeriod";
Expand Down Expand Up @@ -1232,6 +1244,24 @@ public void setStaleInstancesCleanupTaskInstancesRetentionPeriod(String retentio
setProperty(ControllerPeriodicTasksConf.STALE_INSTANCES_CLEANUP_TASK_INSTANCES_RETENTION_PERIOD, retentionPeriod);
}

public int getConfigMigrationFrequencyInSeconds() {
String period = getProperty(ControllerPeriodicTasksConf.CONFIG_MIGRATION_FREQUENCY_PERIOD,
ControllerPeriodicTasksConf.DEFAULT_CONFIG_MIGRATION_FREQUENCY_PERIOD);
if (!isValidPeriodWithLogging(ControllerPeriodicTasksConf.CONFIG_MIGRATION_FREQUENCY_PERIOD, period)) {
period = ControllerPeriodicTasksConf.DEFAULT_CONFIG_MIGRATION_FREQUENCY_PERIOD;
}
return (int) convertPeriodToSeconds(period);
}

public long getConfigMigrationInitialDelaySeconds() {
return getProperty(ControllerPeriodicTasksConf.CONFIG_MIGRATION_INITIAL_DELAY_SECONDS,
ControllerPeriodicTasksConf.getRandomInitialDelayInSeconds());
}

public String getConfigMigrationCronExpression() {
return getProperty(ControllerPeriodicTasksConf.CONFIG_MIGRATION_CRON_EXPRESSION);
}

public int getDefaultTableMinReplicas() {
return getProperty(TABLE_MIN_REPLICAS, DEFAULT_TABLE_MIN_REPLICAS);
}
Expand Down
Loading