Kaynağa Gözat

普罗米修斯关于自动发现相关功能

wukai 8 ay önce
ebeveyn
işleme
a3fdfae603

+ 62 - 0
jjt-admin/src/test/java/com/test/PrometheusTest.java

@@ -0,0 +1,62 @@
+package com.test;
+
+import cn.hutool.http.HttpRequest;
+import cn.hutool.http.HttpResponse;
+import cn.hutool.http.HttpUtil;
+import cn.hutool.http.Method;
+import cn.hutool.json.JSONArray;
+import cn.hutool.json.JSONUtil;
+import com.jjt.common.utils.StringUtils;
+import com.jjt.common.utils.sign.Base64;
+import org.yaml.snakeyaml.util.UriEncoder;
+
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * HttpTest$
+ *
+ * @author wukai
+ * @date 2024/8/19 15:18
+ */
+public class PrometheusTest {
+
+    //    public static void main(String[] args) {
+//        String auth = "admin:123456";
+//        System.err.println(Base64.encode(auth.getBytes()));
+//    }
+    public static void main(String[] args) {
+        String param = "node_cpu_seconds_total{mode=\"idle\"}";
+        String uri = "http://192.168.188.66:9090/api/v1/query";
+        param = UriEncoder.encode(param);
+
+        Map<String, Object> map = new HashMap<>(16);
+        map.put("query", param);
+        HttpRequest request = HttpUtil.createPost(uri);
+        request.setMethod(Method.GET);
+        String auth = "admin:123456";
+        if (StringUtils.isNotEmpty(auth)) {
+            String baseAuth = "Basic " + Base64.encode(auth.getBytes());
+            System.err.println(baseAuth);
+            request.header("Authorization", baseAuth);
+        }
+        request.form(map);
+        request.setConnectionTimeout(2000);
+        try (HttpResponse execute = request.execute()) {
+            if (!execute.isOk()) {
+                throw new RuntimeException("status:" + execute.getStatus() + "\tres:" + execute.body());
+            }
+            String res = new String(execute.body().getBytes(), StandardCharsets.UTF_8);
+            System.err.println(res);
+            cn.hutool.json.JSONObject object = JSONUtil.parseObj(res, true);
+            JSONArray metric = object.getByPath("data.result", JSONArray.class);
+                System.err.println(metric.getByPath("metric.cpu", String.class));
+            for (int i = 0; i < metric.size(); i++) {
+                System.err.println(metric.getJSONObject(i).getByPath("metric.cpu", String.class));
+            }
+        } catch (Exception e) {
+        }
+
+    }
+}

+ 12 - 4
jjt-biz/src/main/java/com/jjt/biz/controller/BizObjController.java

@@ -21,11 +21,9 @@ import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletResponse;
-import java.text.DecimalFormat;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Random;
 import java.util.stream.Collectors;
 
 /**
@@ -91,7 +89,7 @@ public class BizObjController extends BaseController {
 //        Random r = new Random();
 //        float f = r.nextFloat() * 100;
 //        return AjaxResult.success(Float.parseFloat(df.format(f)));
-        Float value=prometheusService.query(exp);
+        Float value = prometheusService.query(exp);
         if (value != null) {
             return success(value);
         } else {
@@ -117,10 +115,20 @@ public class BizObjController extends BaseController {
     @ApiOperation("添加指标")
     @GetMapping("/metrics/add/{objId}")
     public AjaxResult metricsAdd(@ApiParam(value = "对象ID", required = true) @PathVariable("objId") Long objId, @ApiParam(value = "指标ID数组", required = true) Long[] metricsIds) {
-
         return success(metricsService.insertMetricsDetails(objId, metricsIds));
     }
 
+    @ApiOperation("完成自定义指标配置")
+    @GetMapping("/metrics/conf/{objId}")
+    public AjaxResult metricsConf(@ApiParam(value = "对象ID", required = true) @PathVariable("objId") Long objId) {
+        boolean flag = metricsService.insertMc(objId);
+        if (flag) {
+            return success();
+        } else {
+            return error("指标未配置完成");
+        }
+    }
+
     /**
      * 查询业务对象列表
      */

+ 5 - 4
jjt-biz/src/main/java/com/jjt/biz/controller/MetricsTplController.java

@@ -48,7 +48,7 @@ public class MetricsTplController extends BaseController {
      */
     @ApiOperation("导出指标模板列表")
     @PreAuthorize("@ss.hasPermi('metrics:tpl:export')")
-    @Log(title = "指标模板" , businessType = BusinessType.EXPORT)
+    @Log(title = "指标模板", businessType = BusinessType.EXPORT)
     @PostMapping("/export")
     public void export(HttpServletResponse response, MetricsTpl metricsTpl) {
         List<MetricsTpl> list = metricsTplService.selectMetricsTplList(metricsTpl);
@@ -71,9 +71,10 @@ public class MetricsTplController extends BaseController {
      */
     @ApiOperation("新增指标模板")
     @PreAuthorize("@ss.hasPermi('metrics:tpl:add')")
-    @Log(title = "指标模板" , businessType = BusinessType.INSERT)
+    @Log(title = "指标模板", businessType = BusinessType.INSERT)
     @PostMapping
     public AjaxResult add(@RequestBody MetricsTpl metricsTpl) {
+        metricsTpl.setConfStatus("N");
         metricsTpl.setCreateBy(SecurityUtils.getUsername());
         return toAjax(metricsTplService.insertMetricsTpl(metricsTpl));
     }
@@ -83,7 +84,7 @@ public class MetricsTplController extends BaseController {
      */
     @ApiOperation("修改指标模板")
     @PreAuthorize("@ss.hasPermi('metrics:tpl:edit')")
-    @Log(title = "指标模板" , businessType = BusinessType.UPDATE)
+    @Log(title = "指标模板", businessType = BusinessType.UPDATE)
     @PutMapping
     public AjaxResult edit(@RequestBody MetricsTpl metricsTpl) {
         metricsTpl.setUpdateBy(SecurityUtils.getUsername());
@@ -95,7 +96,7 @@ public class MetricsTplController extends BaseController {
      */
     @ApiOperation("删除指标模板")
     @PreAuthorize("@ss.hasPermi('metrics:tpl:remove')")
-    @Log(title = "指标模板" , businessType = BusinessType.DELETE)
+    @Log(title = "指标模板", businessType = BusinessType.DELETE)
     @DeleteMapping("/{tplIds}")
     public AjaxResult remove(@PathVariable Long[] tplIds) {
         return toAjax(metricsTplService.deleteMetricsTplByTplIds(tplIds));

+ 6 - 3
jjt-biz/src/main/java/com/jjt/biz/controller/MetricsTplDetailController.java

@@ -126,13 +126,16 @@ public class MetricsTplDetailController extends BaseController {
         int i = metricsTplDetailService.updateMetricsTplDetail(metricsTplDetail);
         String sql = "select count(*) num from metrics_tpl_detail where tpl_id=? and (data_exp is null or DATA_EXP ='')";
         Integer num = jdbcTemplate.queryForObject(sql, Integer.class, metricsTplDetail.getTplId());
+        MetricsTpl tpl = new MetricsTpl();
+        tpl.setTplId(metricsTplDetail.getTplId());
         if (num == 0) {
-            MetricsTpl tpl = new MetricsTpl();
-            tpl.setTplId(metricsTplDetail.getTplId());
             tpl.setConfStatus("Y");
             tplService.updateMetricsTpl(tpl);
+        } else {
+            tpl.setConfStatus("N");
+            tplService.updateMetricsTpl(tpl);
         }
-//        omService.update(metricsTplDetail);
+        omService.update(metricsTplDetail);
         return toAjax(i);
     }
 

+ 44 - 150
jjt-biz/src/main/java/com/jjt/biz/domain/BizObjMc.java

@@ -1,12 +1,11 @@
 package com.jjt.biz.domain;
 
 import com.baomidou.mybatisplus.annotation.TableId;
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
 import com.jjt.common.annotation.Excel;
 import com.jjt.common.core.domain.BaseEntity;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
 
 /**
  * 业务对象自定义指标对象 biz_obj_mc
@@ -15,199 +14,94 @@ import com.jjt.common.core.domain.BaseEntity;
  * @date 2024-10-09
  */
 @ApiModel(value = "BizObjMc", description = "业务对象自定义指标")
-public class BizObjMc extends BaseEntity
-{
+@Data
+public class BizObjMc extends BaseEntity {
     private static final long serialVersionUID = 1L;
 
-    /** 明细ID */
+    /**
+     * 明细ID
+     */
     @ApiModelProperty("明细ID")
     @TableId
     private Long mcId;
 
-    /** 对象ID */
+    /**
+     * 对象ID
+     */
     @ApiModelProperty("对象ID")
     @Excel(name = "对象ID")
     private Long objId;
 
-    /** 指标ID */
+    /**
+     * 指标ID
+     */
     @ApiModelProperty("指标ID")
     @Excel(name = "指标ID")
     private Long metricsId;
 
-    /** 指标编码 */
+    @ApiModelProperty("指标名称")
+    @Excel(name = "指标名称")
+    private String metricsName;
+    /**
+     * 指标编码
+     */
     @ApiModelProperty("指标编码")
     @Excel(name = "指标编码")
     private String metricsCode;
 
-    /** 告警-低 */
+    /**
+     * 告警-低
+     */
     @ApiModelProperty("告警-低")
     @Excel(name = "告警-低")
     private String alarmLow;
 
-    /** 告警-中 */
+    /**
+     * 告警-中
+     */
     @ApiModelProperty("告警-中")
     @Excel(name = "告警-中")
     private String alarmMid;
 
-    /** 告警-高 */
+    /**
+     * 告警-高
+     */
     @ApiModelProperty("告警-高")
     @Excel(name = "告警-高")
     private String alarmHigh;
 
-    /** 健康度事件 */
+    /**
+     * 健康度事件
+     */
     @ApiModelProperty("健康度事件")
     @Excel(name = "健康度事件")
     private String event;
 
-    /** 数据获取表达式 */
+    /**
+     * 数据获取表达式
+     */
     @ApiModelProperty("数据获取表达式")
     @Excel(name = "数据获取表达式")
     private String dataExp;
 
-    /** 自动发现关键字 */
+    /**
+     * 自动发现关键字
+     */
     @ApiModelProperty("自动发现关键字")
     @Excel(name = "自动发现关键字")
     private String findKey;
 
-    /** 自动发现规则 */
+    /**
+     * 自动发现规则
+     */
     @ApiModelProperty("自动发现规则")
     @Excel(name = "自动发现规则")
     private String findRule;
 
-    /** 自动发现 */
+    /**
+     * 自动发现
+     */
     @ApiModelProperty("自动发现")
     @Excel(name = "自动发现")
     private String findFlag;
-
-    public void setMcId(Long mcId)
-    {
-        this.mcId = mcId;
-    }
-
-    public Long getMcId()
-    {
-        return mcId;
-    }
-    public void setObjId(Long objId)
-    {
-        this.objId = objId;
-    }
-
-    public Long getObjId()
-    {
-        return objId;
-    }
-    public void setMetricsId(Long metricsId)
-    {
-        this.metricsId = metricsId;
-    }
-
-    public Long getMetricsId()
-    {
-        return metricsId;
-    }
-    public void setMetricsCode(String metricsCode)
-    {
-        this.metricsCode = metricsCode;
-    }
-
-    public String getMetricsCode()
-    {
-        return metricsCode;
-    }
-    public void setAlarmLow(String alarmLow)
-    {
-        this.alarmLow = alarmLow;
-    }
-
-    public String getAlarmLow()
-    {
-        return alarmLow;
-    }
-    public void setAlarmMid(String alarmMid)
-    {
-        this.alarmMid = alarmMid;
-    }
-
-    public String getAlarmMid()
-    {
-        return alarmMid;
-    }
-    public void setAlarmHigh(String alarmHigh)
-    {
-        this.alarmHigh = alarmHigh;
-    }
-
-    public String getAlarmHigh()
-    {
-        return alarmHigh;
-    }
-    public void setEvent(String event)
-    {
-        this.event = event;
-    }
-
-    public String getEvent()
-    {
-        return event;
-    }
-    public void setDataExp(String dataExp)
-    {
-        this.dataExp = dataExp;
-    }
-
-    public String getDataExp()
-    {
-        return dataExp;
-    }
-    public void setFindKey(String findKey)
-    {
-        this.findKey = findKey;
-    }
-
-    public String getFindKey()
-    {
-        return findKey;
-    }
-    public void setFindRule(String findRule)
-    {
-        this.findRule = findRule;
-    }
-
-    public String getFindRule()
-    {
-        return findRule;
-    }
-    public void setFindFlag(String findFlag)
-    {
-        this.findFlag = findFlag;
-    }
-
-    public String getFindFlag()
-    {
-        return findFlag;
-    }
-
-    @Override
-    public String toString() {
-        return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
-            .append("mcId", getMcId())
-            .append("objId", getObjId())
-            .append("metricsId", getMetricsId())
-            .append("metricsCode", getMetricsCode())
-            .append("alarmLow", getAlarmLow())
-            .append("alarmMid", getAlarmMid())
-            .append("alarmHigh", getAlarmHigh())
-            .append("event", getEvent())
-            .append("dataExp", getDataExp())
-            .append("findKey", getFindKey())
-            .append("findRule", getFindRule())
-            .append("findFlag", getFindFlag())
-            .append("createBy", getCreateBy())
-            .append("createTime", getCreateTime())
-            .append("updateBy", getUpdateBy())
-            .append("updateTime", getUpdateTime())
-            .append("remark", getRemark())
-            .toString();
-    }
 }

+ 3 - 2
jjt-biz/src/main/java/com/jjt/biz/domain/BizObjTpl.java

@@ -6,8 +6,6 @@ import com.jjt.common.core.domain.BaseEntity;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 import lombok.Data;
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
 
 /**
  * 业务对象模板应用对象 biz_obj_tpl
@@ -43,4 +41,7 @@ public class BizObjTpl extends BaseEntity {
     @ApiModelProperty("模板ID")
     @Excel(name = "模板ID")
     private Long tplId;
+
+    @ApiModelProperty("指标数量")
+    private Long num;
 }

+ 8 - 0
jjt-biz/src/main/java/com/jjt/biz/service/IBizObjMetricsService.java

@@ -149,4 +149,12 @@ public interface IBizObjMetricsService {
      * @return 列表
      */
     String importMetrics(List<BizObjMetrics> metricsList, String userName);
+
+    /**
+     * 插入自定义指标
+     *
+     * @param objId 对象ID
+     * @return 结果
+     */
+    boolean insertMc(Long objId);
 }

+ 8 - 1
jjt-biz/src/main/java/com/jjt/biz/service/IPrometheusService.java

@@ -1,6 +1,6 @@
 package com.jjt.biz.service;
 
-import com.alibaba.fastjson2.JSONObject;
+import cn.hutool.json.JSONObject;
 
 /**
  * API接口
@@ -17,4 +17,11 @@ public interface IPrometheusService {
      */
     Float query(String param);
 
+    /**
+     * 自动发现查询
+     *
+     * @param param 参数
+     * @return json对象
+     */
+    JSONObject find(String param);
 }

+ 80 - 6
jjt-biz/src/main/java/com/jjt/biz/service/impl/BizObjMetricsServiceImpl.java

@@ -63,6 +63,8 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
     private IHlEventService eventService;
     @Resource
     private ISysConfigService configService;
+    @Resource
+    private IBizObjMcService mcService;
 
     /**
      * 查询业务对象指标
@@ -217,7 +219,7 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
                     ms.setAlarmHigh(d.getAlarmHigh());
                     ms.setEvent(d.getEvent());
 
-                    if (pp.getPpType().equals("REDIS")) {
+                    if ("REDIS".equals(pp.getPpType())) {
                         //redis需要将1s换成100ms 3s换成300ms 5s换成500ms
                         if (d.getMetricsCode().endsWith("1s")) {
                             ms.setMetricsName(ms.getMetricsName().replace("1s", "100ms"));
@@ -241,15 +243,35 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
                 ms.setMetricsId(d.getMetricsId());
                 ms.setMetricsName(d.getMetricsDef().getMetricsName());
                 ms.setMetricsCode(d.getMetricsCode());
-                if ("1".equals(d.getMetricsDef().getMetricsType())) {
-                    ms.setDataExp(d.getMetricsCode());
-                }
                 ms.setAlarmLow(d.getAlarmLow());
                 ms.setAlarmMid(d.getAlarmMid());
                 ms.setAlarmHigh(d.getAlarmHigh());
                 ms.setEvent(d.getEvent());
-                objMetrics.add(ms);
+                if ("1".equals(d.getMetricsDef().getMetricsType())) {
+                    ms.setDataExp(d.getMetricsCode());
+                } else {
+                    //如果是普罗米修斯,则需要处理公式
+                    ms.setDataExp(d.getDataExp().replace("${instance}", obj.getObjAddr()));
+                    if ("Y".equals(d.getFindFlag())) {
+                        //如果是自动发现
+                        cn.hutool.json.JSONObject jsonObject = prometheusService.find(d.getFindRule());
+                        cn.hutool.json.JSONArray metric = jsonObject.getByPath("data.result", cn.hutool.json.JSONArray.class);
+                        for (int i = 0; i < metric.size(); i++) {
+                            String v = metric.getJSONObject(i).getByPath("metric." + d.getFindKey(), String.class);
+                            String name = d.getMetricsDef().getMetricsName() + "{" + d.getFindKey() + "=" + v + "}";
+                            String dataExp = ms.getDataExp().replace("${key}", v);
+                            ms.setDataExp(dataExp);
+                            ms.setMetricsName(name);
+                            objMetrics.add(ms);
+                        }
+                    } else {
+                        objMetrics.add(ms);
+                    }
+                }
+
+
             }
+
         });
         try (SqlSession sqlSession = factory.openSession(ExecutorType.BATCH, false)) {
             BizObjMetricsMapper mapper = sqlSession.getMapper(BizObjMetricsMapper.class);
@@ -433,7 +455,7 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
 
         Random random = new Random();
         mList.stream().forEach(om -> {
-            double oldV=100d;
+            double oldV = 100d;
             if (om.getDValue() != null) {
                 oldV = om.getDValue().floatValue();
             }
@@ -533,6 +555,58 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
     }
 
     /**
+     * 插入自定义指标
+     *
+     * @param objId 对象ID
+     */
+    @Override
+    public boolean insertMc(Long objId) {
+        BizObj obj = objService.selectBizObjByObjId(objId);
+        BizObjMc query = new BizObjMc();
+        query.setObjId(objId);
+        List<BizObjMc> list = mcService.selectBizObjMcList(query);
+        List<BizObjMetrics> objMetrics = new ArrayList<>();
+        for (BizObjMc d : list) {
+            BizObjMetrics ms = new BizObjMetrics();
+            ms.setObjId(objId);
+            ms.setTplId(-1L);
+            ms.setMetricsId(d.getMetricsId());
+            ms.setMetricsName(d.getMetricsName());
+            ms.setMetricsCode(d.getMetricsCode());
+            ms.setAlarmLow(d.getAlarmLow());
+            ms.setAlarmMid(d.getAlarmMid());
+            ms.setAlarmHigh(d.getAlarmHigh());
+            ms.setEvent(d.getEvent());
+            if (StringUtils.isEmpty(d.getDataExp())) {
+                return false;
+            }
+            //如果是普罗米修斯,则需要处理公式
+            ms.setDataExp(d.getDataExp().replace("${instance}", obj.getObjAddr()));
+            if ("Y".equals(d.getFindFlag())) {
+                //如果是自动发现
+                cn.hutool.json.JSONObject jsonObject = prometheusService.find(d.getFindRule());
+                cn.hutool.json.JSONArray metric = jsonObject.getByPath("data.result", cn.hutool.json.JSONArray.class);
+                for (int i = 0; i < metric.size(); i++) {
+                    String v = metric.getJSONObject(i).getByPath("metric." + d.getFindKey(), String.class);
+                    String name = d.getMetricsName() + "{" + d.getFindKey() + "=" + v + "}";
+                    String dataExp = ms.getDataExp().replace("${key}", v);
+                    ms.setDataExp(dataExp);
+                    ms.setMetricsName(name);
+                    objMetrics.add(ms);
+                }
+            } else {
+                objMetrics.add(ms);
+            }
+        }
+        try (SqlSession sqlSession = factory.openSession(ExecutorType.BATCH, false)) {
+            BizObjMetricsMapper mapper = sqlSession.getMapper(BizObjMetricsMapper.class);
+            objMetrics.forEach(mapper::insertBizObjMetrics);
+            sqlSession.commit();
+        }
+        return true;
+    }
+
+    /**
      * 更新BIZ_OBJ_PP
      *
      * @param objId          对象ID

+ 61 - 27
jjt-biz/src/main/java/com/jjt/biz/service/impl/PrometheusServiceImpl.java

@@ -51,36 +51,70 @@ public class PrometheusServiceImpl implements IPrometheusService {
     @Override
     public Float query(String param) {
         if (StringUtils.isNotEmpty(param)) {
-            if (StringUtils.isNotEmpty(param)) {
-                String uri = baseUri() + "/api/v1/query";
-                param = UriEncoder.encode(param);
+            String uri = baseUri() + "/api/v1/query";
+            param = UriEncoder.encode(param);
 
-                Map<String, Object> map = new HashMap<>(16);
-                map.put("query", param);
-                HttpRequest request = HttpUtil.createPost(uri);
-                request.setMethod(Method.GET);
-                String auth = configService.selectConfigByKey("pm.param");
-                if (StringUtils.isNotEmpty(auth)) {
-                    String baseAuth = "Basic " + Base64.encode(auth.getBytes());
-                    request.header("Authorization", baseAuth);
+            Map<String, Object> map = new HashMap<>(16);
+            map.put("query", param);
+            HttpRequest request = HttpUtil.createPost(uri);
+            request.setMethod(Method.GET);
+            String auth = configService.selectConfigByKey("pm.param");
+            if (StringUtils.isNotEmpty(auth)) {
+                String baseAuth = "Basic " + Base64.encode(auth.getBytes());
+                request.header("Authorization", baseAuth);
+            }
+            request.form(map);
+            request.setConnectionTimeout(2000);
+            try (HttpResponse execute = request.execute()) {
+                if (!execute.isOk()) {
+                    throw new RuntimeException("status:" + execute.getStatus() + "\tres:" + execute.body());
                 }
-                request.form(map);
-                request.setConnectionTimeout(2000);
-                try (HttpResponse execute = request.execute()) {
-                    if (!execute.isOk()) {
-                        throw new RuntimeException("status:" + execute.getStatus() + "\tres:" + execute.body());
-                    }
-                    String res = new String(execute.body().getBytes(), StandardCharsets.UTF_8);
-                    JSONObject object = JSONUtil.parseObj(res, true);
-                    JSONArray array = object.getJSONObject("data").getJSONArray("result");
-                    JSONArray value = array.getJSONObject(0).getJSONArray("value");
-                    DecimalFormat df = new DecimalFormat("#0.00");
-                    return Float.parseFloat(df.format(value.getFloat(1)));
-                } catch (Exception e) {
-                    log.error("调用prometheus接口失败, url=" + uri + ",param=" + param, e);
-                    return null;
+                String res = new String(execute.body().getBytes(), StandardCharsets.UTF_8);
+                JSONObject object = JSONUtil.parseObj(res, true);
+                JSONArray array = object.getJSONObject("data").getJSONArray("result");
+                JSONArray value = array.getJSONObject(0).getJSONArray("value");
+                DecimalFormat df = new DecimalFormat("#0.00");
+                return Float.parseFloat(df.format(value.getFloat(1)));
+            } catch (Exception e) {
+                log.error("调用prometheus接口失败, url=" + uri + ",param=" + param, e);
+                return null;
+            }
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * 自动发现查询
+     *
+     * @param param 参数
+     * @return json对象
+     */
+    @Override
+    public JSONObject find(String param) {
+        if (StringUtils.isNotEmpty(param)) {
+            String uri = baseUri() + "/api/v1/query";
+            param = UriEncoder.encode(param);
+
+            Map<String, Object> map = new HashMap<>(16);
+            map.put("query", param);
+            HttpRequest request = HttpUtil.createPost(uri);
+            request.setMethod(Method.GET);
+            String auth = configService.selectConfigByKey("pm.param");
+            if (StringUtils.isNotEmpty(auth)) {
+                String baseAuth = "Basic " + Base64.encode(auth.getBytes());
+                request.header("Authorization", baseAuth);
+            }
+            request.form(map);
+            request.setConnectionTimeout(2000);
+            try (HttpResponse execute = request.execute()) {
+                if (!execute.isOk()) {
+                    throw new RuntimeException("status:" + execute.getStatus() + "\tres:" + execute.body());
                 }
-            } else {
+                String res = new String(execute.body().getBytes(), StandardCharsets.UTF_8);
+                return JSONUtil.parseObj(res, true);
+            } catch (Exception e) {
+                log.error("调用prometheus接口失败, url=" + uri + ",param=" + param, e);
                 return null;
             }
         } else {

+ 200 - 181
jjt-biz/src/main/resources/mapper/biz/BizObjMcMapper.xml

@@ -5,221 +5,240 @@
 <mapper namespace="com.jjt.biz.mapper.BizObjMcMapper">
 
     <resultMap type="BizObjMc" id="BizObjMcResult">
-            <result property="mcId" column="MC_ID"/>
-            <result property="objId" column="OBJ_ID"/>
-            <result property="metricsId" column="METRICS_ID"/>
-            <result property="metricsCode" column="METRICS_CODE"/>
-            <result property="alarmLow" column="ALARM_LOW"/>
-            <result property="alarmMid" column="ALARM_MID"/>
-            <result property="alarmHigh" column="ALARM_HIGH"/>
-            <result property="event" column="EVENT"/>
-            <result property="dataExp" column="DATA_EXP"/>
-            <result property="findKey" column="FIND_KEY"/>
-            <result property="findRule" column="FIND_RULE"/>
-            <result property="findFlag" column="FIND_FLAG"/>
-            <result property="createBy" column="CREATE_BY"/>
-            <result property="createTime" column="CREATE_TIME"/>
-            <result property="updateBy" column="UPDATE_BY"/>
-            <result property="updateTime" column="UPDATE_TIME"/>
-            <result property="remark" column="REMARK"/>
+        <result property="mcId" column="MC_ID"/>
+        <result property="objId" column="OBJ_ID"/>
+        <result property="metricsId" column="METRICS_ID"/>
+        <result property="metricsName" column="METRICS_NAME"/>
+        <result property="metricsCode" column="METRICS_CODE"/>
+        <result property="alarmLow" column="ALARM_LOW"/>
+        <result property="alarmMid" column="ALARM_MID"/>
+        <result property="alarmHigh" column="ALARM_HIGH"/>
+        <result property="event" column="EVENT"/>
+        <result property="dataExp" column="DATA_EXP"/>
+        <result property="findKey" column="FIND_KEY"/>
+        <result property="findRule" column="FIND_RULE"/>
+        <result property="findFlag" column="FIND_FLAG"/>
+        <result property="createBy" column="CREATE_BY"/>
+        <result property="createTime" column="CREATE_TIME"/>
+        <result property="updateBy" column="UPDATE_BY"/>
+        <result property="updateTime" column="UPDATE_TIME"/>
+        <result property="remark" column="REMARK"/>
     </resultMap>
 
     <sql id="selectBizObjMcVo">
-        select MC_ID, OBJ_ID, METRICS_ID, METRICS_CODE, ALARM_LOW, ALARM_MID, ALARM_HIGH, EVENT, DATA_EXP, FIND_KEY, FIND_RULE, FIND_FLAG, CREATE_BY, CREATE_TIME, UPDATE_BY, UPDATE_TIME, REMARK
+        select MC_ID,
+               OBJ_ID,
+               METRICS_ID,
+               METRICS_NAME,
+               METRICS_CODE,
+               ALARM_LOW,
+               ALARM_MID,
+               ALARM_HIGH,
+               EVENT,
+               DATA_EXP,
+               FIND_KEY,
+               FIND_RULE,
+               FIND_FLAG,
+               CREATE_BY,
+               CREATE_TIME,
+               UPDATE_BY,
+               UPDATE_TIME,
+               REMARK
         from biz_obj_mc
     </sql>
 
     <select id="selectBizObjMcList" parameterType="BizObjMc" resultMap="BizObjMcResult">
         <include refid="selectBizObjMcVo"/>
         <where>
-                        <if test="objId != null ">
-                            and OBJ_ID = #{objId}
-                        </if>
-                        <if test="metricsId != null ">
-                            and METRICS_ID = #{metricsId}
-                        </if>
-                        <if test="metricsCode != null  and metricsCode != ''">
-                            and METRICS_CODE = #{metricsCode}
-                        </if>
-                        <if test="alarmLow != null  and alarmLow != ''">
-                            and ALARM_LOW = #{alarmLow}
-                        </if>
-                        <if test="alarmMid != null  and alarmMid != ''">
-                            and ALARM_MID = #{alarmMid}
-                        </if>
-                        <if test="alarmHigh != null  and alarmHigh != ''">
-                            and ALARM_HIGH = #{alarmHigh}
-                        </if>
-                        <if test="event != null  and event != ''">
-                            and EVENT = #{event}
-                        </if>
-                        <if test="dataExp != null  and dataExp != ''">
-                            and DATA_EXP = #{dataExp}
-                        </if>
-                        <if test="findKey != null  and findKey != ''">
-                            and FIND_KEY = #{findKey}
-                        </if>
-                        <if test="findRule != null  and findRule != ''">
-                            and FIND_RULE = #{findRule}
-                        </if>
-                        <if test="findFlag != null  and findFlag != ''">
-                            and FIND_FLAG = #{findFlag}
-                        </if>
-                        <if test="createBy != null  and createBy != ''">
-                            and CREATE_BY = #{createBy}
-                        </if>
-                        <if test="createTime != null ">
-                            and CREATE_TIME = #{createTime}
-                        </if>
-                        <if test="updateBy != null  and updateBy != ''">
-                            and UPDATE_BY = #{updateBy}
-                        </if>
-                        <if test="updateTime != null ">
-                            and UPDATE_TIME = #{updateTime}
-                        </if>
-                        <if test="remark != null  and remark != ''">
-                            and REMARK = #{remark}
-                        </if>
+            <if test="objId != null ">
+                and OBJ_ID = #{objId}
+            </if>
+            <if test="metricsId != null ">
+                and METRICS_ID = #{metricsId}
+            </if>
+            <if test="metricsCode != null  and metricsCode != ''">
+                and METRICS_CODE = #{metricsCode}
+            </if>
+            <if test="alarmLow != null  and alarmLow != ''">
+                and ALARM_LOW = #{alarmLow}
+            </if>
+            <if test="alarmMid != null  and alarmMid != ''">
+                and ALARM_MID = #{alarmMid}
+            </if>
+            <if test="alarmHigh != null  and alarmHigh != ''">
+                and ALARM_HIGH = #{alarmHigh}
+            </if>
+            <if test="event != null  and event != ''">
+                and EVENT = #{event}
+            </if>
+            <if test="dataExp != null  and dataExp != ''">
+                and DATA_EXP = #{dataExp}
+            </if>
+            <if test="findKey != null  and findKey != ''">
+                and FIND_KEY = #{findKey}
+            </if>
+            <if test="findRule != null  and findRule != ''">
+                and FIND_RULE = #{findRule}
+            </if>
+            <if test="findFlag != null  and findFlag != ''">
+                and FIND_FLAG = #{findFlag}
+            </if>
+            <if test="createBy != null  and createBy != ''">
+                and CREATE_BY = #{createBy}
+            </if>
+            <if test="createTime != null ">
+                and CREATE_TIME = #{createTime}
+            </if>
+            <if test="updateBy != null  and updateBy != ''">
+                and UPDATE_BY = #{updateBy}
+            </if>
+            <if test="updateTime != null ">
+                and UPDATE_TIME = #{updateTime}
+            </if>
+            <if test="remark != null  and remark != ''">
+                and REMARK = #{remark}
+            </if>
         </where>
     </select>
 
     <select id="selectBizObjMcByMcId" parameterType="Long"
             resultMap="BizObjMcResult">
-            <include refid="selectBizObjMcVo"/>
-            where MC_ID = #{mcId}
+        <include refid="selectBizObjMcVo"/>
+        where MC_ID = #{mcId}
     </select>
 
     <insert id="insertBizObjMc" parameterType="BizObjMc" useGeneratedKeys="true"
             keyProperty="mcId">
         insert into biz_obj_mc
         <trim prefix="(" suffix=")" suffixOverrides=",">
-                    <if test="objId != null">OBJ_ID,
-                    </if>
-                    <if test="metricsId != null">METRICS_ID,
-                    </if>
-                    <if test="metricsCode != null">METRICS_CODE,
-                    </if>
-                    <if test="alarmLow != null">ALARM_LOW,
-                    </if>
-                    <if test="alarmMid != null">ALARM_MID,
-                    </if>
-                    <if test="alarmHigh != null">ALARM_HIGH,
-                    </if>
-                    <if test="event != null">EVENT,
-                    </if>
-                    <if test="dataExp != null">DATA_EXP,
-                    </if>
-                    <if test="findKey != null">FIND_KEY,
-                    </if>
-                    <if test="findRule != null">FIND_RULE,
-                    </if>
-                    <if test="findFlag != null">FIND_FLAG,
-                    </if>
-                    <if test="createBy != null">CREATE_BY,
-                    </if>
-                    <if test="createTime != null">CREATE_TIME,
-                    </if>
-                    <if test="updateBy != null">UPDATE_BY,
-                    </if>
-                    <if test="updateTime != null">UPDATE_TIME,
-                    </if>
-                    <if test="remark != null">REMARK,
-                    </if>
+            <if test="objId != null">OBJ_ID,
+            </if>
+            <if test="metricsId != null">METRICS_ID,
+            </if>
+            <if test="metricsCode != null">METRICS_CODE,
+            </if>
+            <if test="alarmLow != null">ALARM_LOW,
+            </if>
+            <if test="alarmMid != null">ALARM_MID,
+            </if>
+            <if test="alarmHigh != null">ALARM_HIGH,
+            </if>
+            <if test="event != null">EVENT,
+            </if>
+            <if test="dataExp != null">DATA_EXP,
+            </if>
+            <if test="findKey != null">FIND_KEY,
+            </if>
+            <if test="findRule != null">FIND_RULE,
+            </if>
+            <if test="findFlag != null">FIND_FLAG,
+            </if>
+            <if test="createBy != null">CREATE_BY,
+            </if>
+            <if test="createTime != null">CREATE_TIME,
+            </if>
+            <if test="updateBy != null">UPDATE_BY,
+            </if>
+            <if test="updateTime != null">UPDATE_TIME,
+            </if>
+            <if test="remark != null">REMARK,
+            </if>
         </trim>
         <trim prefix="values (" suffix=")" suffixOverrides=",">
-                    <if test="objId != null">#{objId},
-                    </if>
-                    <if test="metricsId != null">#{metricsId},
-                    </if>
-                    <if test="metricsCode != null">#{metricsCode},
-                    </if>
-                    <if test="alarmLow != null">#{alarmLow},
-                    </if>
-                    <if test="alarmMid != null">#{alarmMid},
-                    </if>
-                    <if test="alarmHigh != null">#{alarmHigh},
-                    </if>
-                    <if test="event != null">#{event},
-                    </if>
-                    <if test="dataExp != null">#{dataExp},
-                    </if>
-                    <if test="findKey != null">#{findKey},
-                    </if>
-                    <if test="findRule != null">#{findRule},
-                    </if>
-                    <if test="findFlag != null">#{findFlag},
-                    </if>
-                    <if test="createBy != null">#{createBy},
-                    </if>
-                    <if test="createTime != null">#{createTime},
-                    </if>
-                    <if test="updateBy != null">#{updateBy},
-                    </if>
-                    <if test="updateTime != null">#{updateTime},
-                    </if>
-                    <if test="remark != null">#{remark},
-                    </if>
+            <if test="objId != null">#{objId},
+            </if>
+            <if test="metricsId != null">#{metricsId},
+            </if>
+            <if test="metricsCode != null">#{metricsCode},
+            </if>
+            <if test="alarmLow != null">#{alarmLow},
+            </if>
+            <if test="alarmMid != null">#{alarmMid},
+            </if>
+            <if test="alarmHigh != null">#{alarmHigh},
+            </if>
+            <if test="event != null">#{event},
+            </if>
+            <if test="dataExp != null">#{dataExp},
+            </if>
+            <if test="findKey != null">#{findKey},
+            </if>
+            <if test="findRule != null">#{findRule},
+            </if>
+            <if test="findFlag != null">#{findFlag},
+            </if>
+            <if test="createBy != null">#{createBy},
+            </if>
+            <if test="createTime != null">#{createTime},
+            </if>
+            <if test="updateBy != null">#{updateBy},
+            </if>
+            <if test="updateTime != null">#{updateTime},
+            </if>
+            <if test="remark != null">#{remark},
+            </if>
         </trim>
     </insert>
 
     <update id="updateBizObjMc" parameterType="BizObjMc">
         update biz_obj_mc
         <trim prefix="SET" suffixOverrides=",">
-                    <if test="objId != null">OBJ_ID =
-                        #{objId},
-                    </if>
-                    <if test="metricsId != null">METRICS_ID =
-                        #{metricsId},
-                    </if>
-                    <if test="metricsCode != null">METRICS_CODE =
-                        #{metricsCode},
-                    </if>
-                    <if test="alarmLow != null">ALARM_LOW =
-                        #{alarmLow},
-                    </if>
-                    <if test="alarmMid != null">ALARM_MID =
-                        #{alarmMid},
-                    </if>
-                    <if test="alarmHigh != null">ALARM_HIGH =
-                        #{alarmHigh},
-                    </if>
-                    <if test="event != null">EVENT =
-                        #{event},
-                    </if>
-                    <if test="dataExp != null">DATA_EXP =
-                        #{dataExp},
-                    </if>
-                    <if test="findKey != null">FIND_KEY =
-                        #{findKey},
-                    </if>
-                    <if test="findRule != null">FIND_RULE =
-                        #{findRule},
-                    </if>
-                    <if test="findFlag != null">FIND_FLAG =
-                        #{findFlag},
-                    </if>
-                    <if test="createBy != null">CREATE_BY =
-                        #{createBy},
-                    </if>
-                    <if test="createTime != null">CREATE_TIME =
-                        #{createTime},
-                    </if>
-                    <if test="updateBy != null">UPDATE_BY =
-                        #{updateBy},
-                    </if>
-                    <if test="updateTime != null">UPDATE_TIME =
-                        #{updateTime},
-                    </if>
-                    <if test="remark != null">REMARK =
-                        #{remark},
-                    </if>
+            <if test="objId != null">OBJ_ID =
+                #{objId},
+            </if>
+            <if test="metricsId != null">METRICS_ID =
+                #{metricsId},
+            </if>
+            <if test="metricsCode != null">METRICS_CODE =
+                #{metricsCode},
+            </if>
+            <if test="alarmLow != null">ALARM_LOW =
+                #{alarmLow},
+            </if>
+            <if test="alarmMid != null">ALARM_MID =
+                #{alarmMid},
+            </if>
+            <if test="alarmHigh != null">ALARM_HIGH =
+                #{alarmHigh},
+            </if>
+            <if test="event != null">EVENT =
+                #{event},
+            </if>
+            <if test="dataExp != null">DATA_EXP =
+                #{dataExp},
+            </if>
+            <if test="findKey != null">FIND_KEY =
+                #{findKey},
+            </if>
+            <if test="findRule != null">FIND_RULE =
+                #{findRule},
+            </if>
+            <if test="findFlag != null">FIND_FLAG =
+                #{findFlag},
+            </if>
+            <if test="createBy != null">CREATE_BY =
+                #{createBy},
+            </if>
+            <if test="createTime != null">CREATE_TIME =
+                #{createTime},
+            </if>
+            <if test="updateBy != null">UPDATE_BY =
+                #{updateBy},
+            </if>
+            <if test="updateTime != null">UPDATE_TIME =
+                #{updateTime},
+            </if>
+            <if test="remark != null">REMARK =
+                #{remark},
+            </if>
         </trim>
         where MC_ID = #{mcId}
     </update>
 
     <delete id="deleteBizObjMcByMcId" parameterType="Long">
         delete
-        from biz_obj_mc where MC_ID = #{mcId}
+        from biz_obj_mc
+        where MC_ID = #{mcId}
     </delete>
 
     <delete id="deleteBizObjMcByMcIds" parameterType="String">

+ 2 - 0
jjt-biz/src/main/resources/mapper/obj/BizObjTplMapper.xml

@@ -9,6 +9,7 @@
         <result property="objId" column="OBJ_ID"/>
         <result property="tplId" column="TPL_ID"/>
         <result property="tplName" column="TPL_NAME"/>
+        <result property="num" column="NUM"/>
         <result property="createBy" column="CREATE_BY"/>
         <result property="createTime" column="CREATE_TIME"/>
         <result property="updateBy" column="UPDATE_BY"/>
@@ -22,6 +23,7 @@
                      a.OBJ_ID,
                      a.TPL_ID,
                      b.tpl_name,
+                     (select count(*) from METRICS_TPL_DETAIL where tpl_id = a.tpl_id) num,
                      a.CREATE_BY,
                      a.CREATE_TIME,
                      a.UPDATE_BY,