Search in sources :

Example 1 with AlertDefine

use of com.usthe.common.entity.alerter.AlertDefine in project hertzbeat by dromara.

the class CalculateAlarm method calculate.

private void calculate(CollectRep.MetricsData metricsData) {
    long currentTimeMilli = System.currentTimeMillis();
    long monitorId = metricsData.getId();
    String app = metricsData.getApp();
    String metrics = metricsData.getMetrics();
    // 先判断调度优先级为0的指标组采集响应数据状态 UN_REACHABLE/UN_CONNECTABLE 则需发最高级别告警进行监控状态变更
    if (metricsData.getPriority() == 0) {
        if (metricsData.getCode() != CollectRep.Code.SUCCESS) {
            // 采集异常
            if (metricsData.getCode() == CollectRep.Code.UN_AVAILABLE) {
            // todo 采集器不可用
            } else if (metricsData.getCode() == CollectRep.Code.UN_REACHABLE) {
                // UN_REACHABLE 对端不可达(网络层icmp)
                handlerMonitorStatusAlert(String.valueOf(monitorId), app, metricsData.getCode());
            } else if (metricsData.getCode() == CollectRep.Code.UN_CONNECTABLE) {
                // UN_CONNECTABLE 对端连接失败(传输层tcp,udp)
                handlerMonitorStatusAlert(String.valueOf(monitorId), app, metricsData.getCode());
            } else {
                // 其他异常
                handlerMonitorStatusAlert(String.valueOf(monitorId), app, metricsData.getCode());
            }
            return;
        } else {
            // 判断关联监控之前是否有可用性或者不可达告警,发送恢复告警进行监控状态恢复
            Alert preAlert = triggeredAlertMap.remove(String.valueOf(monitorId));
            if (preAlert != null && preAlert.getStatus() == CommonConstants.ALERT_STATUS_CODE_PENDING) {
                // 发送告警恢复
                Map<String, String> tags = new HashMap<>(6);
                tags.put(CommonConstants.TAG_MONITOR_ID, String.valueOf(monitorId));
                tags.put(CommonConstants.TAG_MONITOR_APP, app);
                String target = CommonConstants.AVAILABLE;
                String content = this.bundle.getString("alerter.availability.resolved");
                if (CommonConstants.REACHABLE.equals(preAlert.getTarget())) {
                    target = CommonConstants.REACHABLE;
                    content = this.bundle.getString("alerter.reachability.resolved");
                }
                Alert resumeAlert = Alert.builder().tags(tags).target(target).content(content).priority(CommonConstants.ALERT_PRIORITY_CODE_WARNING).status(CommonConstants.ALERT_STATUS_CODE_RESTORED).firstTriggerTime(currentTimeMilli).lastTriggerTime(currentTimeMilli).times(1).build();
                dataQueue.addAlertData(resumeAlert);
            }
        }
    }
    // 查出此监控类型下的此指标集合下关联配置的告警定义信息
    // field - define[]
    Map<String, List<AlertDefine>> defineMap = alertDefineService.getMonitorBindAlertDefines(monitorId, app, metrics);
    if (defineMap == null || defineMap.isEmpty()) {
        return;
    }
    List<CollectRep.Field> fields = metricsData.getFieldsList();
    Map<String, Object> fieldValueMap = new HashMap<>(16);
    for (CollectRep.ValueRow valueRow : metricsData.getValuesList()) {
        if (!valueRow.getColumnsList().isEmpty()) {
            fieldValueMap.clear();
            String instance = valueRow.getInstance();
            if (!"".equals(instance)) {
                fieldValueMap.put("instance", instance);
            }
            for (int index = 0; index < valueRow.getColumnsList().size(); index++) {
                String valueStr = valueRow.getColumns(index);
                CollectRep.Field field = fields.get(index);
                if (field.getType() == CommonConstants.TYPE_NUMBER) {
                    Double doubleValue = CommonUtil.parseDoubleStr(valueStr);
                    if (doubleValue != null) {
                        fieldValueMap.put(field.getName(), doubleValue);
                    }
                } else {
                    if (!"".equals(valueStr)) {
                        fieldValueMap.put(field.getName(), valueStr);
                    }
                }
            }
            for (Map.Entry<String, List<AlertDefine>> entry : defineMap.entrySet()) {
                List<AlertDefine> defines = entry.getValue();
                for (AlertDefine define : defines) {
                    String expr = define.getExpr();
                    try {
                        Expression expression = AviatorEvaluator.compile(expr, true);
                        Boolean match = (Boolean) expression.execute(fieldValueMap);
                        if (match) {
                            // 阈值规则匹配,判断已触发阈值次数,触发告警
                            String monitorAlertKey = String.valueOf(monitorId) + define.getId();
                            Alert triggeredAlert = triggeredAlertMap.get(monitorAlertKey);
                            if (triggeredAlert != null) {
                                int times = triggeredAlert.getTimes() + 1;
                                triggeredAlert.setTimes(times);
                                triggeredAlert.setLastTriggerTime(currentTimeMilli);
                                int defineTimes = define.getTimes() == null ? 0 : define.getTimes();
                                if (times >= defineTimes) {
                                    triggeredAlertMap.remove(monitorAlertKey);
                                    dataQueue.addAlertData(triggeredAlert);
                                }
                            } else {
                                int times = 1;
                                fieldValueMap.put("app", app);
                                fieldValueMap.put("metrics", metrics);
                                fieldValueMap.put("metric", define.getField());
                                Map<String, String> tags = new HashMap<>(6);
                                tags.put(CommonConstants.TAG_MONITOR_ID, String.valueOf(monitorId));
                                tags.put(CommonConstants.TAG_MONITOR_APP, app);
                                Alert alert = Alert.builder().tags(tags).alertDefineId(define.getId()).priority(define.getPriority()).status(CommonConstants.ALERT_STATUS_CODE_PENDING).target(app + "." + metrics + "." + define.getField()).times(times).firstTriggerTime(currentTimeMilli).lastTriggerTime(currentTimeMilli).content(AlertTemplateUtil.render(define.getTemplate(), fieldValueMap)).build();
                                int defineTimes = define.getTimes() == null ? 0 : define.getTimes();
                                if (times >= defineTimes) {
                                    dataQueue.addAlertData(alert);
                                } else {
                                    triggeredAlertMap.put(monitorAlertKey, alert);
                                }
                            }
                            // 此优先级以下的阈值规则则忽略
                            break;
                        }
                    } catch (Exception e) {
                        log.warn(e.getMessage());
                    }
                }
            }
        }
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CollectRep(com.usthe.common.entity.message.CollectRep) Expression(com.googlecode.aviator.Expression) AlertDefine(com.usthe.common.entity.alerter.AlertDefine) Alert(com.usthe.common.entity.alerter.Alert) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 2 with AlertDefine

use of com.usthe.common.entity.alerter.AlertDefine in project hertzbeat by dromara.

the class AlertDefineController method getAlertDefine.

@GetMapping(path = "/{id}")
@ApiOperation(value = "查询告警定义", notes = "根据告警定义ID获取告警定义信息")
public ResponseEntity<Message<AlertDefine>> getAlertDefine(@ApiParam(value = "告警定义ID", example = "6565463543") @PathVariable("id") long id) {
    // 获取监控信息
    AlertDefine alertDefine = alertDefineService.getAlertDefine(id);
    Message.MessageBuilder<AlertDefine> messageBuilder = Message.builder();
    if (alertDefine == null) {
        messageBuilder.code(MONITOR_NOT_EXIST_CODE).msg("AlertDefine not exist.");
    } else {
        messageBuilder.data(alertDefine);
    }
    return ResponseEntity.ok(messageBuilder.build());
}
Also used : Message(com.usthe.common.entity.dto.Message) AlertDefine(com.usthe.common.entity.alerter.AlertDefine) GetMapping(org.springframework.web.bind.annotation.GetMapping) ApiOperation(io.swagger.annotations.ApiOperation)

Example 3 with AlertDefine

use of com.usthe.common.entity.alerter.AlertDefine in project hertzbeat by dromara.

the class AlertDefinesController method getAlertDefines.

@GetMapping
@ApiOperation(value = "查询告警定义列表", notes = "根据查询过滤项获取告警定义信息列表")
public ResponseEntity<Message<Page<AlertDefine>>> getAlertDefines(@ApiParam(value = "告警定义ID", example = "6565463543") @RequestParam(required = false) List<Long> ids, @ApiParam(value = "告警定义级别", example = "6565463543") @RequestParam(required = false) Byte priority, @ApiParam(value = "排序字段,默认id", example = "id") @RequestParam(defaultValue = "id") String sort, @ApiParam(value = "排序方式,asc:升序,desc:降序", example = "desc") @RequestParam(defaultValue = "desc") String order, @ApiParam(value = "列表当前分页", example = "0") @RequestParam(defaultValue = "0") int pageIndex, @ApiParam(value = "列表分页数量", example = "8") @RequestParam(defaultValue = "8") int pageSize) {
    Specification<AlertDefine> specification = (root, query, criteriaBuilder) -> {
        List<Predicate> andList = new ArrayList<>();
        if (ids != null && !ids.isEmpty()) {
            CriteriaBuilder.In<Long> inPredicate = criteriaBuilder.in(root.get("id"));
            for (long id : ids) {
                inPredicate.value(id);
            }
            andList.add(inPredicate);
        }
        if (priority != null) {
            Predicate predicate = criteriaBuilder.equal(root.get("priority"), priority);
            andList.add(predicate);
        }
        Predicate[] predicates = new Predicate[andList.size()];
        return criteriaBuilder.and(andList.toArray(predicates));
    };
    // 分页是必须的
    Sort sortExp = Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort));
    PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sortExp);
    Page<AlertDefine> alertDefinePage = alertDefineService.getAlertDefines(specification, pageRequest);
    Message<Page<AlertDefine>> message = new Message<>(alertDefinePage);
    return ResponseEntity.ok(message);
}
Also used : RequestParam(org.springframework.web.bind.annotation.RequestParam) ApiParam(io.swagger.annotations.ApiParam) Autowired(org.springframework.beans.factory.annotation.Autowired) PageRequest(org.springframework.data.domain.PageRequest) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Page(org.springframework.data.domain.Page) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) RestController(org.springframework.web.bind.annotation.RestController) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ApiOperation(io.swagger.annotations.ApiOperation) List(java.util.List) Message(com.usthe.common.entity.dto.Message) Specification(org.springframework.data.jpa.domain.Specification) Predicate(javax.persistence.criteria.Predicate) AlertDefineService(com.usthe.alert.service.AlertDefineService) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) GetMapping(org.springframework.web.bind.annotation.GetMapping) Sort(org.springframework.data.domain.Sort) ResponseEntity(org.springframework.http.ResponseEntity) Api(io.swagger.annotations.Api) AlertDefine(com.usthe.common.entity.alerter.AlertDefine) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) Message(com.usthe.common.entity.dto.Message) Page(org.springframework.data.domain.Page) Predicate(javax.persistence.criteria.Predicate) PageRequest(org.springframework.data.domain.PageRequest) AlertDefine(com.usthe.common.entity.alerter.AlertDefine) Sort(org.springframework.data.domain.Sort) ArrayList(java.util.ArrayList) List(java.util.List) GetMapping(org.springframework.web.bind.annotation.GetMapping) ApiOperation(io.swagger.annotations.ApiOperation)

Aggregations

AlertDefine (com.usthe.common.entity.alerter.AlertDefine)3 Message (com.usthe.common.entity.dto.Message)2 ApiOperation (io.swagger.annotations.ApiOperation)2 GetMapping (org.springframework.web.bind.annotation.GetMapping)2 Expression (com.googlecode.aviator.Expression)1 AlertDefineService (com.usthe.alert.service.AlertDefineService)1 Alert (com.usthe.common.entity.alerter.Alert)1 CollectRep (com.usthe.common.entity.message.CollectRep)1 Api (io.swagger.annotations.Api)1 ApiParam (io.swagger.annotations.ApiParam)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 List (java.util.List)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)1 Predicate (javax.persistence.criteria.Predicate)1 Autowired (org.springframework.beans.factory.annotation.Autowired)1 Page (org.springframework.data.domain.Page)1 PageRequest (org.springframework.data.domain.PageRequest)1 Sort (org.springframework.data.domain.Sort)1