This is an automated email from the ASF dual-hosted git repository.
gortiz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git
The following commit(s) were added to refs/heads/master by this push:
new c470078ce40 Add instance capabilities to the Helix instance config
(#20058)
c470078ce40 is described below
commit c470078ce40c287526480605dee35d1487615720
Author: Gonzalo Ortiz Jaureguizar <[email protected]>
AuthorDate: Thu Nov 19 15:36:34 2026 +0100
Add instance capabilities to the Helix instance config (#20058)
Pinot instances advertise capabilities in the map field `capabilities` of
their Helix instance config: a name and an integer revision. Servers and
brokers write them at startup with HelixHelper.updateCapabilities, together
with a `pinotVersion` stamp that guards against rollbacks to builds that
predate the field.
InstanceCapabilityTracker computes the minimum revision of each capability
over a set of instance configs. BaseBrokerRoutingManager feeds it the records
that it already fetches on each instance config change, so a broker adds no
ZooKeeper reads or watches. RoutingManager.getMinServerCapabilityRevision
exposes the result, and MultiClusterRoutingManager takes the minimum over the
local and remote clusters. A failed refresh resets the minimum to 0 until the
next successful one.
The registry is empty in this change. Extensions can define their own
capabilities through the public InstanceCapability constructor and the
getInstanceCapabilities() hook of the starters.
---
.../broker/broker/helix/BaseBrokerStarter.java | 20 +-
.../routing/manager/BaseBrokerRoutingManager.java | 40 ++-
.../manager/MultiClusterRoutingManager.java | 12 +
.../routing/manager/BrokerRoutingManagerTest.java | 53 ++++
.../manager/MultiClusterRoutingManagerTest.java | 15 ++
.../pinot/common/utils/helix/HelixHelper.java | 34 ++-
.../common/utils/helix/InstanceCapability.java | 158 ++++++++++++
.../utils/helix/InstanceCapabilityTracker.java | 278 +++++++++++++++++++++
.../pinot/common/utils/helix/HelixHelperTest.java | 64 +++++
.../common/utils/helix/InstanceCapabilityTest.java | 44 ++++
.../utils/helix/InstanceCapabilityTrackerTest.java | 275 ++++++++++++++++++++
.../apache/pinot/core/routing/RoutingManager.java | 10 +
.../server/starter/helix/BaseServerStarter.java | 24 +-
.../apache/pinot/spi/utils/CommonConstants.java | 11 +
14 files changed, 1019 insertions(+), 19 deletions(-)
diff --git
a/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
b/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
index 0a8e4726c71..58603cd76b9 100644
---
a/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
+++
b/pinot-broker/src/main/java/org/apache/pinot/broker/broker/helix/BaseBrokerStarter.java
@@ -23,6 +23,7 @@ import com.google.common.base.Preconditions;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -40,7 +41,6 @@ import org.apache.helix.HelixConstants.ChangeType;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
-import org.apache.helix.InstanceType;
import org.apache.helix.SystemPropertyKeys;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
@@ -90,6 +90,7 @@ import
org.apache.pinot.common.utils.config.QueryOptionConfigListener;
import org.apache.pinot.common.utils.config.QueryWorkloadConfigUtils;
import org.apache.pinot.common.utils.config.TagNameUtils;
import org.apache.pinot.common.utils.helix.HelixHelper;
+import org.apache.pinot.common.utils.helix.InstanceCapability;
import org.apache.pinot.common.utils.tls.PinotInsecureMode;
import org.apache.pinot.common.utils.tls.RenewableTlsUtils;
import org.apache.pinot.common.utils.tls.TlsUtils;
@@ -113,6 +114,7 @@ import org.apache.pinot.spi.accounting.ThreadAccountant;
import org.apache.pinot.spi.accounting.ThreadAccountantUtils;
import org.apache.pinot.spi.accounting.ThreadResourceUsageProvider;
import org.apache.pinot.spi.accounting.WorkloadBudgetManagerFactory;
+import org.apache.pinot.spi.config.instance.InstanceType;
import org.apache.pinot.spi.config.provider.PinotClusterConfigChangeListener;
import org.apache.pinot.spi.cursors.ResponseStoreService;
import org.apache.pinot.spi.env.PinotConfiguration;
@@ -503,10 +505,10 @@ public abstract class BaseBrokerStarter implements
ServiceStartable {
// Initialize workload budget manager and thread resource usage
accountant. Workload budget manager must be
// initialized first because it might be used by the accountant.
PinotConfiguration accountingConfig =
ThreadAccountantUtils.extractAccountingConfig(_brokerConf,
- org.apache.pinot.spi.config.instance.InstanceType.BROKER);
+ InstanceType.BROKER);
WorkloadBudgetManagerFactory.register(accountingConfig);
_threadAccountant =
ThreadAccountantUtils.createAccountant(accountingConfig, _instanceId,
- org.apache.pinot.spi.config.instance.InstanceType.BROKER);
+ InstanceType.BROKER);
_threadAccountant.startWatcherTask();
// Get all workload budgets this instance should support
QueryWorkloadConfigUtils.getAndUpdateWorkloadBudgets(_instanceId,
_spectatorHelixManager,
@@ -726,7 +728,8 @@ public abstract class BaseBrokerStarter implements
ServiceStartable {
LOGGER.info("Connecting participant Helix manager");
_participantHelixManager =
- HelixManagerFactory.getZKHelixManager(_clusterName, _instanceId,
InstanceType.PARTICIPANT, _zkServers);
+ HelixManagerFactory.getZKHelixManager(_clusterName, _instanceId,
+ org.apache.helix.InstanceType.PARTICIPANT, _zkServers);
// Register state model factory
_participantHelixManager.getStateMachineEngine()
.registerStateModelFactory(BrokerResourceOnlineOfflineStateModelFactory.getStateModelDef(),
@@ -864,6 +867,12 @@ public abstract class BaseBrokerStarter implements
ServiceStartable {
protected void registerExtraComponents(BrokerAdminApiApplication
brokerAdminApplication) {
}
+ /// The capabilities that this broker advertises in its instance config at
startup, see [InstanceCapability]. A
+ /// distribution or a plugin built on Pinot overrides it to add its own
capabilities to [InstanceCapability#values()].
+ protected Collection<InstanceCapability> getInstanceCapabilities() {
+ return InstanceCapability.values();
+ }
+
private void updateInstanceConfigAndBrokerResourceIfNeeded() {
InstanceConfig instanceConfig =
HelixHelper.getInstanceConfig(_participantHelixManager, _instanceId);
boolean updated = HelixHelper.updateHostnamePort(instanceConfig,
_hostname, _port);
@@ -924,7 +933,8 @@ public abstract class BaseBrokerStarter implements
ServiceStartable {
instanceTags = instanceConfig.getTags();
updated = true;
}
- updated |= HelixHelper.updatePinotVersion(instanceConfig);
+ // Also writes the simple field pinotVersion.
+ updated |= HelixHelper.updateCapabilities(instanceConfig,
InstanceType.BROKER, getInstanceCapabilities());
if (updated) {
HelixHelper.updateInstanceConfig(_participantHelixManager,
instanceConfig);
}
diff --git
a/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/BaseBrokerRoutingManager.java
b/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/BaseBrokerRoutingManager.java
index b217fd49b8c..376b9ed01a3 100644
---
a/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/BaseBrokerRoutingManager.java
+++
b/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/BaseBrokerRoutingManager.java
@@ -83,6 +83,8 @@ import org.apache.pinot.common.request.BrokerRequest;
import org.apache.pinot.common.utils.HashUtil;
import org.apache.pinot.common.utils.config.QueryOptionsUtils;
import org.apache.pinot.common.utils.helix.HelixHelper;
+import org.apache.pinot.common.utils.helix.InstanceCapability;
+import org.apache.pinot.common.utils.helix.InstanceCapabilityTracker;
import org.apache.pinot.core.routing.RoutingManager;
import org.apache.pinot.core.routing.RoutingTable;
import org.apache.pinot.core.routing.SegmentsToQuery;
@@ -93,6 +95,7 @@ import
org.apache.pinot.core.routing.timeboundary.TimeBoundaryStrategy;
import org.apache.pinot.core.routing.timeboundary.TimeBoundaryStrategyService;
import org.apache.pinot.core.transport.ServerInstance;
import
org.apache.pinot.core.transport.server.routing.stats.ServerRoutingStatsManager;
+import org.apache.pinot.spi.config.instance.InstanceType;
import org.apache.pinot.spi.config.provider.PinotClusterConfigChangeListener;
import org.apache.pinot.spi.config.table.ColumnPartitionConfig;
import org.apache.pinot.spi.config.table.QueryConfig;
@@ -184,6 +187,10 @@ public abstract class BaseBrokerRoutingManager
private String _instanceConfigsPath;
protected ZkHelixPropertyStore<ZNRecord> _propertyStore;
+ // The capabilities of the servers, fed with the instance configs that
processInstanceConfigChangeInternal() reads.
+ // Created in init(). Null before init(), which counts as no capability.
+ private volatile InstanceCapabilityTracker _serverCapabilityTracker;
+
private volatile int _partitionPruningPreparationThreshold =
CommonConstants.Broker.DEFAULT_PARTITION_PRUNING_PREPARATION_THRESHOLD;
@@ -224,6 +231,7 @@ public abstract class BaseBrokerRoutingManager
_idealStatePathPrefix =
helixDataAccessor.keyBuilder().idealStates().getPath() + "/";
_instanceConfigsPath =
helixDataAccessor.keyBuilder().instanceConfigs().getPath();
_propertyStore = helixManager.getHelixPropertyStore();
+ _serverCapabilityTracker = new
InstanceCapabilityTracker(helixManager.getClusterName(), InstanceType.SERVER);
}
@Override
@@ -473,11 +481,31 @@ public abstract class BaseBrokerRoutingManager
LOGGER.info("Processing instance config change");
long startTimeMs = System.currentTimeMillis();
- List<ZNRecord> instanceConfigZNRecords =
- _zkDataAccessor.getChildren(_instanceConfigsPath, null,
AccessOption.PERSISTENT, Helix.ZkClient.RETRY_COUNT,
- Helix.ZkClient.RETRY_INTERVAL_MS);
+ List<ZNRecord> instanceConfigZNRecords;
+ try {
+ instanceConfigZNRecords =
+ _zkDataAccessor.getChildren(_instanceConfigsPath, null,
AccessOption.PERSISTENT, Helix.ZkClient.RETRY_COUNT,
+ Helix.ZkClient.RETRY_INTERVAL_MS);
+ } catch (RuntimeException e) {
+ // The previous snapshot no longer proves that a server supports a
capability: the server can restart under the
+ // same id on an older build. Support nothing until the next successful
fetch.
+ _serverCapabilityTracker.invalidate();
+ throw e;
+ }
long fetchInstanceConfigsEndTimeMs = System.currentTimeMillis();
+ // Feed the capability tracker with the same snapshot, so that it reads no
ZooKeeper data of its own. A failure here
+ // must not stop the routing update: the tracker then supports nothing
until the next successful update.
+ // The tracker publishes before the routing below changes. That order is
safe: a new server lowers the minimum
+ // before it becomes routable. The minimum goes up only when a server
rewrites its own instance config with a newer
+ // revision, or when its instance config is deleted, which needs the
server to be down already.
+ try {
+ _serverCapabilityTracker.update(instanceConfigZNRecords);
+ } catch (Exception e) {
+ LOGGER.error("Caught exception while updating the server capabilities",
e);
+ _serverCapabilityTracker.invalidate();
+ }
+
// Calculate new enabled and disabled servers
Set<String> enabledServers = new HashSet<>();
// Every server that still has an instance config, enabled or not. Holds
the raw ids from the records, while
@@ -1429,6 +1457,12 @@ public abstract class BaseBrokerRoutingManager
return _routableServerInstanceMap;
}
+ @Override
+ public int getMinServerCapabilityRevision(InstanceCapability capability) {
+ InstanceCapabilityTracker serverCapabilityTracker =
_serverCapabilityTracker;
+ return serverCapabilityTracker != null ?
serverCapabilityTracker.getMinRevision(capability) : 0;
+ }
+
@Override
public Set<String> getRoutableTables() {
return Set.copyOf(_routingEntryMap.keySet());
diff --git
a/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/MultiClusterRoutingManager.java
b/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/MultiClusterRoutingManager.java
index 538b85dd416..28e5142ade0 100644
---
a/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/MultiClusterRoutingManager.java
+++
b/pinot-broker/src/main/java/org/apache/pinot/broker/routing/manager/MultiClusterRoutingManager.java
@@ -30,6 +30,7 @@ import java.util.function.Predicate;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.helix.InstanceCapability;
import org.apache.pinot.core.routing.RoutingManager;
import org.apache.pinot.core.routing.RoutingTable;
import org.apache.pinot.core.routing.SegmentsToQuery;
@@ -158,6 +159,17 @@ public class MultiClusterRoutingManager implements
RoutingManager {
return combined;
}
+ /// The minimum over the local cluster and every remote cluster. A remote
cluster that has not processed its instance
+ /// configs yet counts as 0.
+ @Override
+ public int getMinServerCapabilityRevision(InstanceCapability capability) {
+ int minRevision =
_localClusterRoutingManager.getMinServerCapabilityRevision(capability);
+ for (BaseBrokerRoutingManager remoteCluster :
_remoteClusterRoutingManagers) {
+ minRevision = Math.min(minRevision,
remoteCluster.getMinServerCapabilityRevision(capability));
+ }
+ return minRevision;
+ }
+
@Override
public Map<String, ServerInstance> getRoutableServerInstanceMap() {
Map<String, ServerInstance> combined = new
HashMap<>(_localClusterRoutingManager.getRoutableServerInstanceMap());
diff --git
a/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/BrokerRoutingManagerTest.java
b/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/BrokerRoutingManagerTest.java
index e179ed1eccd..0e9b6a19104 100644
---
a/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/BrokerRoutingManagerTest.java
+++
b/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/BrokerRoutingManagerTest.java
@@ -20,6 +20,7 @@ package org.apache.pinot.broker.routing.manager;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -56,6 +57,7 @@ import org.apache.pinot.common.metrics.BrokerTimer;
import org.apache.pinot.common.request.BrokerRequest;
import org.apache.pinot.common.request.QuerySource;
import org.apache.pinot.common.utils.config.TableConfigSerDeUtils;
+import org.apache.pinot.common.utils.helix.InstanceCapability;
import org.apache.pinot.core.routing.RoutingTable;
import org.apache.pinot.core.routing.SegmentsToQuery;
import org.apache.pinot.core.routing.TablePartitionInfo;
@@ -63,6 +65,7 @@ import
org.apache.pinot.core.routing.TablePartitionReplicatedServersInfo;
import org.apache.pinot.core.routing.timeboundary.TimeBoundaryInfo;
import org.apache.pinot.core.transport.ServerInstance;
import
org.apache.pinot.core.transport.server.routing.stats.ServerRoutingStatsManager;
+import org.apache.pinot.spi.config.instance.InstanceType;
import org.apache.pinot.spi.config.table.TableConfig;
import org.apache.pinot.spi.config.table.TableType;
import org.apache.pinot.spi.env.PinotConfiguration;
@@ -320,6 +323,47 @@ public class BrokerRoutingManagerTest {
assertTrue(_routingManager.getEnabledServerInstanceMap().containsKey(SERVER_INSTANCE_ID));
}
+ @Test
+ public void testMinServerCapabilityRevisionFollowsInstanceConfigs() {
+ InstanceCapability capability = new InstanceCapability("TEST_CAPABILITY",
InstanceType.SERVER, 1);
+ // Before the first instance config change, no capability is supported.
+ assertEquals(_routingManager.getMinServerCapabilityRevision(capability),
0);
+
+ String otherServer = "Server_otherhost_8000";
+ ZNRecord server1 = createServerZNRecordWithCapability(SERVER_INSTANCE_ID,
"2");
+ ZNRecord server2 = createServerZNRecordWithCapability(otherServer, "1");
+ // A broker without the capability does not count.
+ ZNRecord broker = new ZNRecord("Broker_localhost_8099");
+ when(_zkDataAccessor.getChildren(eq(INSTANCE_CONFIGS_PATH), any(),
eq(AccessOption.PERSISTENT), anyInt(),
+ anyInt())).thenReturn(List.of(server1, server2, broker));
+ _routingManager.processClusterChange(ChangeType.INSTANCE_CONFIG);
+ assertEquals(_routingManager.getMinServerCapabilityRevision(capability),
1);
+
+ // A disabled server still counts.
+
server2.setSimpleField(InstanceConfig.InstanceConfigProperty.HELIX_ENABLED.name(),
"false");
+
server2.getMapField(Helix.Instance.CAPABILITIES_KEY).remove("TEST_CAPABILITY");
+ _routingManager.processClusterChange(ChangeType.INSTANCE_CONFIG);
+ assertEquals(_routingManager.getMinServerCapabilityRevision(capability),
0);
+
+ // The server is removed.
+ when(_zkDataAccessor.getChildren(eq(INSTANCE_CONFIGS_PATH), any(),
eq(AccessOption.PERSISTENT), anyInt(),
+ anyInt())).thenReturn(List.of(server1, broker));
+ _routingManager.processClusterChange(ChangeType.INSTANCE_CONFIG);
+ assertEquals(_routingManager.getMinServerCapabilityRevision(capability),
2);
+
+ // A failed fetch supports nothing: a server can restart under the same id
on an older build.
+ when(_zkDataAccessor.getChildren(eq(INSTANCE_CONFIGS_PATH), any(),
eq(AccessOption.PERSISTENT), anyInt(),
+ anyInt())).thenThrow(new RuntimeException("ZooKeeper is not
reachable"));
+ expectThrows(RuntimeException.class, () ->
_routingManager.processClusterChange(ChangeType.INSTANCE_CONFIG));
+ assertEquals(_routingManager.getMinServerCapabilityRevision(capability),
0);
+
+ // The next successful fetch restores the minimum, also when the instance
configs did not change.
+ doReturn(List.of(server1, broker)).when(_zkDataAccessor)
+ .getChildren(eq(INSTANCE_CONFIGS_PATH), any(),
eq(AccessOption.PERSISTENT), anyInt(), anyInt());
+ _routingManager.processClusterChange(ChangeType.INSTANCE_CONFIG);
+ assertEquals(_routingManager.getMinServerCapabilityRevision(capability),
2);
+ }
+
@Test
public void testServerEnabledCallbackInvokedWhenExcludedServerReenabled() {
// Set up callback
@@ -1127,6 +1171,15 @@ public class BrokerRoutingManagerTest {
verify(_routingManager, never()).buildRouting(TEST_TABLE);
}
+ /// Creates an enabled server instance that advertises `TEST_CAPABILITY`
with the given revision.
+ private ZNRecord createServerZNRecordWithCapability(String instanceId,
String revision) {
+ ZNRecord record = createEnabledServerZNRecord(instanceId);
+ record.setSimpleField(Helix.Instance.PINOT_VERSION_KEY, "1.0.0");
+ record.setMapField(Helix.Instance.CAPABILITIES_KEY, new HashMap<>(
+ Map.of("TEST_CAPABILITY", revision,
Helix.Instance.CAPABILITIES_PINOT_VERSION_KEY, "1.0.0")));
+ return record;
+ }
+
/// Creates a ZNRecord representing a disabled server instance.
@SuppressWarnings("deprecation") // The routing manager still reads Helix's
legacy enabled flag for compatibility.
private ZNRecord createDisabledServerZNRecord(String instanceId) {
diff --git
a/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/MultiClusterRoutingManagerTest.java
b/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/MultiClusterRoutingManagerTest.java
index 98131d62716..a7c266797c3 100644
---
a/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/MultiClusterRoutingManagerTest.java
+++
b/pinot-broker/src/test/java/org/apache/pinot/broker/routing/manager/MultiClusterRoutingManagerTest.java
@@ -26,11 +26,13 @@ import java.util.Map;
import java.util.Set;
import org.apache.pinot.common.request.BrokerRequest;
import org.apache.pinot.common.request.QuerySource;
+import org.apache.pinot.common.utils.helix.InstanceCapability;
import org.apache.pinot.core.routing.RoutingTable;
import org.apache.pinot.core.routing.SegmentsToQuery;
import org.apache.pinot.core.routing.TablePartitionReplicatedServersInfo;
import org.apache.pinot.core.routing.timeboundary.TimeBoundaryInfo;
import org.apache.pinot.core.transport.ServerInstance;
+import org.apache.pinot.spi.config.instance.InstanceType;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
@@ -75,6 +77,19 @@ public class MultiClusterRoutingManagerTest {
_localClusterRoutingManager, remoteClusterManagers);
}
+ @Test
+ public void testMinServerCapabilityRevisionAcrossClusters() {
+ InstanceCapability capability = new InstanceCapability("TEST_CAPABILITY",
InstanceType.SERVER, 1);
+
when(_localClusterRoutingManager.getMinServerCapabilityRevision(capability)).thenReturn(3);
+
when(_remoteClusterRoutingManager1.getMinServerCapabilityRevision(capability)).thenReturn(2);
+
when(_remoteClusterRoutingManager2.getMinServerCapabilityRevision(capability)).thenReturn(4);
+
assertEquals(_multiClusterRoutingManager.getMinServerCapabilityRevision(capability),
2);
+
+ // A remote cluster that has not processed its instance configs yet counts
as 0.
+
when(_remoteClusterRoutingManager2.getMinServerCapabilityRevision(capability)).thenReturn(0);
+
assertEquals(_multiClusterRoutingManager.getMinServerCapabilityRevision(capability),
0);
+ }
+
@Test
public void testRoutingExistsShortCircuits() {
when(_localClusterRoutingManager.routingExists(TEST_TABLE)).thenReturn(true);
diff --git
a/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/HelixHelper.java
b/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/HelixHelper.java
index 6517ffe002b..88a51141976 100644
---
a/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/HelixHelper.java
+++
b/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/HelixHelper.java
@@ -20,6 +20,7 @@ package org.apache.pinot.common.utils.helix;
import com.google.common.base.Preconditions;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
@@ -37,7 +38,6 @@ import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.HelixProperty;
-import org.apache.helix.InstanceType;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.HelixConfigScope;
@@ -53,6 +53,7 @@ import org.apache.pinot.common.utils.config.TagNameUtils;
import org.apache.pinot.common.utils.tls.ZooKeeperSslContextSupplier;
import org.apache.pinot.common.version.PinotVersion;
import org.apache.pinot.common.workload.WorkloadChangeListener;
+import org.apache.pinot.spi.config.instance.InstanceType;
import org.apache.pinot.spi.config.table.TableConfig;
import org.apache.pinot.spi.config.table.TableType;
import org.apache.pinot.spi.data.LogicalTableConfig;
@@ -84,8 +85,8 @@ public class HelixHelper {
/// Creates a ZooKeeper-backed manager with Pinot's TLS bootstrap policy
applied before construction.
/// Callers retain responsibility for the manager's connect/disconnect
lifecycle.
- public static HelixManager createZkHelixManager(String clusterName, String
instanceName, InstanceType instanceType,
- String zkAddress) {
+ public static HelixManager createZkHelixManager(String clusterName, String
instanceName,
+ org.apache.helix.InstanceType instanceType, String zkAddress) {
ZooKeeperSslContextSupplier.initialize();
return HelixManagerFactory.getZKHelixManager(clusterName, instanceName,
instanceType, zkAddress);
}
@@ -719,6 +720,33 @@ public class HelixHelper {
return false;
}
+ /// Writes the capabilities that an instance of the given type advertises in
this version
+ /// ([InstanceCapability#values()]) to the map field `capabilities` of the
instance config, together with the
+ /// reserved entry `pinotVersion`
([CommonConstants.Helix.Instance#CAPABILITIES_PINOT_VERSION_KEY]) set to the
Pinot
+ /// version of this build. It also writes the simple field `pinotVersion`
with [#updatePinotVersion], so one call
+ /// leaves a record that readers trust: readers ignore the capabilities when
the two values differ. The call replaces
+ /// the whole map, so a capability that this build does not advertise
disappears. Any instance type can call it.
+ /// Returns whether the instance config changed.
+ public static boolean updateCapabilities(InstanceConfig instanceConfig,
InstanceType instanceType) {
+ return updateCapabilities(instanceConfig, instanceType,
InstanceCapability.values());
+ }
+
+ /// Same as [#updateCapabilities(InstanceConfig, InstanceType)] with the
given capabilities instead of
+ /// [InstanceCapability#values()]. An extension passes the capabilities of
Pinot together with its own, see
+ /// [InstanceCapability]. Fails, before it changes the instance config, when
two capabilities have the same name.
+ public static boolean updateCapabilities(InstanceConfig instanceConfig,
InstanceType instanceType,
+ Collection<InstanceCapability> capabilities) {
+ Map<String, String> currentCapabilities =
InstanceCapability.toMapField(capabilities, instanceType);
+
currentCapabilities.put(CommonConstants.Helix.Instance.CAPABILITIES_PINOT_VERSION_KEY,
PinotVersion.VERSION);
+ boolean updated = updatePinotVersion(instanceConfig);
+ ZNRecord record = instanceConfig.getRecord();
+ if
(!currentCapabilities.equals(record.getMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY)))
{
+ record.setMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY,
currentCapabilities);
+ updated = true;
+ }
+ return updated;
+ }
+
public static boolean updateMaxConcurrentTasksPerInstance(InstanceConfig
instanceConfig, int maxConcurrentTasks) {
int currentMaxConcurrentTasks = instanceConfig.getMaxConcurrentTask();
if (currentMaxConcurrentTasks != maxConcurrentTasks) {
diff --git
a/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/InstanceCapability.java
b/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/InstanceCapability.java
new file mode 100644
index 00000000000..0c106f97629
--- /dev/null
+++
b/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/InstanceCapability.java
@@ -0,0 +1,158 @@
+/**
+ * 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.pinot.common.utils.helix;
+
+import com.google.common.base.Preconditions;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.pinot.spi.config.instance.InstanceType;
+
+
+/// A feature that a Pinot instance advertises in its instance config, with a
revision.
+///
+/// Any component (server, broker, controller, minion) may advertise
capabilities. Each capability names the area of
+/// the feature in its own name (for example `MSE_` for the multi-stage
engine) and declares the instance type that
+/// advertises it. At startup an instance writes the map field `capabilities`
+/// (`CommonConstants.Helix.Instance.CAPABILITIES_KEY`) of its instance config
with
+/// `HelixHelper.updateCapabilities`: the key is the name of a capability of
its instance type and the value is its
+/// [#revision()] as a decimal integer, for example `{"MSE_FEATURE": "1"}`.
Another component reads the map,
+/// for example with [InstanceCapabilityTracker], to decide whether it can use
a feature that instances of an older
+/// version do not support. A missing map, a missing key or a malformed value
means revision 0: not supported.
+///
+/// The broker reads the capabilities of the servers from the instance configs
that its routing manager already reads,
+/// see `RoutingManager.getMinServerCapabilityRevision`. Other components can
compute the same minimum over their own
+/// set of instances with [InstanceCapabilityTracker].
+///
+/// The map also holds the reserved entry `pinotVersion`, the Pinot version
that wrote it. A reader ignores the map
+/// when that entry is not string-equal to the simple field `pinotVersion` of
the same instance config, so the
+/// capabilities of a version do not survive a rollback to a version that
predates them. See
+/// [InstanceCapabilityTracker].
+///
+/// The capabilities of this version are the constants of this class, listed
in [#values()]. Contract:
+/// - The revision of a capability only grows. Revision `n` implies support
for everything that revisions below `n`
+/// added. A change that old instances with the same capability cannot
handle increments the revision.
+/// - A revision is not a Pinot version. Nothing compares Pinot version
strings.
+/// - A new feature that old instances cannot handle adds a constant with
revision 1, and adds it to [#values()] in
+/// the same change as the code that supports the feature. An instance must
never advertise a feature it cannot run.
+/// - The names are persisted in ZooKeeper: never rename a capability, and
never use its name again for another
+/// feature.
+/// - A capability can retire after its compatibility window. First remove the
readers and their fallback code, then
+/// the advertisement. Remove a reader only when no supported version that
can run in the same cluster still needs
+/// the fallback. A completed rollout alone is not enough: a missing key
means revision 0, so an older reader that
+/// still checks the key falls back. The full map replacement at startup
removes a retired advertisement.
+///
+/// Extensions: a distribution or a plugin built on Pinot can define its own
capabilities with the public constructor.
+/// It passes them, together with [#values()], to
`HelixHelper.updateCapabilities` when the instance starts, so that
+/// one write advertises both. Their names must start with a prefix that is
unique to the extension, so that they never
+/// clash with a capability of Pinot. Readers need no change: they read every
capability that an instance advertises.
+///
+/// Two capabilities are equal when their names are equal. Instances are
immutable and thread-safe.
+///
+/// This class should be a `record`, but `pinot-common` compiles to Java 11
bytecode, and records need Java 16. Until
+/// that changes, it keeps the shape of a record and of an enum: the accessors
use the record style (`name()`,
+/// `instanceType()`, `revision()`) instead of getters, and [#values()] and
`name()` follow `Enum`.
+public final class InstanceCapability {
+ // Declare the constants above this field: it reads them when the class
initializes.
+ private static final List<InstanceCapability> VALUES =
checkUniqueNames(List.of());
+
+ private final String _name;
+ private final InstanceType _instanceType;
+ private final int _revision;
+
+ /// Creates a capability. Pinot declares its capabilities as constants of
this class. An extension declares its own,
+ /// see the class Javadoc.
+ public InstanceCapability(String name, InstanceType instanceType, int
revision) {
+ // Upper case keeps the name apart from the reserved entry pinotVersion of
the capabilities map.
+ Preconditions.checkArgument(name.matches("[A-Z][A-Z0-9_]*"), "Capability
name must be upper case: %s", name);
+ Preconditions.checkArgument(revision > 0, "Revision of capability %s must
be positive: %s", name, revision);
+ _name = name;
+ _instanceType = instanceType;
+ _revision = revision;
+ }
+
+ /// Every capability of this version.
+ public static List<InstanceCapability> values() {
+ return VALUES;
+ }
+
+ /// The name of the capability, the key in the `capabilities` map field.
+ public String name() {
+ return _name;
+ }
+
+ /// The type of the instances that advertise this capability.
+ public InstanceType instanceType() {
+ return _instanceType;
+ }
+
+ /// The revision of this capability that this version of Pinot supports.
Always positive.
+ public int revision() {
+ return _revision;
+ }
+
+ /// Every capability of [#values()] for the instance type with its revision,
as a new mutable map. Empty when the
+ /// instance type advertises no capability. `HelixHelper.updateCapabilities`
adds the reserved `pinotVersion` entry
+ /// and writes the result to the `capabilities` field.
+ public static Map<String, String> toMapField(InstanceType instanceType) {
+ return toMapField(VALUES, instanceType);
+ }
+
+ /// Same as [#toMapField(InstanceType)] over the given capabilities instead
of [#values()]. Fails when two
+ /// capabilities have the same name, of any instance type.
+ public static Map<String, String> toMapField(Collection<InstanceCapability>
capabilities, InstanceType instanceType) {
+ Set<String> names = new HashSet<>();
+ Map<String, String> mapField = new HashMap<>();
+ for (InstanceCapability capability : capabilities) {
+ Preconditions.checkState(names.add(capability._name), "Duplicate
capability name: %s", capability._name);
+ if (capability._instanceType == instanceType) {
+ mapField.put(capability._name, Integer.toString(capability._revision));
+ }
+ }
+ return mapField;
+ }
+
+ /// Fails when two capabilities have the same name. Equality is by name, so
a duplicate name is a definition error.
+ /// Returns the given list.
+ public static List<InstanceCapability>
checkUniqueNames(List<InstanceCapability> capabilities) {
+ Set<String> names = new HashSet<>();
+ for (InstanceCapability capability : capabilities) {
+ Preconditions.checkState(names.add(capability._name), "Duplicate
capability name: %s", capability._name);
+ }
+ return capabilities;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return this == o || (o instanceof InstanceCapability &&
_name.equals(((InstanceCapability) o)._name));
+ }
+
+ @Override
+ public int hashCode() {
+ return _name.hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return _name;
+ }
+}
diff --git
a/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/InstanceCapabilityTracker.java
b/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/InstanceCapabilityTracker.java
new file mode 100644
index 00000000000..96c086e6ce7
--- /dev/null
+++
b/pinot-common/src/main/java/org/apache/pinot/common/utils/helix/InstanceCapabilityTracker.java
@@ -0,0 +1,278 @@
+/**
+ * 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.pinot.common.utils.helix;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+import javax.annotation.Nullable;
+import org.apache.helix.zookeeper.datamodel.ZNRecord;
+import org.apache.pinot.spi.config.instance.InstanceType;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.InstanceTypeUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/// Computes, for each capability, the minimum revision across a set of
instances of one type, see
+/// [InstanceCapability].
+///
+/// The tracker does not read ZooKeeper and does not listen to Helix. Its
owner calls [#update] with the instance
+/// config records that it already reads, for example the broker routing
manager on each instance config change. Each
+/// call replaces the whole set: the tracker keeps the records of the tracked
type and ignores the others. The owner
+/// decides which instances count. A wider set is fail-safe: an instance that
never receives the work can only lower
+/// the minimum, and a lower minimum only keeps the plan that every version
can run.
+///
+/// Each instance advertises its capabilities in the map field `capabilities`
of its instance config
+/// ([CommonConstants.Helix.Instance#CAPABILITIES_KEY]). The tracker reads
every entry of the map, so it also tracks
+/// the capabilities that an extension defines (see [InstanceCapability]). A
missing map, a missing key or a malformed
+/// value counts as revision 0 (not supported). [#getMinRevision] returns 0
before the first [#update] and while the
+/// set has no instance of the tracked type.
+///
+/// When the owner cannot read a complete set, for example because the read
from ZooKeeper failed, it calls
+/// [#invalidate]. The previous set no longer proves anything: an instance can
restart under the same id on an older
+/// build. So [#getMinRevision] returns 0 until the next successful [#update].
+///
+/// Rollback guard: the map also holds the reserved entry `pinotVersion`
+/// ([CommonConstants.Helix.Instance#CAPABILITIES_PINOT_VERSION_KEY]), the
Pinot version that wrote the capabilities.
+/// The tracker reads the capabilities of an instance only when that entry is
string-equal to the simple field
+/// `pinotVersion` ([CommonConstants.Helix.Instance#PINOT_VERSION_KEY]) of the
same instance config. Otherwise it treats
+/// the instance as supporting no capability (revision 0). Every Pinot version
rewrites the simple field at startup,
+/// but a version that predates the capabilities does not clear the map. So
after a rollback to such a version the two
+/// values differ, and the stale capabilities are ignored. This is an equality
check between two fields of one instance
+/// config. It does not order versions, and it cannot detect a rollback
between two builds with the same version
+/// string. Residual gap: `PinotHelixResourceManager.updateInstance` reads the
instance config and writes the full
+/// record back without a version check. When an instance restarts on another
version between that read and that
+/// write, the write restores the previous simple field `pinotVersion` and the
previous map, so stale capabilities can
+/// be trusted. The simple field `pinotVersion` has the same problem today.
+///
+/// Logging: when the parsed capabilities of the set change, the tracker logs
at INFO the instances below the revision
+/// that this version supports, for the capabilities given to the constructor,
at most [#MAX_LOGGED_INSTANCES] per
+/// list. It lists separately the instances whose capabilities are ignored
because the version stamp does not match.
+/// It logs a malformed value at WARN when the capabilities of that instance
change. A call that changes nothing logs
+/// nothing.
+///
+/// Thread safety: [#update] is `synchronized`. It publishes an immutable
snapshot of the minimum revisions through a
+/// `volatile` field, so [#getMinRevision] never blocks and sees the result of
the last [#update].
+public class InstanceCapabilityTracker {
+ private static final Logger LOGGER =
LoggerFactory.getLogger(InstanceCapabilityTracker.class);
+ /// The maximum number of instance ids that the tracker logs for each list.
+ static final int MAX_LOGGED_INSTANCES = 20;
+ /// The revision stored for a malformed value. Counts as 0.
+ private static final int MALFORMED_REVISION = -1;
+
+ private final String _clusterName;
+ private final InstanceType _instanceType;
+ private final List<InstanceCapability> _loggedCapabilities;
+ // Guarded by this. For each tracked instance, the revision of each
capability that it advertises. Null before the
+ // first update and after invalidate(), so that the next update never takes
the unchanged-set early return.
+ @Nullable
+ private Map<String, Map<String, Integer>> _revisionsByInstance;
+ // Guarded by this. The instances whose capabilities are ignored because the
version stamp does not match.
+ private Set<String> _staleInstances = Set.of();
+
+ private volatile Map<String, Integer> _minRevisions = Map.of();
+
+ /// Tracks the instances of `instanceType` in the given cluster. Logs the
lagging instances for the capabilities of
+ /// [InstanceCapability#values()].
+ public InstanceCapabilityTracker(String clusterName, InstanceType
instanceType) {
+ this(clusterName, instanceType, InstanceCapability.values());
+ }
+
+ /// Same as [#InstanceCapabilityTracker(String, InstanceType)], but logs the
lagging instances for the given
+ /// capabilities, for example the capabilities of Pinot and those of an
extension. Every capability that the
+ /// instances advertise is tracked either way.
+ public InstanceCapabilityTracker(String clusterName, InstanceType
instanceType,
+ Collection<InstanceCapability> loggedCapabilities) {
+ _clusterName = clusterName;
+ _instanceType = instanceType;
+ List<InstanceCapability> capabilities = new ArrayList<>();
+ for (InstanceCapability capability : loggedCapabilities) {
+ if (capability.instanceType() == instanceType) {
+ capabilities.add(capability);
+ }
+ }
+ _loggedCapabilities = List.copyOf(capabilities);
+ }
+
+ /// The minimum revision of the capability across the tracked instances, 0
when one of them does not support it or
+ /// when there is no tracked instance. Never blocks.
+ public int getMinRevision(InstanceCapability capability) {
+ return _minRevisions.getOrDefault(capability.name(), 0);
+ }
+
+ /// Replaces the set of instances with the given instance config records.
Keeps the records of the tracked type and
+ /// ignores the others. Never throws because of the content of a record.
+ public synchronized void update(Collection<ZNRecord> instanceConfigRecords) {
+ Map<String, Map<String, Integer>> revisionsByInstance = new HashMap<>();
+ Set<String> staleInstances = new TreeSet<>();
+ for (ZNRecord record : instanceConfigRecords) {
+ String instanceId = record.getId();
+ if (InstanceTypeUtils.getInstanceType(instanceId) != _instanceType) {
+ continue;
+ }
+ if (hasStaleCapabilities(record)) {
+ staleInstances.add(instanceId);
+ }
+ Map<String, Integer> revisions = readRevisions(record);
+ revisionsByInstance.put(instanceId, revisions);
+ if (revisions.containsValue(MALFORMED_REVISION) && (_revisionsByInstance
== null || !revisions.equals(
+ _revisionsByInstance.get(instanceId)))) {
+ LOGGER.warn("Malformed capability revisions for instance: {} of
cluster: {}, treating them as 0: {}",
+ instanceId, _clusterName,
record.getMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY));
+ }
+ }
+ if (revisionsByInstance.equals(_revisionsByInstance) &&
staleInstances.equals(_staleInstances)) {
+ return;
+ }
+ _revisionsByInstance = revisionsByInstance;
+ _staleInstances = staleInstances;
+ Map<String, Integer> minRevisions =
computeMinRevisions(revisionsByInstance);
+ if (!minRevisions.equals(_minRevisions)) {
+ LOGGER.info("Minimum capability revisions across {} {} instances of
cluster: {} changed from {} to {}",
+ revisionsByInstance.size(), _instanceType, _clusterName,
_minRevisions, minRevisions);
+ _minRevisions = minRevisions;
+ }
+ logLaggingInstances();
+ }
+
+ /// Forgets the set of instances: [#getMinRevision] returns 0 for every
capability until the next [#update]. The
+ /// owner calls it when it cannot read a complete set of instance configs.
+ public synchronized void invalidate() {
+ _revisionsByInstance = null;
+ _staleInstances = Set.of();
+ if (!_minRevisions.isEmpty()) {
+ LOGGER.warn("Invalidating the capabilities of the {} instances of
cluster: {}, treating every capability as "
+ + "not supported until the next successful update. Previous minimum
revisions: {}", _instanceType,
+ _clusterName, _minRevisions);
+ _minRevisions = Map.of();
+ }
+ }
+
+ /// The sorted ids of the tracked instances whose capabilities are ignored
because the version stamp does not match.
+ @VisibleForTesting
+ synchronized List<String> getStaleInstances() {
+ return List.copyOf(_staleInstances);
+ }
+
+ /// For each capability that some instance advertises, the minimum revision
across all the instances. A capability
+ /// with minimum 0 has no entry.
+ private static Map<String, Integer> computeMinRevisions(Map<String,
Map<String, Integer>> revisionsByInstance) {
+ if (revisionsByInstance.isEmpty()) {
+ return Map.of();
+ }
+ Map<String, Integer> minRevisions = new HashMap<>();
+ // Every instance must advertise a capability, so the candidates are the
capabilities of any one instance.
+ for (String name :
revisionsByInstance.values().iterator().next().keySet()) {
+ int minRevision = Integer.MAX_VALUE;
+ for (Map<String, Integer> revisions : revisionsByInstance.values()) {
+ minRevision = Math.min(minRevision, revisions.getOrDefault(name, 0));
+ if (minRevision <= 0) {
+ break;
+ }
+ }
+ if (minRevision > 0) {
+ minRevisions.put(name, minRevision);
+ }
+ }
+ return Map.copyOf(minRevisions);
+ }
+
+ /// Logs at INFO, for each logged capability, the instances below the
revision that this version supports, in two
+ /// lists: the instances that advertise no or an older revision, and the
instances whose capabilities are ignored
+ /// because the version stamp does not match.
+ private void logLaggingInstances() {
+ if (_loggedCapabilities.isEmpty() || !LOGGER.isInfoEnabled()) {
+ return;
+ }
+ Map<String, Map<String, Integer>> sortedRevisions = new
TreeMap<>(_revisionsByInstance);
+ for (InstanceCapability capability : _loggedCapabilities) {
+ List<String> olderInstances = new ArrayList<>();
+ List<String> ignoredInstances = new ArrayList<>();
+ for (Map.Entry<String, Map<String, Integer>> entry :
sortedRevisions.entrySet()) {
+ if (entry.getValue().getOrDefault(capability.name(), 0) <
capability.revision()) {
+ (_staleInstances.contains(entry.getKey()) ? ignoredInstances :
olderInstances).add(entry.getKey());
+ }
+ }
+ if (olderInstances.isEmpty() && ignoredInstances.isEmpty()) {
+ continue;
+ }
+ LOGGER.info("{} {} instances of cluster: {} are below revision {} of
capability {}. With no or an older revision "
+ + "({}): {}. With capabilities ignored because of a version
stamp mismatch ({}): {}",
+ olderInstances.size() + ignoredInstances.size(), _instanceType,
_clusterName, capability.revision(),
+ capability, olderInstances.size(), truncate(olderInstances),
ignoredInstances.size(),
+ truncate(ignoredInstances));
+ }
+ }
+
+ private static String truncate(List<String> instances) {
+ if (instances.size() <= MAX_LOGGED_INSTANCES) {
+ return instances.toString();
+ }
+ return instances.subList(0, MAX_LOGGED_INSTANCES) + " ...";
+ }
+
+ /// Reads the revision of every capability that an instance advertises, by
name. Returns an empty map (revision 0
+ /// for every capability) when the instance config has no capabilities, or
when the capabilities were written by
+ /// another Pinot version than the one in the simple field `pinotVersion`.
See the rollback guard in the class
+ /// Javadoc. A malformed value is stored as [#MALFORMED_REVISION], which
counts as 0.
+ @VisibleForTesting
+ static Map<String, Integer> readRevisions(@Nullable ZNRecord record) {
+ if (record == null) {
+ return Map.of();
+ }
+ Map<String, String> mapField =
record.getMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY);
+ if (mapField == null || hasStaleCapabilities(record)) {
+ return Map.of();
+ }
+ Map<String, Integer> revisions = new HashMap<>();
+ for (Map.Entry<String, String> entry : mapField.entrySet()) {
+ String name = entry.getKey();
+ if
(name.equals(CommonConstants.Helix.Instance.CAPABILITIES_PINOT_VERSION_KEY)) {
+ continue;
+ }
+ int revision;
+ try {
+ revision = entry.getValue() != null ?
Integer.parseInt(entry.getValue().trim()) : MALFORMED_REVISION;
+ } catch (NumberFormatException e) {
+ revision = MALFORMED_REVISION;
+ }
+ revisions.put(name, revision < 0 ? MALFORMED_REVISION : revision);
+ }
+ return revisions;
+ }
+
+ /// Whether the instance config has a capabilities map that was not written
by the Pinot version in its simple field
+ /// `pinotVersion`: the version stamp is missing or not string-equal. Not an
ordering of versions.
+ private static boolean hasStaleCapabilities(ZNRecord record) {
+ Map<String, String> mapField =
record.getMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY);
+ if (mapField == null) {
+ return false;
+ }
+ String writtenByVersion =
mapField.get(CommonConstants.Helix.Instance.CAPABILITIES_PINOT_VERSION_KEY);
+ return writtenByVersion == null
+ ||
!writtenByVersion.equals(record.getSimpleField(CommonConstants.Helix.Instance.PINOT_VERSION_KEY));
+ }
+}
diff --git
a/pinot-common/src/test/java/org/apache/pinot/common/utils/helix/HelixHelperTest.java
b/pinot-common/src/test/java/org/apache/pinot/common/utils/helix/HelixHelperTest.java
index da248b03ece..6d68c2e046e 100644
---
a/pinot-common/src/test/java/org/apache/pinot/common/utils/helix/HelixHelperTest.java
+++
b/pinot-common/src/test/java/org/apache/pinot/common/utils/helix/HelixHelperTest.java
@@ -40,6 +40,8 @@ import org.apache.helix.model.InstanceConfig;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer;
import org.apache.helix.zookeeper.util.GZipCompressionUtil;
+import org.apache.pinot.common.version.PinotVersion;
+import org.apache.pinot.spi.config.instance.InstanceType;
import org.apache.pinot.spi.utils.CommonConstants;
import org.apache.pinot.spi.utils.JsonUtils;
import org.testng.annotations.Test;
@@ -304,4 +306,66 @@ public class HelixHelperTest {
return mapper;
}
}
+
+ @Test
+ public void testUpdateCapabilities() {
+ InstanceCapability serverCapability = new
InstanceCapability("TEST_SERVER_CAPABILITY", InstanceType.SERVER, 2);
+ InstanceCapability brokerCapability = new
InstanceCapability("TEST_BROKER_CAPABILITY", InstanceType.BROKER, 1);
+ List<InstanceCapability> capabilities = List.of(serverCapability,
brokerCapability);
+ InstanceConfig instanceConfig = new
InstanceConfig("Server_localhost_1234");
+ // One call also writes the simple field pinotVersion.
+ assertTrue(HelixHelper.updateCapabilities(instanceConfig,
InstanceType.SERVER, capabilities));
+ // Only the capabilities of the instance type, and the version stamp.
+ Map<String, String> expected = Map.of("TEST_SERVER_CAPABILITY", "2",
+ CommonConstants.Helix.Instance.CAPABILITIES_PINOT_VERSION_KEY,
PinotVersion.VERSION);
+ Map<String, String> mapField =
+
instanceConfig.getRecord().getMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY);
+ assertEquals(mapField, expected);
+ // The stamp is the version in the simple field pinotVersion, so a reader
uses the capabilities.
+
assertEquals(mapField.get(CommonConstants.Helix.Instance.CAPABILITIES_PINOT_VERSION_KEY),
+
instanceConfig.getRecord().getSimpleField(CommonConstants.Helix.Instance.PINOT_VERSION_KEY));
+
assertEquals(InstanceCapabilityTracker.readRevisions(instanceConfig.getRecord()),
+ Map.of("TEST_SERVER_CAPABILITY", 2));
+ // Writing the same capabilities again does not change the instance config.
+ assertFalse(HelixHelper.updateCapabilities(instanceConfig,
InstanceType.SERVER, capabilities));
+
+ // An older revision is replaced by the current one.
+
instanceConfig.getRecord().setMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY,
+ Map.of("TEST_SERVER_CAPABILITY", "1",
CommonConstants.Helix.Instance.CAPABILITIES_PINOT_VERSION_KEY,
+ PinotVersion.VERSION));
+ assertTrue(HelixHelper.updateCapabilities(instanceConfig,
InstanceType.SERVER, capabilities));
+
assertEquals(instanceConfig.getRecord().getMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY),
expected);
+
+ // Capabilities written by another version get the stamp of this version.
+
instanceConfig.getRecord().setMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY,
+ Map.of("TEST_SERVER_CAPABILITY", "2",
CommonConstants.Helix.Instance.CAPABILITIES_PINOT_VERSION_KEY, "0.0.1"));
+ assertTrue(HelixHelper.updateCapabilities(instanceConfig,
InstanceType.SERVER, capabilities));
+
assertEquals(instanceConfig.getRecord().getMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY),
expected);
+
+ // Without capabilities for the instance type, the map holds only the
version stamp.
+ InstanceConfig minionConfig = new InstanceConfig("Minion_localhost_1234");
+ assertTrue(HelixHelper.updateCapabilities(minionConfig,
InstanceType.MINION, capabilities));
+
assertEquals(minionConfig.getRecord().getMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY),
+ Map.of(CommonConstants.Helix.Instance.CAPABILITIES_PINOT_VERSION_KEY,
PinotVersion.VERSION));
+
+ // Two capabilities with the same name are a definition error.
+ List<InstanceCapability> duplicates =
+ List.of(serverCapability, new
InstanceCapability("TEST_SERVER_CAPABILITY", InstanceType.SERVER, 3));
+ assertThrows(IllegalStateException.class,
+ () -> HelixHelper.updateCapabilities(instanceConfig,
InstanceType.SERVER, duplicates));
+ // Also across instance types, and before the instance config changes.
+ InstanceConfig newConfig = new InstanceConfig("Server_localhost_5678");
+ List<InstanceCapability> crossTypeDuplicates =
+ List.of(serverCapability, new
InstanceCapability("TEST_SERVER_CAPABILITY", InstanceType.BROKER, 1));
+ assertThrows(IllegalStateException.class,
+ () -> HelixHelper.updateCapabilities(newConfig, InstanceType.SERVER,
crossTypeDuplicates));
+
assertNull(newConfig.getRecord().getSimpleField(CommonConstants.Helix.Instance.PINOT_VERSION_KEY));
+
assertNull(newConfig.getRecord().getMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY));
+
+ // The simple field pinotVersion of another version is replaced, so the
stamp matches it.
+
instanceConfig.getRecord().setSimpleField(CommonConstants.Helix.Instance.PINOT_VERSION_KEY,
"0.0.1");
+ assertTrue(HelixHelper.updateCapabilities(instanceConfig,
InstanceType.SERVER, capabilities));
+
assertEquals(instanceConfig.getRecord().getSimpleField(CommonConstants.Helix.Instance.PINOT_VERSION_KEY),
+ PinotVersion.VERSION);
+ }
}
diff --git
a/pinot-common/src/test/java/org/apache/pinot/common/utils/helix/InstanceCapabilityTest.java
b/pinot-common/src/test/java/org/apache/pinot/common/utils/helix/InstanceCapabilityTest.java
new file mode 100644
index 00000000000..36bd1864d70
--- /dev/null
+++
b/pinot-common/src/test/java/org/apache/pinot/common/utils/helix/InstanceCapabilityTest.java
@@ -0,0 +1,44 @@
+/**
+ * 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.pinot.common.utils.helix;
+
+import java.util.List;
+import org.apache.pinot.spi.config.instance.InstanceType;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertThrows;
+
+
+public class InstanceCapabilityTest {
+
+ @Test
+ public void testUniqueNamesPass() {
+ List<InstanceCapability> capabilities = List.of(new
InstanceCapability("FIRST", InstanceType.SERVER, 1),
+ new InstanceCapability("SECOND", InstanceType.BROKER, 1));
+ assertEquals(InstanceCapability.checkUniqueNames(capabilities),
capabilities);
+ }
+
+ @Test
+ public void testDuplicateNameFails() {
+ List<InstanceCapability> capabilities = List.of(new
InstanceCapability("SAME", InstanceType.SERVER, 1),
+ new InstanceCapability("SAME", InstanceType.BROKER, 2));
+ assertThrows(IllegalStateException.class, () ->
InstanceCapability.checkUniqueNames(capabilities));
+ }
+}
diff --git
a/pinot-common/src/test/java/org/apache/pinot/common/utils/helix/InstanceCapabilityTrackerTest.java
b/pinot-common/src/test/java/org/apache/pinot/common/utils/helix/InstanceCapabilityTrackerTest.java
new file mode 100644
index 00000000000..0833b2650db
--- /dev/null
+++
b/pinot-common/src/test/java/org/apache/pinot/common/utils/helix/InstanceCapabilityTrackerTest.java
@@ -0,0 +1,275 @@
+/**
+ * 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.pinot.common.utils.helix;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.annotation.Nullable;
+import org.apache.helix.zookeeper.datamodel.ZNRecord;
+import org.apache.pinot.spi.config.instance.InstanceType;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+
+
+public class InstanceCapabilityTrackerTest {
+ private static final String CLUSTER = "testCluster";
+ private static final String SERVER_1 = "Server_host1_8098";
+ private static final String SERVER_2 = "Server_host2_8098";
+ private static final String BROKER_1 = "Broker_host3_8099";
+ private static final String BROKER_2 = "Broker_host4_8099";
+ private static final String VERSION = "1.6.0";
+ private static final String OLD_VERSION = "1.5.0";
+ private static final String CAPABILITY_NAME = "TEST_CAPABILITY";
+ private static final InstanceCapability CAPABILITY =
+ new InstanceCapability(CAPABILITY_NAME, InstanceType.SERVER, 1);
+
+ private final Map<String, ZNRecord> _records = new HashMap<>();
+ private InstanceCapabilityTracker _tracker;
+
+ @BeforeMethod
+ public void setUp() {
+ _records.clear();
+ _tracker = new InstanceCapabilityTracker(CLUSTER, InstanceType.SERVER,
List.of(CAPABILITY));
+ }
+
+ @Test
+ public void testRevisionZeroBeforeUpdateAndWithoutServers() {
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+ putInstance(BROKER_1, Map.of(CAPABILITY_NAME, "1"));
+ update();
+ // Brokers are ignored, and a set without servers supports nothing.
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+ }
+
+ @Test
+ public void testAllServersAdvertiseTheCapability() {
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "1"));
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "1"));
+ // A broker without the capability does not count.
+ putInstance(BROKER_1, null);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 1);
+ }
+
+ @Test
+ public void testMissingMapOrKeyIsRevisionZero() {
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "1"));
+ putInstance(SERVER_2, null);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+
+ putInstance(SERVER_2, Map.of("SOME_FUTURE_CAPABILITY", "3"));
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+ }
+
+ @Test
+ public void testMixedRevisionsMinWins() {
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "3"));
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "2"));
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 2);
+ }
+
+ @Test
+ public void testMalformedRevisionIsZero() {
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "1"));
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "one"));
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "-1"));
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, " 1 "));
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 1);
+ }
+
+ @Test
+ public void testConfigChangeOfOneServer() {
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "1"));
+ putInstance(SERVER_2, null);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+
+ // The old server is upgraded and writes the capability.
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "1"));
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 1);
+
+ // The capability disappears from the instance config of a server.
+ putInstance(SERVER_1, null);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+ }
+
+ @Test
+ public void testServerAddedAndRemoved() {
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "1"));
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 1);
+
+ // A new server without the capability joins.
+ putInstance(SERVER_2, null);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+
+ // The server is removed.
+ _records.remove(SERVER_2);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 1);
+
+ // The last server is removed.
+ _records.remove(SERVER_1);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+ }
+
+ @Test
+ public void testExtensionCapabilityIsTracked() {
+ // The tracker reads every capability that the instances advertise, also
one it was not given.
+ InstanceCapability extensionCapability = new
InstanceCapability("VENDOR_CAPABILITY", InstanceType.SERVER, 1);
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "1", "VENDOR_CAPABILITY",
"2"));
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "1", "VENDOR_CAPABILITY",
"3"));
+ update();
+ assertEquals(_tracker.getMinRevision(extensionCapability), 2);
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 1);
+ }
+
+ @Test
+ public void testBrokerTracker() {
+ InstanceCapability brokerCapability = new
InstanceCapability("TEST_BROKER_CAPABILITY", InstanceType.BROKER, 1);
+ InstanceCapabilityTracker tracker =
+ new InstanceCapabilityTracker(CLUSTER, InstanceType.BROKER,
List.of(brokerCapability));
+ putInstance(BROKER_1, Map.of("TEST_BROKER_CAPABILITY", "1"));
+ putInstance(BROKER_2, Map.of("TEST_BROKER_CAPABILITY", "1"));
+ // A server without the capability does not count.
+ putInstance(SERVER_1, null);
+ tracker.update(_records.values());
+ assertEquals(tracker.getMinRevision(brokerCapability), 1);
+
+ // The owner decides which instances count: a set without BROKER_2 still
gives the minimum over BROKER_1.
+ putInstance(BROKER_2, null);
+ tracker.update(List.of(_records.get(BROKER_1)));
+ assertEquals(tracker.getMinRevision(brokerCapability), 1);
+ tracker.update(_records.values());
+ assertEquals(tracker.getMinRevision(brokerCapability), 0);
+ }
+
+ @Test
+ public void testInvalidateUntilTheNextUpdate() {
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "1"));
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "1"));
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 1);
+
+ _tracker.invalidate();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+ // The next update restores the minimum, also when the set is the same as
before the invalidation.
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 1);
+ }
+
+ @Test
+ public void testMatchingVersionStampGivesTheAdvertisedRevision() {
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "2"), VERSION, VERSION);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 2);
+ }
+
+ @Test
+ public void testRollbackIgnoresStaleCapabilities() {
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "1"));
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "1"));
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 1);
+
+ // SERVER_2 is rolled back to a version that predates the capabilities.
That version rewrites the simple field
+ // pinotVersion at startup but keeps the capabilities map, so the stamp no
longer matches.
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "1"), OLD_VERSION, VERSION);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+ assertEquals(_tracker.getStaleInstances(), List.of(SERVER_2));
+
+ // Not an ordering of versions: a newer version in the simple field does
not match either.
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "1"), "9.9.9", VERSION);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+
+ // The server is upgraded again and rewrites the capabilities with its
version.
+ putInstance(SERVER_2, Map.of(CAPABILITY_NAME, "1"));
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 1);
+ assertEquals(_tracker.getStaleInstances(), List.of());
+ }
+
+ @Test
+ public void testMissingVersionStampIsRevisionZero() {
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "1"), VERSION, null);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+
+ // The stamp without the simple field does not match either.
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "1"), null, VERSION);
+ update();
+ assertEquals(_tracker.getMinRevision(CAPABILITY), 0);
+ }
+
+ @Test
+ public void testReadRevisions() {
+ assertEquals(InstanceCapabilityTracker.readRevisions(null), Map.of());
+ putInstance(SERVER_1, Map.of(CAPABILITY_NAME, "2", "OTHER", "x"));
+ // The version stamp is not a capability, and a malformed value is stored
below 0.
+
assertEquals(InstanceCapabilityTracker.readRevisions(_records.get(SERVER_1)),
Map.of(CAPABILITY_NAME, 2, "OTHER",
+ -1));
+ }
+
+ private void update() {
+ _tracker.update(_records.values());
+ }
+
+ /// Puts an instance config whose capabilities were written by the Pinot
version that the instance runs.
+ private void putInstance(String instanceId, @Nullable Map<String, String>
capabilities) {
+ putInstance(instanceId, capabilities, VERSION, VERSION);
+ }
+
+ /// Puts an instance config with the given simple field `pinotVersion` and
the given `pinotVersion` entry of the
+ /// capabilities map. A null value leaves the field or the entry out.
+ private void putInstance(String instanceId, @Nullable Map<String, String>
capabilities,
+ @Nullable String instanceVersion, @Nullable String capabilitiesVersion) {
+ ZNRecord record = new ZNRecord(instanceId);
+ if (instanceVersion != null) {
+ record.setSimpleField(CommonConstants.Helix.Instance.PINOT_VERSION_KEY,
instanceVersion);
+ }
+ if (capabilities != null) {
+ Map<String, String> mapField = new HashMap<>(capabilities);
+ if (capabilitiesVersion != null) {
+
mapField.put(CommonConstants.Helix.Instance.CAPABILITIES_PINOT_VERSION_KEY,
capabilitiesVersion);
+ }
+ record.setMapField(CommonConstants.Helix.Instance.CAPABILITIES_KEY,
mapField);
+ }
+ _records.put(instanceId, record);
+ }
+}
diff --git
a/pinot-core/src/main/java/org/apache/pinot/core/routing/RoutingManager.java
b/pinot-core/src/main/java/org/apache/pinot/core/routing/RoutingManager.java
index f04bdde57bd..06728782147 100644
--- a/pinot-core/src/main/java/org/apache/pinot/core/routing/RoutingManager.java
+++ b/pinot-core/src/main/java/org/apache/pinot/core/routing/RoutingManager.java
@@ -23,6 +23,7 @@ import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.helix.InstanceCapability;
import org.apache.pinot.core.routing.timeboundary.TimeBoundaryInfo;
import org.apache.pinot.core.transport.ServerInstance;
import org.apache.pinot.spi.annotations.InterfaceAudience;
@@ -54,6 +55,15 @@ public interface RoutingManager {
return getEnabledServerInstanceMap();
}
+ /// Returns the minimum revision of the capability across the servers, see
[InstanceCapability]. 0 means that at least
+ /// one server does not support the capability. The minimum covers every
server with an instance config, including
+ /// the disabled ones, so it never overstates what a routable server
supports. Never blocks.
+ ///
+ /// The default implementation returns 0: no capability is supported.
+ default int getMinServerCapabilityRevision(InstanceCapability capability) {
+ return 0;
+ }
+
/// Returns whether the given table is enabled
/// @param tableNameWithType Table name with type
/// @return Whether the given table is enabled
diff --git
a/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/BaseServerStarter.java
b/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/BaseServerStarter.java
index 5c62d86d38b..7d4512ae4d4 100644
---
a/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/BaseServerStarter.java
+++
b/pinot-server/src/main/java/org/apache/pinot/server/starter/helix/BaseServerStarter.java
@@ -25,6 +25,7 @@ import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -44,7 +45,6 @@ import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
-import org.apache.helix.InstanceType;
import org.apache.helix.SystemPropertyKeys;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.model.ExternalView;
@@ -78,6 +78,7 @@ import
org.apache.pinot.common.utils.config.QueryWorkloadConfigUtils;
import org.apache.pinot.common.utils.config.TagNameUtils;
import org.apache.pinot.common.utils.fetcher.SegmentFetcherFactory;
import org.apache.pinot.common.utils.helix.HelixHelper;
+import org.apache.pinot.common.utils.helix.InstanceCapability;
import org.apache.pinot.common.utils.regex.PatternFactory;
import org.apache.pinot.common.utils.tls.PinotInsecureMode;
import org.apache.pinot.common.utils.tls.RenewableTlsUtils;
@@ -124,6 +125,7 @@ import org.apache.pinot.spi.accounting.ThreadAccountant;
import org.apache.pinot.spi.accounting.ThreadAccountantUtils;
import org.apache.pinot.spi.accounting.ThreadResourceUsageProvider;
import org.apache.pinot.spi.accounting.WorkloadBudgetManagerFactory;
+import org.apache.pinot.spi.config.instance.InstanceType;
import org.apache.pinot.spi.config.provider.PinotClusterConfigChangeListener;
import org.apache.pinot.spi.crypt.PinotCrypterFactory;
import org.apache.pinot.spi.env.PinotConfiguration;
@@ -296,8 +298,8 @@ public abstract class BaseServerStarter implements
ServiceStartable {
LOGGER.info("Initializing Helix manager with zkAddress: {}, clusterName:
{}, instanceId: {}", _zkAddress,
_helixClusterName, _instanceId);
- _helixManager =
- HelixManagerFactory.getZKHelixManager(_helixClusterName, _instanceId,
InstanceType.PARTICIPANT, _zkAddress);
+ _helixManager = HelixManagerFactory.getZKHelixManager(_helixClusterName,
_instanceId,
+ org.apache.helix.InstanceType.PARTICIPANT, _zkAddress);
_clusterConfigChangeHandler.registerClusterConfigChangeListener(ContinuousJfrStarter.INSTANCE);
initTransitionThreadPoolManager();
@@ -481,6 +483,12 @@ public abstract class BaseServerStarter implements
ServiceStartable {
return consumingSegments;
}
+ /// The capabilities that this server advertises in its instance config at
startup, see [InstanceCapability]. A
+ /// distribution or a plugin built on Pinot overrides it to add its own
capabilities to [InstanceCapability#values()].
+ protected Collection<InstanceCapability> getInstanceCapabilities() {
+ return InstanceCapability.values();
+ }
+
private void updateInstanceConfigIfNeeded(ServerConf serverConf) {
InstanceConfig instanceConfig =
HelixHelper.getInstanceConfig(_helixManager, _instanceId);
@@ -530,7 +538,8 @@ public abstract class BaseServerStarter implements
ServiceStartable {
updated |= updatePortIfNeeded(simpleFields,
Instance.MULTI_STAGE_QUERY_ENGINE_MAILBOX_PORT_KEY,
serverConf.getMultiStageMailboxPort());
}
- updated |= HelixHelper.updatePinotVersion(instanceConfig);
+ // Also writes the simple field pinotVersion.
+ updated |= HelixHelper.updateCapabilities(instanceConfig,
InstanceType.SERVER, getInstanceCapabilities());
// Update environment properties
if (_pinotEnvironmentProvider != null) {
@@ -770,11 +779,10 @@ public abstract class BaseServerStarter implements
ServiceStartable {
Server.DEFAULT_THREAD_ALLOCATED_BYTES_MEASUREMENT));
// Initialize workload budget manager and thread accountant. Workload
budget manager must be initialized first
// because it might be used by the accountant.
- PinotConfiguration accountingConfig =
ThreadAccountantUtils.extractAccountingConfig(_serverConf,
- org.apache.pinot.spi.config.instance.InstanceType.SERVER);
+ PinotConfiguration accountingConfig =
+ ThreadAccountantUtils.extractAccountingConfig(_serverConf,
InstanceType.SERVER);
WorkloadBudgetManagerFactory.register(accountingConfig);
- _threadAccountant =
ThreadAccountantUtils.createAccountant(accountingConfig, _instanceId,
- org.apache.pinot.spi.config.instance.InstanceType.SERVER);
+ _threadAccountant =
ThreadAccountantUtils.createAccountant(accountingConfig, _instanceId,
InstanceType.SERVER);
// Initialize scan-based query killing
PinotConfiguration schedulerConfig =
_serverConf.subset(CommonConstants.PINOT_QUERY_SCHEDULER_PREFIX);
diff --git
a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
index b8701d878d0..71eb450b72e 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/utils/CommonConstants.java
@@ -216,6 +216,17 @@ public class CommonConstants {
public static final String SYSTEM_RESOURCE_INFO_KEY =
"SYSTEM_RESOURCE_INFO";
public static final String PINOT_VERSION_KEY = "pinotVersion";
+ /// The map field with the features that an instance supports: the key
is the capability name and the value is
+ /// its revision, an integer that only grows. Any instance type may
write it at startup. Other components read
+ /// it to decide whether they can use a feature that instances of an
older version do not support. A missing
+ /// map or key means revision 0: not supported. See `InstanceCapability`
in pinot-common.
+ public static final String CAPABILITIES_KEY = "capabilities";
+ /// The reserved entry of the [#CAPABILITIES_KEY] map with the Pinot
version that wrote the map. A reader uses the
+ /// capabilities only when this entry is string-equal to the simple
field [#PINOT_VERSION_KEY] of the same
+ /// instance config. A version that predates the capabilities rewrites
[#PINOT_VERSION_KEY] at startup but keeps
+ /// the map, so after a rollback the two values differ and the stale map
is ignored. Capability names are upper
+ /// case, so they never clash with this key.
+ public static final String CAPABILITIES_PINOT_VERSION_KEY =
PINOT_VERSION_KEY;
}
public static final String SET_INSTANCE_ID_TO_HOSTNAME_KEY =
"pinot.set.instance.id.to.hostname";
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]