akshayrai commented on a change in pull request #4777: [TE] add event driven scheduler URL: https://github.com/apache/incubator-pinot/pull/4777#discussion_r343930422
########## 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())); + } + } + dataset2DetectionMap.put(datasets, detectionConfig); + for (String dataset : datasets) { + if (!datasetRefreshTimeMap.containsKey(dataset)) { + DatasetConfigDTO datasetConfig = datasetConfigManager.findByDataset(dataset); + datasetRefreshTimeMap.put(dataset, datasetConfig.getLastRefreshTime()); + } + } + } + } + + private Map<Long, TaskDTO> retrieveRunningDetection() { + TaskManager taskManager = DAORegistry.getInstance().getTaskDAO(); + List<TaskConstants.TaskStatus> statuses = new ArrayList<>(); + statuses.add(TaskConstants.TaskStatus.WAITING); + statuses.add(TaskConstants.TaskStatus.RUNNING); + List<TaskDTO> tasks = taskManager.findByStatusesAndTypeWithinDays(statuses, TaskConstants.TaskType.DETECTION, + (int) TimeUnit.MILLISECONDS.toDays(ThirdEyeUtils.DETECTION_TASK_MAX_LOOKBACK_WINDOW)); + Map<Long, TaskDTO> res = new HashMap<>(tasks.size()); + for (TaskDTO task : tasks) { + String[] parts = task.getJobName().split("_"); + if (parts.length < 2) { + LOG.error("Invalid name found {} for task id {}", task.getJobName(), task.getId()); + continue; + } + res.put(Long.parseLong(parts[1]), task); + } + return res; + } + + private void createDetectionTask(DetectionConfigDTO detectionConfig) { + TaskManager taskManager = DAORegistry.getInstance().getTaskDAO(); + long detectionConfigId = detectionConfig.getId(); + // Make sure start time is not out of DETECTION_TASK_MAX_LOOKBACK_WINDOW + long end = System.currentTimeMillis(); + long start = Math.max(detectionConfig.getLastTimestamp(), + end - ThirdEyeUtils.DETECTION_TASK_MAX_LOOKBACK_WINDOW); + DetectionPipelineTaskInfo taskInfo = new DetectionPipelineTaskInfo(detectionConfigId, start, end); + String taskInfoJson = null; + try { + taskInfoJson = OBJECT_MAPPER.writeValueAsString(taskInfo); + } catch (JsonProcessingException e) { + LOG.error("Exception when converting DetectionPipelineTaskInfo {} to jsonString", taskInfo, e); + } + TaskDTO taskDTO = new TaskDTO(); + + taskDTO.setTaskType(TaskConstants.TaskType.DETECTION); + taskDTO.setJobName(TaskConstants.TaskType.DETECTION.toString() + "_" + detectionConfigId); + taskDTO.setStatus(TaskConstants.TaskStatus.WAITING); + taskDTO.setTaskInfo(taskInfoJson); + long taskId = taskManager.save(taskDTO); + LOG.info("Created detection pipeline task {} with taskId {}", taskDTO, taskId); + lastTaskCreateTimeMap.put(detectionConfigId, end); + } + + private void loadLatestTaskCreateTime (DetectionConfigDTO detectionConfig) throws Exception { + long detectionConfigId = detectionConfig.getId(); + TaskManager taskManager = DAORegistry.getInstance().getTaskDAO(); Review comment: nit: As a organically grown convention in ThirdEye, we prefer naming all the data access object variables suffixed with `...DAO`. Example: taskDAO, anomalyDAO, detectionDAO etc. Applies here and elsewhere above ---------------------------------------------------------------- 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]
