Search in sources :

Example 1 with Monitor

use of com.usthe.common.entity.manager.Monitor in project hertzbeat by dromara.

the class MonitorController method deleteMonitor.

@DeleteMapping(path = "/{id}")
@ApiOperation(value = "Delete monitoring application based on monitoring ID", notes = "根据监控ID删除监控应用")
public ResponseEntity<Message<Void>> deleteMonitor(@ApiParam(value = "en: Monitor ID,zh: 监控ID", example = "6565463543") @PathVariable("id") final long id) {
    // delete monitor 删除监控
    Monitor monitor = monitorService.getMonitor(id);
    if (monitor == null) {
        return ResponseEntity.ok(new Message<>("The specified monitoring was not queried, please check whether the parameters are correct"));
    }
    monitorService.deleteMonitor(id);
    return ResponseEntity.ok(new Message<>("Delete success"));
}
Also used : Monitor(com.usthe.common.entity.manager.Monitor) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) ApiOperation(io.swagger.annotations.ApiOperation)

Example 2 with Monitor

use of com.usthe.common.entity.manager.Monitor in project hertzbeat by dromara.

the class MonitorsController method getMonitors.

@GetMapping
@ApiOperation(value = "Obtain a list of monitoring information based on query filter items", notes = "根据查询过滤项获取监控信息列表")
public ResponseEntity<Message<Page<Monitor>>> getMonitors(@ApiParam(value = "en: Monitor ID,zh: 监控ID", example = "6565463543") @RequestParam(required = false) final List<Long> ids, @ApiParam(value = "en: Monitor Type,zh: 监控类型", example = "linux") @RequestParam(required = false) final String app, @ApiParam(value = "en: Monitor Name,zh: 监控名称,模糊查询", example = "linux-127.0.0.1") @RequestParam(required = false) final String name, @ApiParam(value = "en: Monitor Host,zh: 监控Host,模糊查询", example = "127.0.0.1") @RequestParam(required = false) final String host, @ApiParam(value = "en: Monitor Status,zh: 监控状态 0:未监控,1:可用,2:不可用,3:不可达,4:挂起,9:全部状态", example = "1") @RequestParam(required = false) final Byte status, @ApiParam(value = "en: Sort Field,default id,zh: 排序字段,默认id", example = "name") @RequestParam(defaultValue = "id") final String sort, @ApiParam(value = "en: Sort by,zh: 排序方式,asc:升序,desc:降序", example = "desc") @RequestParam(defaultValue = "desc") final String order, @ApiParam(value = "en: List current page,zh: 列表当前分页", example = "0") @RequestParam(defaultValue = "0") int pageIndex, @ApiParam(value = "en: Number of list pagination,zh: 列表分页数量", example = "8") @RequestParam(defaultValue = "8") int pageSize) {
    Specification<Monitor> 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 (app != null && !"".equals(app)) {
            Predicate predicateApp = criteriaBuilder.equal(root.get("app"), app);
            andList.add(predicateApp);
        }
        if (status != null && status >= 0 && status < ALL_MONITOR_STATUS) {
            Predicate predicateStatus = criteriaBuilder.equal(root.get("status"), status);
            andList.add(predicateStatus);
        }
        Predicate[] andPredicates = new Predicate[andList.size()];
        Predicate andPredicate = criteriaBuilder.and(andList.toArray(andPredicates));
        List<Predicate> orList = new ArrayList<>();
        if (host != null && !"".equals(host)) {
            Predicate predicateHost = criteriaBuilder.like(root.get("host"), "%" + host + "%");
            orList.add(predicateHost);
        }
        if (name != null && !"".equals(name)) {
            Predicate predicateName = criteriaBuilder.like(root.get("name"), "%" + name + "%");
            orList.add(predicateName);
        }
        Predicate[] orPredicates = new Predicate[orList.size()];
        Predicate orPredicate = criteriaBuilder.or(orList.toArray(orPredicates));
        if (andPredicate.getExpressions().isEmpty() && orPredicate.getExpressions().isEmpty()) {
            return query.where().getRestriction();
        } else if (andPredicate.getExpressions().isEmpty()) {
            return query.where(orPredicate).getRestriction();
        } else if (orPredicate.getExpressions().isEmpty()) {
            return query.where(andPredicate).getRestriction();
        } else {
            return query.where(andPredicate, orPredicate).getRestriction();
        }
    };
    // Pagination is a must         分页是必须的
    Sort sortExp = Sort.by(new Sort.Order(Sort.Direction.fromString(order), sort));
    PageRequest pageRequest = PageRequest.of(pageIndex, pageSize, sortExp);
    Page<Monitor> monitorPage = monitorService.getMonitors(specification, pageRequest);
    Message<Page<Monitor>> message = new Message<>(monitorPage);
    return ResponseEntity.ok(message);
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) Monitor(com.usthe.common.entity.manager.Monitor) 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) MonitorService(com.usthe.manager.service.MonitorService) Message(com.usthe.common.entity.dto.Message) Specification(org.springframework.data.jpa.domain.Specification) Predicate(javax.persistence.criteria.Predicate) 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) 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) Monitor(com.usthe.common.entity.manager.Monitor) 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)

Example 3 with Monitor

use of com.usthe.common.entity.manager.Monitor 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)

Example 4 with Monitor

use of com.usthe.common.entity.manager.Monitor in project hertzbeat by dromara.

the class MonitorServiceImpl method deleteMonitor.

@Override
@Transactional(rollbackFor = Exception.class)
public void deleteMonitor(long id) throws RuntimeException {
    Optional<Monitor> monitorOptional = monitorDao.findById(id);
    if (monitorOptional.isPresent()) {
        Monitor monitor = monitorOptional.get();
        monitorDao.deleteById(id);
        paramDao.deleteParamsByMonitorId(id);
        alertDefineBindDao.deleteAlertDefineMonitorBindsByMonitorIdEquals(id);
        collectJobService.cancelAsyncCollectJob(monitor.getJobId());
    }
}
Also used : Monitor(com.usthe.common.entity.manager.Monitor) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with Monitor

use of com.usthe.common.entity.manager.Monitor in project hertzbeat by dromara.

the class MonitorServiceImpl method validate.

@Override
@Transactional(readOnly = true)
public void validate(MonitorDto monitorDto, Boolean isModify) throws IllegalArgumentException {
    // The request monitoring parameter matches the monitoring parameter definition mapping check
    // 请求监控参数与监控参数定义映射校验匹配
    Monitor monitor = monitorDto.getMonitor();
    monitor.setHost(monitor.getHost().trim());
    monitor.setName(monitor.getName().trim());
    Map<String, Param> paramMap = monitorDto.getParams().stream().peek(param -> {
        param.setMonitorId(monitor.getId());
        String value = param.getValue() == null ? null : param.getValue().trim();
        param.setValue(value);
    }).collect(Collectors.toMap(Param::getField, param -> param));
    // Check name uniqueness    校验名称唯一性
    if (isModify != null) {
        Optional<Monitor> monitorOptional = monitorDao.findMonitorByNameEquals(monitor.getName());
        if (monitorOptional.isPresent()) {
            Monitor existMonitor = monitorOptional.get();
            if (isModify) {
                if (!existMonitor.getId().equals(monitor.getId())) {
                    throw new IllegalArgumentException("监控名称不能重复!");
                }
            } else {
                throw new IllegalArgumentException("监控名称不能重复!");
            }
        }
    }
    // todo 校验标签
    if (monitor.getTags() != null) {
        monitor.setTags(monitor.getTags().stream().distinct().collect(Collectors.toList()));
    }
    // Parameter definition structure verification  参数定义结构校验
    List<ParamDefine> paramDefines = appService.getAppParamDefines(monitorDto.getMonitor().getApp());
    if (paramDefines != null) {
        for (ParamDefine paramDefine : paramDefines) {
            String field = paramDefine.getField();
            Param param = paramMap.get(field);
            if (paramDefine.isRequired() && (param == null || param.getValue() == null)) {
                throw new IllegalArgumentException("Params field " + field + " is required.");
            }
            if (param != null && param.getValue() != null && !"".equals(param.getValue())) {
                switch(paramDefine.getType()) {
                    case "number":
                        double doubleValue;
                        try {
                            doubleValue = Double.parseDouble(param.getValue());
                        } catch (Exception e) {
                            throw new IllegalArgumentException("Params field " + field + " type " + paramDefine.getType() + " is invalid.");
                        }
                        if (paramDefine.getRange() != null) {
                            if (!IntervalExpressionUtil.validNumberIntervalExpress(doubleValue, paramDefine.getRange())) {
                                throw new IllegalArgumentException("Params field " + field + " type " + paramDefine.getType() + " over range " + paramDefine.getRange());
                            }
                        }
                        param.setType(CommonConstants.PARAM_TYPE_NUMBER);
                        break;
                    case "textarea":
                    case "text":
                        Short limit = paramDefine.getLimit();
                        if (limit != null) {
                            if (param.getValue() != null && param.getValue().length() > limit) {
                                throw new IllegalArgumentException("Params field " + field + " type " + paramDefine.getType() + " over limit " + limit);
                            }
                        }
                        break;
                    case "host":
                        String hostValue = param.getValue();
                        if (!IpDomainUtil.validateIpDomain(hostValue)) {
                            throw new IllegalArgumentException("Params field " + field + " value " + hostValue + " is invalid host value.");
                        }
                        break;
                    case "password":
                        // The plaintext password needs to be encrypted for transmission and storage
                        // 明文密码需加密传输存储
                        String passwordValue = param.getValue();
                        if (!AesUtil.isCiphertext(passwordValue)) {
                            passwordValue = AesUtil.aesEncode(passwordValue);
                            param.setValue(passwordValue);
                        }
                        param.setType(CommonConstants.PARAM_TYPE_PASSWORD);
                        break;
                    case "boolean":
                        // boolean check
                        String booleanValue = param.getValue();
                        try {
                            Boolean.parseBoolean(booleanValue);
                        } catch (Exception e) {
                            throw new IllegalArgumentException("Params field " + field + " value " + booleanValue + " is invalid boolean value.");
                        }
                        break;
                    case "radio":
                        // radio single value check  radio单选值校验
                        List<ParamDefine.Option> options = paramDefine.getOptions();
                        boolean invalid = true;
                        if (options != null) {
                            for (ParamDefine.Option option : options) {
                                if (param.getValue().equalsIgnoreCase(option.getValue())) {
                                    invalid = false;
                                    break;
                                }
                            }
                        }
                        if (invalid) {
                            throw new IllegalArgumentException("Params field " + field + " value " + param.getValue() + " is invalid option value");
                        }
                        break;
                    case "checkbox":
                        // todo checkbox校验
                        break;
                    case "key-value":
                        // todo key-value校验
                        break;
                    // 更多参数定义与实际值格式校验
                    default:
                        throw new IllegalArgumentException("ParamDefine type " + paramDefine.getType() + " is invalid.");
                }
            }
        }
    }
}
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) MonitorDatabaseException(com.usthe.manager.support.exception.MonitorDatabaseException) MonitorDetectException(com.usthe.manager.support.exception.MonitorDetectException) ParamDefine(com.usthe.common.entity.manager.ParamDefine) Monitor(com.usthe.common.entity.manager.Monitor) Param(com.usthe.common.entity.manager.Param) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

Monitor (com.usthe.common.entity.manager.Monitor)13 Transactional (org.springframework.transaction.annotation.Transactional)9 Job (com.usthe.common.entity.job.Job)8 Param (com.usthe.common.entity.manager.Param)8 Autowired (org.springframework.beans.factory.annotation.Autowired)8 CollectJobService (com.usthe.collector.dispatch.entrance.internal.CollectJobService)7 Configmap (com.usthe.common.entity.job.Configmap)7 MonitorDao (com.usthe.manager.dao.MonitorDao)7 ParamDao (com.usthe.manager.dao.ParamDao)7 MonitorDto (com.usthe.manager.pojo.dto.MonitorDto)7 MonitorService (com.usthe.manager.service.MonitorService)7 Collectors (java.util.stream.Collectors)7 Slf4j (lombok.extern.slf4j.Slf4j)7 Page (org.springframework.data.domain.Page)7 PageRequest (org.springframework.data.domain.PageRequest)7 Specification (org.springframework.data.jpa.domain.Specification)7 Service (org.springframework.stereotype.Service)7 AlertDefineBindDao (com.usthe.alert.dao.AlertDefineBindDao)6 Metrics (com.usthe.common.entity.job.Metrics)6 ParamDefine (com.usthe.common.entity.manager.ParamDefine)6