pinot-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From GitBox <...@apache.org>
Subject [GitHub] [incubator-pinot] Jackie-Jiang commented on a change in pull request #5046: Re-design the broker routing
Date Thu, 06 Feb 2020 18:48:51 GMT
Jackie-Jiang commented on a change in pull request #5046: Re-design the broker routing
URL: https://github.com/apache/incubator-pinot/pull/5046#discussion_r376016642
 
 

 ##########
 File path: pinot-broker/src/main/java/org/apache/pinot/broker/routing/v2/RoutingManager.java
 ##########
 @@ -0,0 +1,481 @@
+/**
+ * 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.broker.routing.v2;
+
+import com.google.common.base.Preconditions;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.BaseDataAccessor;
+import org.apache.helix.HelixConstants;
+import org.apache.helix.HelixDataAccessor;
+import org.apache.helix.HelixManager;
+import org.apache.helix.ZNRecord;
+import org.apache.helix.model.ExternalView;
+import org.apache.helix.model.InstanceConfig;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.pinot.broker.broker.helix.ClusterChangeHandler;
+import org.apache.pinot.broker.routing.v2.instanceselector.InstanceSelector;
+import org.apache.pinot.broker.routing.v2.instanceselector.InstanceSelectorFactory;
+import org.apache.pinot.broker.routing.v2.segmentpruner.SegmentPruner;
+import org.apache.pinot.broker.routing.v2.segmentpruner.SegmentPrunerFactory;
+import org.apache.pinot.broker.routing.v2.segmentselector.SegmentSelector;
+import org.apache.pinot.broker.routing.v2.segmentselector.SegmentSelectorFactory;
+import org.apache.pinot.broker.routing.v2.timeboundary.TimeBoundaryInfo;
+import org.apache.pinot.broker.routing.v2.timeboundary.TimeBoundaryManager;
+import org.apache.pinot.common.config.TableConfig;
+import org.apache.pinot.common.config.TableNameBuilder;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.metrics.BrokerMeter;
+import org.apache.pinot.common.metrics.BrokerMetrics;
+import org.apache.pinot.common.request.BrokerRequest;
+import org.apache.pinot.common.utils.CommonConstants;
+import org.apache.pinot.common.utils.CommonConstants.Helix.StateModel.RealtimeSegmentOnlineOfflineStateModel;
+import org.apache.pinot.common.utils.HashUtil;
+import org.apache.pinot.core.transport.ServerInstance;
+import org.apache.zookeeper.data.Stat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * The {@code RoutingManager} manages the routing of all tables hosted by the broker instance.
+ */
+public class RoutingManager implements ClusterChangeHandler {
+  private static final Logger LOGGER = LoggerFactory.getLogger(RoutingManager.class);
+
+  private final BrokerMetrics _brokerMetrics;
+  private final Map<String, RoutingEntry> _routingEntryMap = new ConcurrentHashMap<>();
+  private final Map<String, ServerInstance> _enabledServerInstanceMap = new ConcurrentHashMap<>();
+
+  private BaseDataAccessor<ZNRecord> _zkDataAccessor;
+  private String _externalViewPathPrefix;
+  private String _idealStatePathPrefix;
+  private String _instanceConfigsPath;
+  private ZkHelixPropertyStore<ZNRecord> _propertyStore;
+
+  public RoutingManager(BrokerMetrics brokerMetrics) {
+    _brokerMetrics = brokerMetrics;
+  }
+
+  @Override
+  public void init(HelixManager helixManager) {
+    HelixDataAccessor helixDataAccessor = helixManager.getHelixDataAccessor();
+    _zkDataAccessor = helixDataAccessor.getBaseDataAccessor();
+    _externalViewPathPrefix = helixDataAccessor.keyBuilder().externalViews().getPath() +
"/";
+    _idealStatePathPrefix = helixDataAccessor.keyBuilder().idealStates().getPath() + "/";
+    _instanceConfigsPath = helixDataAccessor.keyBuilder().instanceConfigs().getPath();
+    _propertyStore = helixManager.getHelixPropertyStore();
+  }
+
+  @Override
+  public synchronized void processClusterChange(HelixConstants.ChangeType changeType) {
+    Preconditions.checkState(changeType == HelixConstants.ChangeType.EXTERNAL_VIEW
+        || changeType == HelixConstants.ChangeType.INSTANCE_CONFIG, "Illegal change type:
" + changeType);
+    if (changeType == HelixConstants.ChangeType.EXTERNAL_VIEW) {
+      processExternalViewChange();
+    } else {
+      processInstanceConfigChange();
+    }
+  }
+
+  private void processExternalViewChange() {
+    LOGGER.info("Processing external view change");
+    long startTimeMs = System.currentTimeMillis();
+
+    int numTables = _routingEntryMap.size();
+    if (numTables == 0) {
+      LOGGER.info("No table exists in the routing, skipping processing external view change");
+      return;
+    }
+
+    List<RoutingEntry> routingEntries = new ArrayList<>(numTables);
+    List<String> externalViewPaths = new ArrayList<>(numTables);
+    for (Map.Entry<String, RoutingEntry> entry : _routingEntryMap.entrySet()) {
+      String tableNameWithType = entry.getKey();
+      routingEntries.add(entry.getValue());
+      externalViewPaths.add(_externalViewPathPrefix + tableNameWithType);
+    }
+    Stat[] stats = _zkDataAccessor.getStats(externalViewPaths, AccessOption.PERSISTENT);
+    long fetchStatsEndTimeMs = System.currentTimeMillis();
+
+    int numRoutingEntriesToUpdate = 0;
+    for (int i = 0; i < numTables; i++) {
+      Stat stat = stats[i];
+      if (stat != null) {
+        RoutingEntry routingEntry = routingEntries.get(i);
+        if (stat.getVersion() != routingEntry.getLastUpdateExternalViewVersion()) {
+          numRoutingEntriesToUpdate++;
+          try {
+            updateRoutingEntryOnExternalViewChange(routingEntry);
+          } catch (Exception e) {
+            LOGGER
+                .error("Caught unexpected exception while updating routing entry on external
view change for table: {}",
+                    routingEntry.getTableNameWithType(), e);
+          }
+        }
+      }
+    }
+    long updateRoutingEntriesEndTimeMs = System.currentTimeMillis();
+
+    LOGGER.info(
+        "Processed external view change in {}ms (fetch {} external view stats: {}ms, update
{} routing entries: {}ms)",
+        updateRoutingEntriesEndTimeMs - startTimeMs, numTables, fetchStatsEndTimeMs - startTimeMs,
+        numRoutingEntriesToUpdate, updateRoutingEntriesEndTimeMs - fetchStatsEndTimeMs);
+  }
+
+  private void updateRoutingEntryOnExternalViewChange(RoutingEntry routingEntry) {
+    String tableNameWithType = routingEntry.getTableNameWithType();
+    ExternalView externalView = getExternalView(tableNameWithType);
+    if (externalView == null) {
+      LOGGER.warn("Failed to find external view for table: {}, skipping updating routing
entry", tableNameWithType);
+      return;
+    }
+    Set<String> onlineSegments = getOnlineSegments(tableNameWithType);
+    if (onlineSegments == null) {
+      LOGGER.warn("Failed to find ideal state for table: {}, skipping updating routing entry",
tableNameWithType);
+      return;
+    }
+    routingEntry.onExternalViewChange(externalView, onlineSegments);
+  }
+
+  @Nullable
+  private ExternalView getExternalView(String tableNameWithType) {
+    Stat stat = new Stat();
+    ZNRecord znRecord = _zkDataAccessor.get(_externalViewPathPrefix + tableNameWithType,
stat, AccessOption.PERSISTENT);
+    if (znRecord != null) {
+      znRecord.setVersion(stat.getVersion());
+      return new ExternalView(znRecord);
+    } else {
+      return null;
+    }
+  }
+
+  @Nullable
+  private Set<String> getOnlineSegments(String tableNameWithType) {
+    ZNRecord znRecord = _zkDataAccessor.get(_idealStatePathPrefix + tableNameWithType, null,
AccessOption.PERSISTENT);
+    if (znRecord != null) {
+      Map<String, Map<String, String>> segmentAssignment = znRecord.getMapFields();
+      Set<String> onlineSegments = new HashSet<>(HashUtil.getHashMapCapacity(segmentAssignment.size()));
+      for (Map.Entry<String, Map<String, String>> entry : segmentAssignment.entrySet())
{
+        Map<String, String> instanceStateMap = entry.getValue();
+        if (instanceStateMap.containsValue(RealtimeSegmentOnlineOfflineStateModel.ONLINE)
|| instanceStateMap
+            .containsValue(RealtimeSegmentOnlineOfflineStateModel.CONSUMING)) {
+          onlineSegments.add(entry.getKey());
+        }
+      }
+      return onlineSegments;
+    } else {
+      return null;
+    }
+  }
+
+  private void processInstanceConfigChange() {
+    LOGGER.info("Processing instance config change");
+    long startTimeMs = System.currentTimeMillis();
+
+    List<ZNRecord> instanceConfigZNRecords =
+        _zkDataAccessor.getChildren(_instanceConfigsPath, null, AccessOption.PERSISTENT);
+    long fetchInstanceConfigsEndTimeMs = System.currentTimeMillis();
+
+    // Calculate new enabled and disabled instances
+    Set<String> enabledInstances = new HashSet<>();
+    List<String> newEnabledInstances = new ArrayList<>();
+    for (ZNRecord instanceConfigZNRecord : instanceConfigZNRecords) {
+      String instance = instanceConfigZNRecord.getId();
+      if (isInstanceEnabled(instanceConfigZNRecord)) {
+        enabledInstances.add(instance);
+
+        // Always refresh the server instance with the latest instance config in case it
changes
+        ServerInstance serverInstance = new ServerInstance(new InstanceConfig(instanceConfigZNRecord));
+        if (_enabledServerInstanceMap.put(instance, serverInstance) == null) {
+          newEnabledInstances.add(instance);
+        }
+      }
+    }
+    List<String> newDisabledInstances = new ArrayList<>();
+    for (String instance : _enabledServerInstanceMap.keySet()) {
+      if (!enabledInstances.contains(instance)) {
+        newDisabledInstances.add(instance);
+      }
+    }
+    List<String> changedInstances = new ArrayList<>(newEnabledInstances.size()
+ newDisabledInstances.size());
+    changedInstances.addAll(newEnabledInstances);
+    changedInstances.addAll(newDisabledInstances);
+    long calculateChangedInstancesEndTimeMs = System.currentTimeMillis();
+
+    // Update routing entry for all tables
+    for (RoutingEntry routingEntry : _routingEntryMap.values()) {
+      try {
+        routingEntry.onInstancesChange(enabledInstances, changedInstances);
+      } catch (Exception e) {
+        LOGGER.error("Caught unexpected exception while updating routing entry on instances
change for table: {}",
+            routingEntry.getTableNameWithType(), e);
+      }
+    }
+    long updateRoutingEntriesEndTimeMs = System.currentTimeMillis();
+
+    // Remove new disabled instances from _enabledServerInstanceMap after updating all routing
entries to ensure it
+    // always contains the selected instances
+    _enabledServerInstanceMap.keySet().removeAll(newDisabledInstances);
+
+    LOGGER.info(
+        "Processed instance config change in {}ms (fetch {} instance configs: {}ms, calculate
changed instances: {}ms, update {} routing entries: {}ms), new enabled instances: {}, new
disabled instances: {}",
+        updateRoutingEntriesEndTimeMs - startTimeMs, instanceConfigZNRecords.size(),
+        fetchInstanceConfigsEndTimeMs - startTimeMs, calculateChangedInstancesEndTimeMs -
fetchInstanceConfigsEndTimeMs,
+        _routingEntryMap.size(), updateRoutingEntriesEndTimeMs - calculateChangedInstancesEndTimeMs,
+        newEnabledInstances, newDisabledInstances);
+  }
+
+  private static boolean isInstanceEnabled(ZNRecord instanceConfigZNRecord) {
+    if ("false"
+        .equals(instanceConfigZNRecord.getSimpleField(InstanceConfig.InstanceConfigProperty.HELIX_ENABLED.name())))
{
+      return false;
+    }
+    if ("true".equals(instanceConfigZNRecord.getSimpleField(CommonConstants.Helix.IS_SHUTDOWN_IN_PROGRESS)))
{
+      return false;
+    }
+    if ("true".equals(instanceConfigZNRecord.getSimpleField(CommonConstants.Helix.QUERIES_DISABLED)))
{
+      return false;
+    }
+    return true;
+  }
+
+  /**
+   * Builds/rebuilds the routing for the given table.
+   */
+  public synchronized void buildRouting(String tableNameWithType) {
+    LOGGER.info("Building routing for table: {}", tableNameWithType);
+
+    TableConfig tableConfig = ZKMetadataProvider.getTableConfig(_propertyStore, tableNameWithType);
+    Preconditions.checkState(tableConfig != null, "Failed to find table config for table:
{}", tableNameWithType);
+    ExternalView externalView = getExternalView(tableNameWithType);
+    Preconditions.checkState(externalView != null, "Failed to find external view for table:
{}", tableNameWithType);
+    Set<String> onlineSegments = getOnlineSegments(tableNameWithType);
+    Preconditions.checkState(onlineSegments != null, "Failed to find ideal state for table:
{}", tableNameWithType);
+    Set<String> enabledInstances = _enabledServerInstanceMap.keySet();
+
+    SegmentSelector segmentSelector = SegmentSelectorFactory.getSegmentSelector(tableConfig);
+    segmentSelector.init(externalView, onlineSegments);
+    SegmentPruner segmentPruner = SegmentPrunerFactory.getSegmentPruner(tableConfig, _propertyStore);
+    segmentPruner.init(externalView, onlineSegments);
+    InstanceSelector instanceSelector = InstanceSelectorFactory.getInstanceSelector(tableConfig,
_brokerMetrics);
+    instanceSelector.init(enabledInstances, externalView, onlineSegments);
+    int externalViewVersion = externalView.getRecord().getVersion();
+
+    // Add time boundary manager if both offline and real-time part exist for a hybrid table
+    TimeBoundaryManager timeBoundaryManager = null;
+    String rawTableName = TableNameBuilder.extractRawTableName(tableNameWithType);
+    if (TableNameBuilder.isOfflineTableResource(tableNameWithType)) {
+      // Current table is offline
+      String realtimeTableName = TableNameBuilder.REALTIME.tableNameWithType(rawTableName);
+      if (_routingEntryMap.containsKey(realtimeTableName)) {
+        LOGGER.info("Adding time boundary manager for table: {}", tableNameWithType);
+        timeBoundaryManager = new TimeBoundaryManager(tableConfig, _propertyStore);
+        timeBoundaryManager.init(externalView, onlineSegments);
+      }
+    } else {
+      // Current table is real-time
+      String offlineTableName = TableNameBuilder.OFFLINE.tableNameWithType(rawTableName);
+      RoutingEntry offlineTableRoutingEntry = _routingEntryMap.get(offlineTableName);
+      if (offlineTableRoutingEntry != null && offlineTableRoutingEntry.getTimeBoundaryManager()
== null) {
+        LOGGER.info("Adding time boundary manager for table: {}", offlineTableName);
+
+        // NOTE: Add time boundary manager to the offline part before adding the routing
for the real-time part to
+        // ensure no overlapping data getting queried
+        TableConfig offlineTableConfig = ZKMetadataProvider.getTableConfig(_propertyStore,
offlineTableName);
+        Preconditions
+            .checkState(offlineTableConfig != null, "Failed to find table config for table:
{}", offlineTableName);
+        ExternalView offlineTableExternalView = getExternalView(offlineTableName);
+        Preconditions.checkState(offlineTableExternalView != null, "Failed to find external
view for table: {}",
+            offlineTableName);
+        Set<String> offlineTableOnlineSegments = getOnlineSegments(offlineTableName);
+        Preconditions.checkState(offlineTableOnlineSegments != null, "Failed to find ideal
state for table: {}",
+            offlineTableName);
+        TimeBoundaryManager offlineTableTimeBoundaryManager =
+            new TimeBoundaryManager(offlineTableConfig, _propertyStore);
+        offlineTableTimeBoundaryManager.init(offlineTableExternalView, offlineTableOnlineSegments);
+        offlineTableRoutingEntry.setTimeBoundaryManager(offlineTableTimeBoundaryManager);
+      }
+    }
+
+    RoutingEntry routingEntry =
+        new RoutingEntry(tableNameWithType, segmentSelector, segmentPruner, instanceSelector,
externalViewVersion,
+            timeBoundaryManager);
+    if (_routingEntryMap.put(tableNameWithType, routingEntry) == null) {
+      LOGGER.info("Built routing for table: {}", tableNameWithType);
+    } else {
+      LOGGER.info("Rebuilt routing for table: {}", tableNameWithType);
+    }
+  }
+
+  /**
+   * Removes the routing for the given table.
+   */
+  public synchronized void removeRouting(String tableNameWithType) {
+    LOGGER.info("Removing routing for table: {}", tableNameWithType);
+    if (_routingEntryMap.remove(tableNameWithType) != null) {
+      LOGGER.info("Removed routing for table: {}", tableNameWithType);
+
+      // Remove time boundary manager for the offline part routing if the removed routing
is the real-time part of a
+      // hybrid table
+      if (TableNameBuilder.isRealtimeTableResource(tableNameWithType)) {
+        String offlineTableName =
+            TableNameBuilder.OFFLINE.tableNameWithType(TableNameBuilder.extractRawTableName(tableNameWithType));
+        RoutingEntry routingEntry = _routingEntryMap.get(offlineTableName);
+        if (routingEntry != null) {
+          routingEntry.setTimeBoundaryManager(null);
+          LOGGER.info("Removed time boundary manager for table: {}", offlineTableName);
+        }
+      }
+    } else {
+      LOGGER.warn("Routing does not exist for table: {}, skipping removing routing", tableNameWithType);
+    }
+  }
+
+  /**
+   * Refreshes the metadata for the given segment (called when segment is getting refreshed).
+   */
+  public synchronized void refreshSegment(String tableNameWithType, String segment) {
+    LOGGER.info("Refreshing segment: {} for table: {}", segment, tableNameWithType);
+    RoutingEntry routingEntry = _routingEntryMap.get(tableNameWithType);
+    if (routingEntry != null) {
+      routingEntry.refreshSegment(segment);
+      LOGGER.info("Refreshed segment: {} for table: {}", segment, tableNameWithType);
+    } else {
+      LOGGER.warn("Routing does not exist for table: {}, skipping refreshing segment", tableNameWithType);
+    }
+  }
+
+  /**
+   * Returns {@code true} if the routing exists for the given table.
+   */
+  public boolean routingExists(String tableNameWithType) {
+    return _routingEntryMap.containsKey(tableNameWithType);
+  }
+
+  /**
+   * Returns the routing table (map from server instance to list of segments hosted by the
server) based on the broker
+   * request.
+   * <p>NOTE: The broker request should already have the table suffix (_OFFLINE or
_REALTIME) appended.
+   */
+  public Map<ServerInstance, List<String>> getRoutingTable(BrokerRequest brokerRequest)
{
+    String tableNameWithType = brokerRequest.getQuerySource().getTableName();
+    RoutingEntry routingEntry = _routingEntryMap.get(tableNameWithType);
+    Preconditions.checkState(routingEntry != null, "Failed to find routing for table: %s",
tableNameWithType);
+
+    Map<String, String> segmentToInstanceMap = routingEntry.calculateSegmentToInstanceMap(brokerRequest);
+    Map<ServerInstance, List<String>> routingTable = new HashMap<>();
+    for (Map.Entry<String, String> entry : segmentToInstanceMap.entrySet()) {
+      ServerInstance serverInstance = _enabledServerInstanceMap.get(entry.getValue());
+      if (serverInstance != null) {
+        routingTable.computeIfAbsent(serverInstance, k -> new ArrayList<>()).add(entry.getKey());
+      } else {
+        // Should not happen in normal case unless encountered unexpected exception when
updating routing entries
+        _brokerMetrics.addMeteredTableValue(tableNameWithType, BrokerMeter.SERVER_MISSING_FOR_ROUTING,
1L);
+      }
+    }
+    return routingTable;
+  }
+
+  /**
+   * Returns the time boundary info for the given offline table name.
+   * <p>NOTE: Time boundary info is only available for the offline part of the hybrid
table.
+   */
+  @Nullable
+  public TimeBoundaryInfo getTimeBoundaryInfo(String offlineTableName) {
+    RoutingEntry routingEntry = _routingEntryMap.get(offlineTableName);
+    Preconditions.checkState(routingEntry != null, "Failed to find routing for table: %s",
offlineTableName);
+    TimeBoundaryManager timeBoundaryManager = routingEntry.getTimeBoundaryManager();
+    return timeBoundaryManager != null ? timeBoundaryManager.getTimeBoundaryInfo() : null;
+  }
+
+  private static class RoutingEntry {
+    final String _tableNameWithType;
+    final SegmentSelector _segmentSelector;
+    final SegmentPruner _segmentPruner;
+    final InstanceSelector _instanceSelector;
+
+    // Cache the ExternalView version for the last update
+    transient int _lastUpdateExternalViewVersion;
+    // Time boundary manager is only available for the offline part of the hybrid table
+    transient TimeBoundaryManager _timeBoundaryManager;
+
+    RoutingEntry(String tableNameWithType, SegmentSelector segmentSelector, SegmentPruner
segmentPruner,
+        InstanceSelector instanceSelector, int lastUpdateExternalViewVersion,
+        @Nullable TimeBoundaryManager timeBoundaryManager) {
+      _tableNameWithType = tableNameWithType;
+      _segmentSelector = segmentSelector;
+      _segmentPruner = segmentPruner;
+      _instanceSelector = instanceSelector;
+      _lastUpdateExternalViewVersion = lastUpdateExternalViewVersion;
+      _timeBoundaryManager = timeBoundaryManager;
+    }
+
+    String getTableNameWithType() {
+      return _tableNameWithType;
+    }
+
+    int getLastUpdateExternalViewVersion() {
+      return _lastUpdateExternalViewVersion;
+    }
+
+    void setTimeBoundaryManager(@Nullable TimeBoundaryManager timeBoundaryManager) {
+      _timeBoundaryManager = timeBoundaryManager;
+    }
+
+    @Nullable
+    TimeBoundaryManager getTimeBoundaryManager() {
+      return _timeBoundaryManager;
+    }
+
+    void onExternalViewChange(ExternalView externalView, Set<String> onlineSegments)
{
 
 Review comment:
   Yes, we won't route to the new segments before the whole routing entry gets updated. Will
add some comments here

----------------------------------------------------------------
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.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org


Mime
View raw message