Search in sources :

Example 1 with Metrics

use of com.usthe.common.entity.job.Metrics in project hertzbeat by dromara.

the class CommonDispatcher method dispatchCollectData.

@Override
public void dispatchCollectData(Timeout timeout, Metrics metrics, CollectRep.MetricsData metricsData) {
    WheelTimerTask timerJob = (WheelTimerTask) timeout.task();
    Job job = timerJob.getJob();
    metricsTimeoutMonitorMap.remove(job.getId() + "-" + metrics.getName());
    Set<Metrics> metricsSet = job.getNextCollectMetrics(metrics, false);
    if (job.isCyclic()) {
        // If it is an asynchronous periodic cyclic task, directly send the collected data of the indicator group to the message middleware
        // 若是异步的周期性循环任务,直接发送指标组的采集数据到消息中间件
        kafkaDataExporter.send(metricsData);
        // 或判断采集指标组是否优先级为0,即为可用性采集指标组 若可用性采集失败 则取消后面的指标组调度直接进入下一轮调度
        if (metricsSet == null || (metrics.getPriority() == (byte) 0 && metricsData.getCode() != CollectRep.Code.SUCCESS)) {
            // 先判断此次任务执行时间与任务采集间隔时间
            if (timeout.isCancelled()) {
                return;
            }
            long spendTime = System.currentTimeMillis() - job.getDispatchTime();
            long interval = job.getInterval() - spendTime / 1000;
            interval = interval <= 0 ? 0 : interval;
            // Reset Construction Execution Metrics Group View  重置构造执行指标组视图
            job.constructPriorMetrics();
            timerDispatch.cyclicJob(timerJob, interval, TimeUnit.SECONDS);
        } else if (!metricsSet.isEmpty()) {
            // The execution of the current level indicator group is completed, and the execution of the next level indicator group starts
            // 当前级别指标组执行完成,开始执行下一级别的指标组
            metricsSet.forEach(metricItem -> {
                MetricsCollect metricsCollect = new MetricsCollect(metricItem, timeout, this);
                jobRequestQueue.addJob(metricsCollect);
                metricsTimeoutMonitorMap.put(job.getId() + "-" + metricItem.getName(), new MetricsTime(System.currentTimeMillis(), metricItem, timeout));
            });
        } else {
        // The list of indicator groups at the current execution level has not been fully executed.
        // It needs to wait for the execution of other indicator groups of the same level to complete the execution and enter the next level for execution.
        // 当前执行级别的指标组列表未全执行完成,
        // 需等待其它同级别指标组执行完成后进入下一级别执行
        }
    } else {
        // If it is a temporary one-time task, you need to wait for the collected data of all indicator groups to be packaged and returned.
        // Insert the current indicator group data into the job for unified assembly
        // 若是临时性一次任务,需等待所有指标组的采集数据统一包装返回
        // 将当前指标组数据插入job里统一组装
        job.addCollectMetricsData(metricsData);
        if (metricsSet == null) {
            // The collection and execution of all indicator groups of this job are completed
            // and the result listener is notified of the combination of all indicator group data
            // 此Job所有指标组采集执行完成
            // 将所有指标组数据组合一起通知结果监听器
            timerDispatch.responseSyncJobData(job.getId(), job.getResponseDataTemp());
        } else if (!metricsSet.isEmpty()) {
            // The execution of the current level indicator group is completed, and the execution of the next level indicator group starts
            // 当前级别指标组执行完成,开始执行下一级别的指标组
            metricsSet.forEach(metricItem -> {
                MetricsCollect metricsCollect = new MetricsCollect(metricItem, timeout, this);
                jobRequestQueue.addJob(metricsCollect);
                metricsTimeoutMonitorMap.put(job.getId() + "-" + metricItem.getName(), new MetricsTime(System.currentTimeMillis(), metricItem, timeout));
            });
        } else {
        // The list of indicator groups at the current execution level has not been fully executed.
        // It needs to wait for the execution of other indicator groups of the same level to complete the execution and enter the next level for execution.
        // 当前执行级别的指标组列表未全执行完成,
        // 需等待其它同级别指标组执行完成后进入下一级别执行
        }
    }
}
Also used : Timeout(com.usthe.collector.dispatch.timer.Timeout) SynchronousQueue(java.util.concurrent.SynchronousQueue) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) MetricsDataExporter(com.usthe.collector.dispatch.export.MetricsDataExporter) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) Component(org.springframework.stereotype.Component) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) WheelTimerTask(com.usthe.collector.dispatch.timer.WheelTimerTask) Job(com.usthe.common.entity.job.Job) Map(java.util.Map) Data(lombok.Data) TimerDispatch(com.usthe.collector.dispatch.timer.TimerDispatch) AllArgsConstructor(lombok.AllArgsConstructor) CollectRep(com.usthe.common.entity.message.CollectRep) Metrics(com.usthe.common.entity.job.Metrics) Metrics(com.usthe.common.entity.job.Metrics) WheelTimerTask(com.usthe.collector.dispatch.timer.WheelTimerTask) Job(com.usthe.common.entity.job.Job)

Example 2 with Metrics

use of com.usthe.common.entity.job.Metrics in project hertzbeat by dromara.

the class CommonDispatcher method dispatchMetricsTask.

@Override
public void dispatchMetricsTask(Timeout timeout) {
    // Divide the collection task of a single application into corresponding collection tasks of the indicator group according to the indicator group under it. AbstractCollect
    // Put each indicator group into the thread pool for scheduling
    // 将单个应用的采集任务根据其下的指标组拆分为对应的指标组采集任务 AbstractCollect
    // 将每个指标组放入线程池进行调度
    WheelTimerTask timerTask = (WheelTimerTask) timeout.task();
    Job job = timerTask.getJob();
    job.constructPriorMetrics();
    Set<Metrics> metricsSet = job.getNextCollectMetrics(null, true);
    metricsSet.forEach(metrics -> {
        MetricsCollect metricsCollect = new MetricsCollect(metrics, timeout, this);
        jobRequestQueue.addJob(metricsCollect);
        metricsTimeoutMonitorMap.put(job.getId() + "-" + metrics.getName(), new MetricsTime(System.currentTimeMillis(), metrics, timeout));
    });
}
Also used : Metrics(com.usthe.common.entity.job.Metrics) WheelTimerTask(com.usthe.collector.dispatch.timer.WheelTimerTask) Job(com.usthe.common.entity.job.Job)

Example 3 with Metrics

use of com.usthe.common.entity.job.Metrics in project hertzbeat by dromara.

the class MetricsCollect method calculateFields.

/**
 * Calculate the real indicator (fields) value according to the calculates and aliasFields configuration
 * Calculate instance instance value
 * <p>
 * 根据 calculates 和 aliasFields 配置计算出真正的指标(fields)值
 * 计算instance实例值
 *
 * @param metrics     Metric group configuration        指标组配置
 * @param collectData Data collection       采集数据
 */
private void calculateFields(Metrics metrics, CollectRep.MetricsData.Builder collectData) {
    collectData.setPriority(metrics.getPriority());
    List<CollectRep.Field> fieldList = new LinkedList<>();
    for (Metrics.Field field : metrics.getFields()) {
        fieldList.add(CollectRep.Field.newBuilder().setName(field.getField()).setType(field.getType()).build());
    }
    collectData.addAllFields(fieldList);
    List<CollectRep.ValueRow> aliasRowList = collectData.getValuesList();
    if (aliasRowList == null || aliasRowList.isEmpty()) {
        return;
    }
    collectData.clearValues();
    // Preprocess calculates first      先预处理 calculates
    if (metrics.getCalculates() == null) {
        metrics.setCalculates(Collections.emptyList());
    }
    // eg: database_pages=Database pages unconventional mapping   非常规映射
    Map<String, String> fieldAliasMap = new HashMap<>(8);
    Map<String, Expression> fieldExpressionMap = metrics.getCalculates().stream().map(cal -> {
        int splitIndex = cal.indexOf("=");
        String field = cal.substring(0, splitIndex).trim();
        String expressionStr = cal.substring(splitIndex + 1).trim();
        Expression expression = null;
        try {
            expression = AviatorEvaluator.compile(expressionStr, true);
        } catch (Exception e) {
            fieldAliasMap.put(field, expressionStr);
            return null;
        }
        return new Object[] { field, expression };
    }).filter(Objects::nonNull).collect(Collectors.toMap(arr -> (String) arr[0], arr -> (Expression) arr[1]));
    List<Metrics.Field> fields = metrics.getFields();
    List<String> aliasFields = metrics.getAliasFields();
    Map<String, String> aliasFieldValueMap = new HashMap<>(16);
    Map<String, Object> fieldValueMap = new HashMap<>(16);
    CollectRep.ValueRow.Builder realValueRowBuilder = CollectRep.ValueRow.newBuilder();
    for (CollectRep.ValueRow aliasRow : aliasRowList) {
        for (int aliasIndex = 0; aliasIndex < aliasFields.size(); aliasIndex++) {
            String aliasFieldValue = aliasRow.getColumns(aliasIndex);
            if (!CommonConstants.NULL_VALUE.equals(aliasFieldValue)) {
                aliasFieldValueMap.put(aliasFields.get(aliasIndex), aliasFieldValue);
            }
        }
        StringBuilder instanceBuilder = new StringBuilder();
        for (Metrics.Field field : fields) {
            String realField = field.getField();
            Expression expression = fieldExpressionMap.get(realField);
            String value = null;
            if (expression != null) {
                // 存在计算表达式 则计算值
                if (CommonConstants.TYPE_NUMBER == field.getType()) {
                    for (String variable : expression.getVariableNames()) {
                        Double doubleValue = CommonUtil.parseDoubleStr(aliasFieldValueMap.get(variable));
                        if (doubleValue != null) {
                            fieldValueMap.put(variable, doubleValue);
                        }
                    }
                } else {
                    for (String variable : expression.getVariableNames()) {
                        String strValue = aliasFieldValueMap.get(variable);
                        if (strValue != null && !"".equals(strValue)) {
                            fieldValueMap.put(variable, strValue);
                        }
                    }
                }
                try {
                    Object objValue = expression.execute(fieldValueMap);
                    if (objValue != null) {
                        value = String.valueOf(objValue);
                    }
                } catch (Exception e) {
                    log.warn(e.getMessage());
                }
            } else {
                // does not exist then map the alias value
                // 不存在 则映射别名值
                String aliasField = fieldAliasMap.get(realField);
                if (aliasField != null) {
                    value = aliasFieldValueMap.get(aliasField);
                } else {
                    value = aliasFieldValueMap.get(realField);
                }
            }
            // 处理可能带单位的指标数值 比如 34%, 34Mb,并将数值小数点限制到4位
            if (CommonConstants.TYPE_NUMBER == field.getType()) {
                value = CommonUtil.parseDoubleStr(value, field.getUnit());
            }
            if (value == null) {
                value = CommonConstants.NULL_VALUE;
            }
            realValueRowBuilder.addColumns(value);
            fieldValueMap.clear();
            if (field.isInstance() && !CommonConstants.NULL_VALUE.equals(value)) {
                instanceBuilder.append(value);
            }
        }
        aliasFieldValueMap.clear();
        // set instance         设置实例instance
        realValueRowBuilder.setInstance(instanceBuilder.toString());
        collectData.addValues(realValueRowBuilder.build());
        realValueRowBuilder.clear();
    }
}
Also used : Timeout(com.usthe.collector.dispatch.timer.Timeout) Expression(com.googlecode.aviator.Expression) CommonConstants(com.usthe.common.util.CommonConstants) AviatorEvaluator(com.googlecode.aviator.AviatorEvaluator) HashMap(java.util.HashMap) JdbcCommonCollect(com.usthe.collector.collect.database.JdbcCommonCollect) WheelTimerTask(com.usthe.collector.dispatch.timer.WheelTimerTask) Job(com.usthe.common.entity.job.Job) Map(java.util.Map) AbstractCollect(com.usthe.collector.collect.AbstractCollect) LinkedList(java.util.LinkedList) CollectRep(com.usthe.common.entity.message.CollectRep) RedisSingleCollectImpl(com.usthe.collector.collect.redis.RedisSingleCollectImpl) SshCollectImpl(com.usthe.collector.collect.ssh.SshCollectImpl) CommonUtil(com.usthe.common.util.CommonUtil) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Data(lombok.Data) TelnetCollectImpl(com.usthe.collector.collect.telnet.TelnetCollectImpl) Collections(java.util.Collections) HttpCollectImpl(com.usthe.collector.collect.http.HttpCollectImpl) IcmpCollectImpl(com.usthe.collector.collect.icmp.IcmpCollectImpl) Metrics(com.usthe.common.entity.job.Metrics) HashMap(java.util.HashMap) LinkedList(java.util.LinkedList) Metrics(com.usthe.common.entity.job.Metrics) CollectRep(com.usthe.common.entity.message.CollectRep) Expression(com.googlecode.aviator.Expression)

Example 4 with Metrics

use of com.usthe.common.entity.job.Metrics in project hertzbeat by dromara.

the class AppServiceImpl method getAllAppHierarchy.

@Override
public List<Hierarchy> getAllAppHierarchy(String lang) {
    List<Hierarchy> hierarchies = new LinkedList<>();
    for (Job job : appDefines.values()) {
        Hierarchy hierarchyApp = new Hierarchy();
        hierarchyApp.setCategory(job.getCategory());
        hierarchyApp.setValue(job.getApp());
        Map<String, String> nameMap = job.getName();
        if (nameMap != null) {
            String i18nName = nameMap.get(lang);
            if (i18nName == null) {
                i18nName = nameMap.values().stream().findFirst().get();
            }
            hierarchyApp.setLabel(i18nName);
        }
        List<Hierarchy> hierarchyMetricList = new LinkedList<>();
        if (job.getMetrics() != null) {
            for (Metrics metrics : job.getMetrics()) {
                Hierarchy hierarchyMetric = new Hierarchy();
                hierarchyMetric.setValue(metrics.getName());
                hierarchyMetric.setLabel(metrics.getName());
                List<Hierarchy> hierarchyFieldList = new LinkedList<>();
                if (metrics.getFields() != null) {
                    for (Metrics.Field field : metrics.getFields()) {
                        Hierarchy hierarchyField = new Hierarchy();
                        hierarchyField.setValue(field.getField());
                        hierarchyField.setLabel(field.getField());
                        hierarchyField.setIsLeaf(true);
                        hierarchyFieldList.add(hierarchyField);
                    }
                    hierarchyMetric.setChildren(hierarchyFieldList);
                }
                hierarchyMetricList.add(hierarchyMetric);
            }
        }
        hierarchyApp.setChildren(hierarchyMetricList);
        hierarchies.add(hierarchyApp);
    }
    return hierarchies;
}
Also used : Hierarchy(com.usthe.manager.pojo.dto.Hierarchy) Metrics(com.usthe.common.entity.job.Metrics) Job(com.usthe.common.entity.job.Job) LinkedList(java.util.LinkedList)

Example 5 with Metrics

use of com.usthe.common.entity.job.Metrics in project hertzbeat by dromara.

the class MonitorServiceImpl method detectMonitor.

@Override
@Transactional(readOnly = true)
public void detectMonitor(Monitor monitor, List<Param> params) throws MonitorDetectException {
    Long monitorId = monitor.getId();
    if (monitorId == null || monitorId == 0) {
        monitorId = MONITOR_ID_TMP;
    }
    Job appDefine = appService.getAppDefine(monitor.getApp());
    appDefine.setMonitorId(monitorId);
    appDefine.setCyclic(false);
    appDefine.setTimestamp(System.currentTimeMillis());
    List<Configmap> configmaps = params.stream().map(param -> new Configmap(param.getField(), param.getValue(), param.getType())).collect(Collectors.toList());
    appDefine.setConfigmap(configmaps);
    // To detect availability, you only need to collect the set of availability indicators with a priority of 0.
    // 探测可用性只需要采集优先级为0的可用性指标集合
    List<Metrics> availableMetrics = appDefine.getMetrics().stream().filter(item -> item.getPriority() == 0).collect(Collectors.toList());
    appDefine.setMetrics(availableMetrics);
    List<CollectRep.MetricsData> collectRep = collectJobService.collectSyncJobData(appDefine);
    // 判断探测结果 失败则抛出探测异常
    if (collectRep == null || collectRep.isEmpty()) {
        throw new MonitorDetectException("No collector response");
    }
    if (collectRep.get(0).getCode() != CollectRep.Code.SUCCESS) {
        throw new MonitorDetectException(collectRep.get(0).getMsg());
    }
}
Also used : java.util(java.util) CommonConstants(com.usthe.common.util.CommonConstants) MonitorDao(com.usthe.manager.dao.MonitorDao) ParamDefine(com.usthe.common.entity.manager.ParamDefine) MonitorDatabaseException(com.usthe.manager.support.exception.MonitorDatabaseException) Configmap(com.usthe.common.entity.job.Configmap) Autowired(org.springframework.beans.factory.annotation.Autowired) Param(com.usthe.common.entity.manager.Param) IntervalExpressionUtil(com.usthe.common.util.IntervalExpressionUtil) MonitorService(com.usthe.manager.service.MonitorService) Job(com.usthe.common.entity.job.Job) AppCount(com.usthe.manager.pojo.dto.AppCount) Tag(com.usthe.common.entity.manager.Tag) Service(org.springframework.stereotype.Service) MonitorDto(com.usthe.manager.pojo.dto.MonitorDto) CollectRep(com.usthe.common.entity.message.CollectRep) ParamDao(com.usthe.manager.dao.ParamDao) Monitor(com.usthe.common.entity.manager.Monitor) PageRequest(org.springframework.data.domain.PageRequest) Page(org.springframework.data.domain.Page) Collectors(java.util.stream.Collectors) IpDomainUtil(com.usthe.common.util.IpDomainUtil) Slf4j(lombok.extern.slf4j.Slf4j) AlertDefineBindDao(com.usthe.alert.dao.AlertDefineBindDao) SnowFlakeIdGenerator(com.usthe.common.util.SnowFlakeIdGenerator) Specification(org.springframework.data.jpa.domain.Specification) AppService(com.usthe.manager.service.AppService) AesUtil(com.usthe.common.util.AesUtil) CollectJobService(com.usthe.collector.dispatch.entrance.internal.CollectJobService) MonitorDetectException(com.usthe.manager.support.exception.MonitorDetectException) Metrics(com.usthe.common.entity.job.Metrics) Transactional(org.springframework.transaction.annotation.Transactional) Metrics(com.usthe.common.entity.job.Metrics) MonitorDetectException(com.usthe.manager.support.exception.MonitorDetectException) Configmap(com.usthe.common.entity.job.Configmap) Job(com.usthe.common.entity.job.Job) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

Job (com.usthe.common.entity.job.Job)6 Metrics (com.usthe.common.entity.job.Metrics)6 Slf4j (lombok.extern.slf4j.Slf4j)4 WheelTimerTask (com.usthe.collector.dispatch.timer.WheelTimerTask)3 CollectRep (com.usthe.common.entity.message.CollectRep)3 CommonConstants (com.usthe.common.util.CommonConstants)3 Map (java.util.Map)3 Collectors (java.util.stream.Collectors)3 Timeout (com.usthe.collector.dispatch.timer.Timeout)2 Configmap (com.usthe.common.entity.job.Configmap)2 AesUtil (com.usthe.common.util.AesUtil)2 LinkedList (java.util.LinkedList)2 Data (lombok.Data)2 Gson (com.google.gson.Gson)1 JsonArray (com.google.gson.JsonArray)1 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 AviatorEvaluator (com.googlecode.aviator.AviatorEvaluator)1 Expression (com.googlecode.aviator.Expression)1