pinot-commits mailing list archives

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

 ##########
 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) {
 
 Review comment:
   why is this static?

----------------------------------------------------------------
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