deemoliu commented on code in PR #14686:
URL: https://github.com/apache/pinot/pull/14686#discussion_r1978434991


##########
pinot-server/src/main/java/org/apache/pinot/server/predownload/PredownloadScheduler.java:
##########
@@ -0,0 +1,430 @@
+/**
+ * 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.server.predownload;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.commons.configuration2.PropertiesConfiguration;
+import org.apache.commons.io.FileUtils;
+import org.apache.pinot.common.utils.TarCompressionUtils;
+import org.apache.pinot.common.utils.fetcher.SegmentFetcherFactory;
+import org.apache.pinot.server.conf.ServerConf;
+import org.apache.pinot.server.starter.helix.HelixInstanceDataManagerConfig;
+import org.apache.pinot.spi.config.instance.InstanceDataManagerConfig;
+import org.apache.pinot.spi.crypt.PinotCrypterFactory;
+import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.filesystem.PinotFSFactory;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.retry.AttemptsExceededException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class PredownloadScheduler {
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(PredownloadScheduler.class);
+  private static final String TMP_DIR_NAME = "tmp";
+  // Segment download dir in format of "tmp-" + segmentName + "-" + 
UUID.randomUUID()
+  private static final String TMP_DIR_FORMAT = "tmp-%s-%s";
+  // TODO: make download timeout configurable
+  private static final long DOWNLOAD_SEGMENTS_TIMEOUT_MIN = 60;
+  private static final long LOAD_SEGMENTS_TIMEOUT_MIN = 5;
+  private final PropertiesConfiguration _properties;
+  private final PinotConfiguration _pinotConfig;
+  private final InstanceDataManagerConfig _instanceDataManagerConfig;
+  private final String _clusterName;
+  private final String _instanceId;
+  private final String _zkAddress;
+  @VisibleForTesting
+  Executor _executor;
+  @VisibleForTesting
+  Set<String> _failedSegments;
+  private PredownloadMetrics _predownloadMetrics;
+  private int _numOfSkippedSegments;
+  private int _numOfUnableToDownloadSegments;
+  private int _numOfDownloadSegments;
+  private long _totalDownloadedSizeBytes;
+  private PredownloadZKClient _predownloadZkClient;
+  private List<PredownloadSegmentInfo> _predownloadSegmentInfoList;
+  private Map<String, PredownloadTableInfo> _tableInfoMap;
+
+  public PredownloadScheduler(PropertiesConfiguration properties)
+      throws Exception {
+    _properties = properties;
+    _clusterName = 
properties.getString(CommonConstants.Helix.CONFIG_OF_CLUSTER_NAME);
+    _zkAddress = 
properties.getString(CommonConstants.Helix.CONFIG_OF_ZOOKEEPR_SERVER);
+    _instanceId = 
properties.getString(CommonConstants.Server.CONFIG_OF_INSTANCE_ID);
+    _pinotConfig = new PinotConfiguration(properties);
+    _instanceDataManagerConfig =
+        new HelixInstanceDataManagerConfig(new 
ServerConf(_pinotConfig).getInstanceDataManagerConfig());
+    // Get the number of available processors (vCPUs)
+    int numProcessors = Runtime.getRuntime().availableProcessors();
+    _failedSegments = ConcurrentHashMap.newKeySet();
+    // TODO: tune the value
+    _executor = Executors.newFixedThreadPool(numProcessors * 3);
+    LOGGER.info("Created thread pool with num of threads: {}", numProcessors * 
3);
+    _numOfSkippedSegments = 0;
+    _numOfDownloadSegments = 0;
+  }
+
+  public void start() {
+
+    Runtime.getRuntime().addShutdownHook(new Thread() {
+      @Override
+      public void run() {
+        try {
+          LOGGER.info("Trying to stop predownload process!");
+          stop();
+        } catch (Exception e) {
+          LOGGER.error("error shutting down predownload process : ", e);
+        }
+      }
+    });
+
+    long startTime = System.currentTimeMillis();
+    initializeZK();
+    initializeMetricsReporter();
+    initializeSegmentFetcher();
+    getSegmentsInfo();
+    loadSegmentsFromLocal();
+    PredownloadCompletionReason reason = downloadSegments();
+    long timeTaken = System.currentTimeMillis() - startTime;
+    LOGGER.info(
+        "Predownload process took {} sec, tried to download {} segments, 
skipped {} segments "
+            + "and unable to download {} segments. Download size: {} MB. 
Download speed: {} MB/s",
+        timeTaken / 1000, _numOfDownloadSegments, _numOfSkippedSegments, 
_numOfUnableToDownloadSegments,
+        _totalDownloadedSizeBytes / (1024 * 1024),
+        (_totalDownloadedSizeBytes / (1024 * 1024)) / (timeTaken / 1000 + 1));
+    if (reason.isSucceed()) {
+      _predownloadMetrics.preDownloadSucceed(_totalDownloadedSizeBytes, 
timeTaken);
+    }
+    PredownloadStatusRecorder.predownloadComplete(reason, _clusterName, 
_instanceId, String.join(",", _failedSegments));
+  }
+
+  public void stop() {
+    if (_predownloadZkClient != null) {
+      _predownloadZkClient.close();
+    }
+    if (_executor != null) {
+      ((ThreadPoolExecutor) _executor).shutdownNow();
+    }
+  }
+
+  void initializeZK() {
+    LOGGER.info("Initializing ZK client with address: {} and instanceId: {}", 
_zkAddress, _instanceId);
+    _predownloadZkClient = new PredownloadZKClient(_zkAddress, _clusterName, 
_instanceId);
+    _predownloadZkClient.start();
+  }
+
+  void initializeMetricsReporter() {
+    LOGGER.info("Initializing metrics reporter");
+
+    _predownloadMetrics = new PredownloadMetrics();
+    PredownloadStatusRecorder.registerMetrics(_predownloadMetrics);
+  }
+
+  @VisibleForTesting
+  void getSegmentsInfo() {
+    LOGGER.info("Getting segments info from ZK");
+    _predownloadSegmentInfoList = 
_predownloadZkClient.getSegmentsOfInstance(_predownloadZkClient.getDataAccessor());
+    if (_predownloadSegmentInfoList.isEmpty()) {
+      PredownloadCompletionReason reason = 
PredownloadCompletionReason.NO_SEGMENT_TO_PREDOWNLOAD;
+      PredownloadStatusRecorder.predownloadComplete(reason, _clusterName, 
_instanceId, "");
+    }
+    _tableInfoMap = new HashMap<>();
+    _predownloadZkClient.updateSegmentMetadata(_predownloadSegmentInfoList, 
_tableInfoMap,
+        _instanceDataManagerConfig);
+  }
+
+  @VisibleForTesting
+  void loadSegmentsFromLocal() {
+    LOGGER.info("Loading segments from local to reduce number of segments to 
download");
+    long startTime = System.currentTimeMillis();
+    List<CompletableFuture<Void>> futures = new ArrayList<>();
+
+    // Submit tasks to the executor
+    for (PredownloadSegmentInfo predownloadSegmentInfo : 
_predownloadSegmentInfoList) {
+      CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
+        boolean loadSegmentSuccess = false;
+        try {
+          PredownloadTableInfo predownloadTableInfo = 
_tableInfoMap.get(predownloadSegmentInfo.getTableNameWithType());
+          if (predownloadTableInfo != null) {
+            loadSegmentSuccess =
+                
predownloadTableInfo.loadSegmentFromLocal(predownloadSegmentInfo, 
_instanceDataManagerConfig);
+          }
+        } catch (Exception e) {
+          LOGGER.error("Failed to load from local for segment: {} of table: {} 
with issue ",
+              predownloadSegmentInfo.getSegmentName(), 
predownloadSegmentInfo.getTableNameWithType(), e);

Review Comment:
   can we reuse `predownloadSegmentInfo.getTableNameWithType()`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@pinot.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


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

Reply via email to