xiaohui-sun commented on a change in pull request #4777: [TE] add event driven scheduler URL: https://github.com/apache/incubator-pinot/pull/4777#discussion_r343847067
########## File path: thirdeye/thirdeye-pinot/src/main/java/org/apache/pinot/thirdeye/anomaly/detection/trigger/DataAvailabilityTaskScheduler.java ########## @@ -0,0 +1,229 @@ +/* + * 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.thirdeye.anomaly.detection.trigger; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimap; +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.Executors; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import org.apache.pinot.thirdeye.anomaly.task.TaskConstants; +import org.apache.pinot.thirdeye.anomaly.task.TaskInfoFactory; +import org.apache.pinot.thirdeye.datalayer.bao.DatasetConfigManager; +import org.apache.pinot.thirdeye.datalayer.bao.DetectionConfigManager; +import org.apache.pinot.thirdeye.datalayer.bao.MetricConfigManager; +import org.apache.pinot.thirdeye.datalayer.bao.TaskManager; +import org.apache.pinot.thirdeye.datalayer.dto.DatasetConfigDTO; +import org.apache.pinot.thirdeye.datalayer.dto.DetectionConfigDTO; +import org.apache.pinot.thirdeye.datalayer.dto.MetricConfigDTO; +import org.apache.pinot.thirdeye.datalayer.dto.TaskDTO; +import org.apache.pinot.thirdeye.datasource.DAORegistry; +import org.apache.pinot.thirdeye.datasource.MetricExpression; +import org.apache.pinot.thirdeye.datasource.MetricFunction; +import org.apache.pinot.thirdeye.detection.DetectionPipelineTaskInfo; +import org.apache.pinot.thirdeye.formatter.DetectionConfigFormatter; +import org.apache.pinot.thirdeye.rootcause.impl.MetricEntity; +import org.apache.pinot.thirdeye.util.ThirdEyeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DataAvailabilityTaskScheduler implements Runnable { + public static final String LIX_FLAG_VALUE = "DATA_AVAILABILITY_SCHEDULE"; + private static final Logger LOG = LoggerFactory.getLogger(DataAvailabilityTaskScheduler.class); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private ScheduledThreadPoolExecutor executorService; + private long delayInSec; + private int notRunThresholdInMin; + private Map<Long, Long> lastTaskCreateTimeMap; + + public DataAvailabilityTaskScheduler(long delayInSec, int notRunThresholdInMin ) { + this.delayInSec = delayInSec; + this.notRunThresholdInMin = notRunThresholdInMin; + this.lastTaskCreateTimeMap = new HashMap<>(); + this.executorService = new ScheduledThreadPoolExecutor(1, r -> { + Thread t = Executors.defaultThreadFactory().newThread(r); + t.setDaemon(true); + return t; + }); + } + + @Override + public void run() { + Multimap<Set<String>, DetectionConfigDTO> dataset2DetectionMap = ArrayListMultimap.create(); + Map<String, Long> datasetRefreshTimeMap = new HashMap<>(); + populateRequiredMetadata(dataset2DetectionMap, datasetRefreshTimeMap); + Map<Long, TaskDTO> runningDetection = retrieveRunningDetection(); + for (Set<String> datasets : dataset2DetectionMap.keySet()) { + for (DetectionConfigDTO detectionConfig : dataset2DetectionMap.get(datasets)) { + long detectionConfigId = detectionConfig.getId(); + long lastTimestamp = detectionConfig.getLastTimestamp(); + boolean allUpdated = datasets.stream().map(d -> datasetRefreshTimeMap.get(d) >= lastTimestamp) + .reduce(true, (a, b) -> a && b); + if (allUpdated) { + if (!runningDetection.containsKey(detectionConfigId)) { + createDetectionTask(detectionConfig); + } else { + LOG.info("Skipping creating detection task for detection {} because task {} is not finished.", + detectionConfigId, runningDetection.get(detectionConfigId)); + } + } else { + try { + if (!runningDetection.containsKey(detectionConfigId)) { + if (!lastTaskCreateTimeMap.containsKey(detectionConfigId)) loadLatestTaskCreateTime(detectionConfig); + long lastRunTime = lastTaskCreateTimeMap.get(detectionConfigId); + if (System.currentTimeMillis() - lastRunTime >= TimeUnit.MINUTES.toMillis(notRunThresholdInMin)) { + LOG.info("Scheduling a task for detection {}, since the create time of last task is {}", + detectionConfigId, lastRunTime); + createDetectionTask(detectionConfig); + } + } + } catch (Exception e) { + LOG.error("Unable to check latest task create time for detection {}, so skipping...", detectionConfigId ,e); + } + } + } + } + } + + public void start() { + executorService.scheduleWithFixedDelay(this, 0, delayInSec, TimeUnit.SECONDS); + } + + public void close() { + executorService.shutdownNow(); + } + + private void populateRequiredMetadata(Multimap<Set<String>, DetectionConfigDTO> dataset2DetectionMap, + Map<String, Long> datasetRefreshTimeMap) { + DetectionConfigManager detectionConfigManager = DAORegistry.getInstance().getDetectionConfigManager(); + MetricConfigManager metricConfigManager = DAORegistry.getInstance().getMetricConfigDAO(); + DatasetConfigManager datasetConfigManager = DAORegistry.getInstance().getDatasetConfigDAO(); + Map<Long, Set<String>> metricCache = new HashMap<>(); + List<DetectionConfigDTO> detectionConfigs = detectionConfigManager.findAll(); + for (DetectionConfigDTO detectionConfig : detectionConfigs) { + if (!detectionConfig.isActive()) continue; // skip inactive detection + if (detectionConfig.getLixFlags().stream().filter(x -> x.equals(LIX_FLAG_VALUE)).count() < 1) continue; + List<String> metricUrns = DetectionConfigFormatter + .extractMetricUrnsFromProperties(detectionConfig.getProperties()); + if (metricUrns.size() < 1) { + LOG.error("Empty metricUrn for detection {}", detectionConfig.getId()); + continue; + } + Set<String> datasets = new HashSet<>(); + for (String urn : metricUrns) { + MetricEntity me = MetricEntity.fromURN(urn); + if (!metricCache.containsKey(me.getId())) { + MetricConfigDTO metricConfig = metricConfigManager.findById(me.getId()); + if (metricConfig == null) { + LOG.warn("Found null value for metric: " + me.getId()); + metricCache.put(me.getId(), null); + continue; + } + if (metricConfig.isDerived()) { + MetricExpression metricExpression = ThirdEyeUtils.getMetricExpressionFromMetricConfig(metricConfig); + List<MetricFunction> functions = metricExpression.computeMetricFunctions(); + functions.forEach(f -> datasets.add(f.getDataset())); + } else { + datasets.add(metricConfig.getDataset()); + } + // cache the mapping in memory to avoid duplicate retrieval + metricCache.put(me.getId(), datasets); + } else { + // retrieve dataset mapping from memory + if (metricCache.get(me.getId()) != null) + datasets.addAll(metricCache.get(me.getId())); + } + } Review comment: This logic is duplicated. Can we put it in a helper function and get it reused? ---------------------------------------------------------------- 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: [email protected] With regards, Apache Git Services --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
