Forráskód Böngészése

搞定链路分析相关

wukai 7 hónapja
szülő
commit
d3b5756964

+ 135 - 0
jjt-admin/src/test/java/com/test/PinpointTest.java

@@ -0,0 +1,135 @@
+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.JSONObject;
+import cn.hutool.json.JSONUtil;
+import com.jjt.common.utils.DateUtils;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * HttpTest$
+ *
+ * @author wukai
+ * @date 2024/8/19 15:18
+ */
+public class PinpointTest {
+
+    public static void main(String[] args) {
+        agentList();
+    }
+
+    public static void agentList() {
+        String uri = "http://192.168.188.66:8080/getAgentList.pinpoint";
+        Map<String, Object> map = new HashMap<>(16);
+        map.put("application", "px-basesystem-systemmonitor-xyddljypt-zx-j1yehx-7d584478c884ts2");
+//        map.put("from", "1728899854000");
+//        map.put("to", "1728899914000");
+        HttpRequest request = HttpUtil.createGet(uri);
+        request.setMethod(Method.GET);
+        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);
+            JSONObject object = JSONUtil.parseObj(res, true);
+//            System.err.println(object.keySet());
+//            object.getJSONObject(object.get)
+//            System.err.println(object.size());
+
+            for (String key : object.keySet()) {
+                JSONArray arr = object.getJSONArray(key);
+                for (int i = 0; i < arr.size(); i++) {
+                    JSONObject obj = arr.getJSONObject(i);
+                    String name = obj.getByPath("applicationName", String.class);
+                    Integer code = obj.getByPath("status.state.code", Integer.class);
+                    String agentId = obj.getByPath("status.agentId", String.class);
+                    Long eventTimestamp = obj.getByPath("status.eventTimestamp", Long.class);
+                    Long startTimestamp = obj.getByPath("startTimestamp", Long.class);
+//                    if (code == 100) {
+                    System.err.println(name + "\t" + code + "\t" + agentId + "\t" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date(eventTimestamp)) + "\t" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date(startTimestamp)));
+//                    }
+                }
+            }
+//            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) {
+            e.printStackTrace();
+        }
+    }
+
+    public static void removeInactiveAgents() {
+        String uri = "http://192.168.188.66:8080/admin/removeInactiveAgents.pinpoint";
+        Map<String, Object> map = new HashMap<>(16);
+        map.put("application", "px-basesystem-systemmonitor-xyddljypt-zx-j1yehx-7d584478c884ts2");
+//        map.put("durationDays", 3);
+        map.put("password", "admin");
+        HttpRequest request = HttpUtil.createGet(uri);
+        request.setMethod(Method.GET);
+        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);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static void removeAgent() {
+        String uri = "http://192.168.188.66:8080/admin/removeAgentId.pinpoint";
+        Map<String, Object> map = new HashMap<>(16);
+        map.put("applicationName", "px-basesystem-systemmonitor-xyddljypt-zx-j1yehx-7d584478c884ts2");
+        map.put("agentId", "gNC-xtTnSiiIpQrSugfg6A");
+        map.put("password", "admin");
+        HttpRequest request = HttpUtil.createGet(uri);
+        request.setMethod(Method.GET);
+        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);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    public static void removeApplicationName() {
+        String uri = "http://192.168.188.66:8080/admin/removeApplicationName.pinpoint";
+        Map<String, Object> map = new HashMap<>(16);
+        map.put("applicationName", "doc-job");
+        map.put("password", "admin");
+        HttpRequest request = HttpUtil.createGet(uri);
+        request.setMethod(Method.GET);
+        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);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+}

+ 114 - 0
jjt-biz/src/main/java/com/jjt/biz/controller/BizObjPpAgentController.java

@@ -0,0 +1,114 @@
+package com.jjt.biz.controller;
+
+import java.util.List;
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletResponse;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import com.jjt.common.annotation.Log;
+import com.jjt.common.core.controller.BaseController;
+import com.jjt.common.core.domain.AjaxResult;
+import com.jjt.common.enums.BusinessType;
+import com.jjt.biz.domain.BizObjPpAgent;
+import com.jjt.biz.service.IBizObjPpAgentService;
+import com.jjt.common.utils.poi.ExcelUtil;
+import com.jjt.common.core.page.TableDataInfo;
+
+/**
+ * 业务对象pinpoint组成agentController
+ *
+ * @author jjt
+ * @date 2024-10-14
+ */
+@Api(tags="业务对象pinpoint组成agent")
+@RestController
+@RequestMapping("/obj/agent")
+public class BizObjPpAgentController extends BaseController
+{
+    @Resource
+    private IBizObjPpAgentService bizObjPpAgentService;
+
+    /**
+     * 查询业务对象pinpoint组成agent列表
+     */
+    @ApiOperation("查询业务对象pinpoint组成agent列表")
+    @PreAuthorize("@ss.hasPermi('obj:agent:list')")
+    @GetMapping("/list")
+    public TableDataInfo list(BizObjPpAgent bizObjPpAgent)
+    {
+        startPage();
+        List<BizObjPpAgent> list = bizObjPpAgentService.selectBizObjPpAgentList(bizObjPpAgent);
+        return getDataTable(list);
+    }
+
+    /**
+     * 导出业务对象pinpoint组成agent列表
+     */
+    @ApiOperation("导出业务对象pinpoint组成agent列表")
+    @PreAuthorize("@ss.hasPermi('obj:agent:export')")
+    @Log(title = "业务对象pinpoint组成agent", businessType = BusinessType.EXPORT)
+    @PostMapping("/export")
+    public void export(HttpServletResponse response, BizObjPpAgent bizObjPpAgent)
+    {
+        List<BizObjPpAgent> list = bizObjPpAgentService.selectBizObjPpAgentList(bizObjPpAgent);
+        ExcelUtil<BizObjPpAgent> util = new ExcelUtil<BizObjPpAgent>(BizObjPpAgent.class);
+        util.exportExcel(response, list, "业务对象pinpoint组成agent数据");
+    }
+
+    /**
+     * 获取业务对象pinpoint组成agent详细信息
+     */
+    @ApiOperation("获取业务对象pinpoint组成agent详细信息")
+    @PreAuthorize("@ss.hasPermi('obj:agent:query')")
+    @GetMapping(value = "/{objPpAgentId}")
+    public AjaxResult getInfo(@PathVariable("objPpAgentId") Long objPpAgentId)
+    {
+        return success(bizObjPpAgentService.selectBizObjPpAgentByObjPpAgentId(objPpAgentId));
+    }
+
+    /**
+     * 新增业务对象pinpoint组成agent
+     */
+    @ApiOperation("新增业务对象pinpoint组成agent")
+    @PreAuthorize("@ss.hasPermi('obj:agent:add')")
+    @Log(title = "业务对象pinpoint组成agent", businessType = BusinessType.INSERT)
+    @PostMapping
+    public AjaxResult add(@RequestBody BizObjPpAgent bizObjPpAgent)
+    {
+        return toAjax(bizObjPpAgentService.insertBizObjPpAgent(bizObjPpAgent));
+    }
+
+    /**
+     * 修改业务对象pinpoint组成agent
+     */
+    @ApiOperation("修改业务对象pinpoint组成agent")
+    @PreAuthorize("@ss.hasPermi('obj:agent:edit')")
+    @Log(title = "业务对象pinpoint组成agent", businessType = BusinessType.UPDATE)
+    @PutMapping
+    public AjaxResult edit(@RequestBody BizObjPpAgent bizObjPpAgent)
+    {
+        return toAjax(bizObjPpAgentService.updateBizObjPpAgent(bizObjPpAgent));
+    }
+
+    /**
+     * 删除业务对象pinpoint组成agent
+     */
+    @ApiOperation("删除业务对象pinpoint组成agent")
+    @PreAuthorize("@ss.hasPermi('obj:agent:remove')")
+    @Log(title = "业务对象pinpoint组成agent", businessType = BusinessType.DELETE)
+	@DeleteMapping("/{objPpAgentIds}")
+    public AjaxResult remove(@PathVariable Long[] objPpAgentIds)
+    {
+        return toAjax(bizObjPpAgentService.deleteBizObjPpAgentByObjPpAgentIds(objPpAgentIds));
+    }
+}

+ 89 - 0
jjt-biz/src/main/java/com/jjt/biz/domain/BizObjPpAgent.java

@@ -0,0 +1,89 @@
+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;
+
+/**
+ * 业务对象pinpoint组成agent对象 biz_obj_pp_agent
+ *
+ * @author jjt
+ * @date 2024-10-14
+ */
+@ApiModel(value = "BizObjPpAgent", description = "业务对象pinpoint组成agent")
+public class BizObjPpAgent extends BaseEntity
+{
+    private static final long serialVersionUID = 1L;
+
+    /** 对象明细ID */
+    @ApiModelProperty("对象明细ID")
+    @TableId
+    private Long objPpAgentId;
+
+    /** 对象ID */
+    @ApiModelProperty("对象ID")
+    @Excel(name = "对象ID")
+    private Long objId;
+
+    /** agentId */
+    @ApiModelProperty("agentId")
+    @Excel(name = "agentId")
+    private String agentId;
+
+    /** 状态 */
+    @ApiModelProperty("状态")
+    @Excel(name = "状态")
+    private String status;
+
+    public void setObjPpAgentId(Long objPpAgentId)
+    {
+        this.objPpAgentId = objPpAgentId;
+    }
+
+    public Long getObjPpAgentId()
+    {
+        return objPpAgentId;
+    }
+    public void setObjId(Long objId)
+    {
+        this.objId = objId;
+    }
+
+    public Long getObjId()
+    {
+        return objId;
+    }
+    public void setAgentId(String agentId)
+    {
+        this.agentId = agentId;
+    }
+
+    public String getAgentId()
+    {
+        return agentId;
+    }
+    public void setStatus(String status)
+    {
+        this.status = status;
+    }
+
+    public String getStatus()
+    {
+        return status;
+    }
+
+    @Override
+    public String toString() {
+        return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
+            .append("objPpAgentId", getObjPpAgentId())
+            .append("objId", getObjId())
+            .append("agentId", getAgentId())
+            .append("status", getStatus())
+            .append("remark", getRemark())
+            .toString();
+    }
+}

+ 62 - 0
jjt-biz/src/main/java/com/jjt/biz/mapper/BizObjPpAgentMapper.java

@@ -0,0 +1,62 @@
+package com.jjt.biz.mapper;
+
+import java.util.List;
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.jjt.biz.domain.BizObjPpAgent;
+
+/**
+ * 业务对象pinpoint组成agentMapper接口
+ * 
+ * @author jjt
+ * @date 2024-10-14
+ */
+public interface BizObjPpAgentMapper extends BaseMapper<BizObjPpAgent>
+{
+    /**
+     * 查询业务对象pinpoint组成agent
+     * 
+     * @param objPpAgentId 业务对象pinpoint组成agent主键
+     * @return 业务对象pinpoint组成agent
+     */
+    public BizObjPpAgent selectBizObjPpAgentByObjPpAgentId(Long objPpAgentId);
+
+    /**
+     * 查询业务对象pinpoint组成agent列表
+     * 
+     * @param bizObjPpAgent 业务对象pinpoint组成agent
+     * @return 业务对象pinpoint组成agent集合
+     */
+    public List<BizObjPpAgent> selectBizObjPpAgentList(BizObjPpAgent bizObjPpAgent);
+
+    /**
+     * 新增业务对象pinpoint组成agent
+     * 
+     * @param bizObjPpAgent 业务对象pinpoint组成agent
+     * @return 结果
+     */
+    public int insertBizObjPpAgent(BizObjPpAgent bizObjPpAgent);
+
+    /**
+     * 修改业务对象pinpoint组成agent
+     * 
+     * @param bizObjPpAgent 业务对象pinpoint组成agent
+     * @return 结果
+     */
+    public int updateBizObjPpAgent(BizObjPpAgent bizObjPpAgent);
+
+    /**
+     * 删除业务对象pinpoint组成agent
+     * 
+     * @param objPpAgentId 业务对象pinpoint组成agent主键
+     * @return 结果
+     */
+    public int deleteBizObjPpAgentByObjPpAgentId(Long objPpAgentId);
+
+    /**
+     * 批量删除业务对象pinpoint组成agent
+     * 
+     * @param objPpAgentIds 需要删除的数据主键集合
+     * @return 结果
+     */
+    public int deleteBizObjPpAgentByObjPpAgentIds(Long[] objPpAgentIds);
+}

+ 76 - 0
jjt-biz/src/main/java/com/jjt/biz/service/IBizObjPpAgentService.java

@@ -0,0 +1,76 @@
+package com.jjt.biz.service;
+
+import com.jjt.biz.domain.BizObjPpAgent;
+
+import java.util.List;
+
+/**
+ * 业务对象pinpoint组成agentService接口
+ *
+ * @author jjt
+ * @date 2024-10-14
+ */
+public interface IBizObjPpAgentService {
+    /**
+     * 查询业务对象pinpoint组成agent
+     *
+     * @param objPpAgentId 业务对象pinpoint组成agent主键
+     * @return 业务对象pinpoint组成agent
+     */
+    public BizObjPpAgent selectBizObjPpAgentByObjPpAgentId(Long objPpAgentId);
+
+    /**
+     * 查询业务对象pinpoint组成agent列表
+     *
+     * @param bizObjPpAgent 业务对象pinpoint组成agent
+     * @return 业务对象pinpoint组成agent集合
+     */
+    public List<BizObjPpAgent> selectBizObjPpAgentList(BizObjPpAgent bizObjPpAgent);
+
+    /**
+     * 新增业务对象pinpoint组成agent
+     *
+     * @param bizObjPpAgent 业务对象pinpoint组成agent
+     * @return 结果
+     */
+    public int insertBizObjPpAgent(BizObjPpAgent bizObjPpAgent);
+
+    /**
+     * 修改业务对象pinpoint组成agent
+     *
+     * @param bizObjPpAgent 业务对象pinpoint组成agent
+     * @return 结果
+     */
+    public int updateBizObjPpAgent(BizObjPpAgent bizObjPpAgent);
+
+    /**
+     * 批量删除业务对象pinpoint组成agent
+     *
+     * @param objPpAgentIds 需要删除的业务对象pinpoint组成agent主键集合
+     * @return 结果
+     */
+    public int deleteBizObjPpAgentByObjPpAgentIds(Long[] objPpAgentIds);
+
+    /**
+     * 删除业务对象pinpoint组成agent信息
+     *
+     * @param objPpAgentId 业务对象pinpoint组成agent主键
+     * @return 结果
+     */
+    public int deleteBizObjPpAgentByObjPpAgentId(Long objPpAgentId);
+
+    /**
+     * 根据对象ID查询
+     *
+     * @param objId 对象ID
+     * @return 列表
+     */
+    List<BizObjPpAgent> selectBizObjPpAgentListByObjId(Long objId);
+
+    /**
+     * 根据对象删除
+     *
+     * @param ag 对象
+     */
+    void delete(BizObjPpAgent ag);
+}

+ 1 - 0
jjt-biz/src/main/java/com/jjt/biz/service/IBizObjPpService.java

@@ -1,6 +1,7 @@
 package com.jjt.biz.service;
 
 import com.jjt.biz.domain.BizObjPp;
+import com.jjt.biz.domain.PinpointVO;
 
 import java.util.List;
 

+ 17 - 0
jjt-biz/src/main/java/com/jjt/biz/service/IPinpointService.java

@@ -1,8 +1,10 @@
 package com.jjt.biz.service;
 
 import com.alibaba.fastjson2.JSONObject;
+import com.jjt.biz.vo.AgentVO;
 
 import java.time.LocalDateTime;
+import java.util.List;
 import java.util.Map;
 
 /**
@@ -59,4 +61,19 @@ public interface IPinpointService {
      * @return 结果
      */
     Map<String, Object> jvmMemory(String agentId, LocalDateTime st, LocalDateTime ed);
+
+    /**
+     * 清理失效agent
+     */
+    void cleanAgent();
+
+    /**
+     * 通过应用名称获取agent列表
+     *
+     * @param applicationName 应用名称
+     * @param st              开始时间
+     * @param ed              结束时间
+     * @return 结果
+     */
+    List<AgentVO> agentList(String applicationName, LocalDateTime st, LocalDateTime ed);
 }

+ 145 - 76
jjt-biz/src/main/java/com/jjt/biz/service/impl/BizObjMetricsServiceImpl.java

@@ -8,6 +8,7 @@ import com.jjt.biz.mapper.AlarmRecordMapper;
 import com.jjt.biz.mapper.BizObjMetricsDataMapper;
 import com.jjt.biz.mapper.BizObjMetricsMapper;
 import com.jjt.biz.service.*;
+import com.jjt.biz.vo.AgentVO;
 import com.jjt.common.exception.ServiceException;
 import com.jjt.common.utils.DateUtils;
 import com.jjt.common.utils.StringUtils;
@@ -47,7 +48,7 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
     @Resource
     private IBizObjService objService;
     @Resource
-    private IBizObjAppService appService;
+    private IBizObjPpAgentService agentService;
     @Resource
     private IPinpointService pinpointService;
     @Resource
@@ -342,19 +343,29 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
             // 获取应用程序的code
             String appName = bizObj.getObjAddr();
 
-            Long time = Long.parseLong(configService.selectConfigByKey("pp.api.time"));
+            long time = Long.parseLong(configService.selectConfigByKey("pp.api.time"));
             LocalDateTime endTime = LocalDateTime.now();
 
             LocalDateTime startTime = endTime.minusMinutes(time);
             Map<String, String> appMap = pinpointService.getApps();
             String appType = appMap.get(appName);
 
+            List<AgentVO> agentList = pinpointService.agentList(appName, startTime, endTime);
             // 获取监控数据
-//            Float tps = pinpointService.tps(appName, startTime, endTime);
-//            int openFiles = pinpointService.openFile(appName, startTime, endTime);
-//            Map<String, Object> jvmInfo = pinpointService.jvmMemory(appName, startTime, endTime);
-//            float heapUsage = (float) jvmInfo.get("usage");
-//            int gcCount = (int) jvmInfo.get("gc");
+            agentList.forEach(vo -> {
+                if (vo.getCode() == 100) {
+                    Float tps = pinpointService.tps(vo.getAgentId(), startTime, endTime);
+                    int openFiles = pinpointService.openFile(vo.getAgentId(), startTime, endTime);
+                    Map<String, Object> jvmInfo = pinpointService.jvmMemory(vo.getAgentId(), startTime, endTime);
+                    float heapUsage = (float) jvmInfo.get("usage");
+                    int gcCount = (int) jvmInfo.get("gc");
+
+                    vo.setTps(tps);
+                    vo.setOpenFiles(openFiles);
+                    vo.setHeapUsage(heapUsage);
+                    vo.setGcCount(gcCount);
+                }
+            });
 
             JSONObject linkData = pinpointService.link(appName, appType, startTime, endTime);
             JSONArray nodeDataArray = linkData.getJSONObject("applicationMapData").getJSONArray("nodeDataArray");
@@ -373,14 +384,15 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
             }
 
             // 1.更新 BIZ_OBJ_PP 表
-            updateBizObjPpTable(objId, pinpointVOList);
+            updateBizObjPpTable(objId, pinpointVOList, agentList);
 
             // 2.更新业务对象指标表
-            updateBizObjMetrics(objId, null, 0, 0, 0, pinpointVOList, date);
+            updateBizObjMetrics(objId, agentList, pinpointVOList, date);
 //            updateBizObjMetrics(objId, tps, openFiles, heapUsage, gcCount, pinpointVOList, date);
         }
     }
 
+
     /**
      * 根据objId获取prometheus指标值
      *
@@ -491,6 +503,7 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
                 }
             }
             om.setDValue(dv);
+
             BizObjMetricsData data = new BizObjMetricsData();
             data.setObjMetricsId(om.getObjMetricsId());
             data.setdValue(om.getDValue());
@@ -620,16 +633,48 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
 
     /**
      * 更新BIZ_OBJ_PP
+     * 更新agent
      *
      * @param objId          对象ID
      * @param pinpointVOList PP组成
+     * @param agentList      agentId列表
      */
-    private void updateBizObjPpTable(Long objId, List<PinpointVO> pinpointVOList) {
+    private void updateBizObjPpTable(Long objId, List<PinpointVO> pinpointVOList, List<AgentVO> agentList) {
+        List<BizObjPpAgent> existingAgentList = agentService.selectBizObjPpAgentListByObjId(objId);
+        Set<String> ags = agentList.stream()
+                .map(AgentVO::getAgentId)
+                .collect(Collectors.toSet());
+        //删除表中存在,agentList中不存在的记录
+        existingAgentList.forEach(ag -> {
+            if (!ags.contains(ag.getAgentId())) {
+                agentService.delete(ag);
+            }
+        });
+
+
+        Set<String> existingAgents = existingAgentList.stream()
+                .map(BizObjPpAgent::getAgentId)
+                .collect(Collectors.toSet());
+
         List<BizObjPp> existingPpList = ppService.selectBizObjPpListByObjId(objId);
         Set<String> existingNames = existingPpList.stream()
                 .map(BizObjPp::getPpName)
                 .collect(Collectors.toSet());
 
+        List<BizObjPpAgent> agents = new ArrayList<>();
+        List<BizObjPp> pps = new ArrayList<>();
+        agentList.forEach(vo -> {
+            //如果没有,则添加
+            if (!existingAgents.contains(vo.getAgentId()) && vo.getCode() == 100) {
+                BizObjPpAgent agent = new BizObjPpAgent();
+                agent.setAgentId(vo.getAgentId());
+                agent.setObjId(objId);
+                agentService.insertBizObjPpAgent(agent);
+                agents.add(agent);
+            }
+        });
+
+
         pinpointVOList.stream()
                 .filter(vo -> !existingNames.contains(vo.getApplicationName()))
                 .forEach(vo -> {
@@ -639,66 +684,85 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
                     pp.setPpName(vo.getApplicationName());
                     pp.setPpType(vo.getCategory());
                     ppService.insertBizObjPp(pp);
-
-                    // 根据模板更新业务对象指标表
-                    updateBizObjMetricsFromTemplate(objId, pp);
-                    existingPpList.add(pp);
+                    pps.add(pp);
                 });
+        updateBizObjMetricsFromTemplate(objId, agents, pps);
     }
 
+
     /**
      * 根据模板更新业务对象指标表
      *
-     * @param objId 对象ID
-     * @param pp    pp对象
+     * @param objId  对象ID
+     * @param agents agent对象
+     * @param pps    pp对象
      */
-    private void updateBizObjMetricsFromTemplate(Long objId, BizObjPp pp) {
+    private void updateBizObjMetricsFromTemplate(Long objId, List<BizObjPpAgent> agents, List<BizObjPp> pps) {
         List<BizObjTpl> templateList = objTplService.selectTplList4objId(objId);
-        templateList.forEach(template -> insertOrUpdateMetricsFromTemplate(objId, template.getTplId(), pp));
+        templateList.forEach(template -> insertOrUpdateMetricsFromTemplate(objId, template.getTplId(), agents, pps));
     }
 
     /**
      * 更新模板中的pinpoint指标到业务对象指标
      *
-     * @param objId 对象ID
-     * @param tplId 模板ID
-     * @param pp    pinpoint组成
+     * @param objId  对象ID
+     * @param tplId  模板ID
+     * @param agents agent对象
+     * @param pps    pp对象
      */
-    private void insertOrUpdateMetricsFromTemplate(Long objId, Long tplId, BizObjPp pp) {
+    private void insertOrUpdateMetricsFromTemplate(Long objId, Long tplId, List<BizObjPpAgent> agents, List<BizObjPp> pps) {
         MetricsTplDetail query = new MetricsTplDetail();
         query.setTplId(tplId);
         List<MetricsTplDetail> list = detailService.selectMetricsTplDetailList(query);
         List<BizObjMetrics> objMetrics = new ArrayList<>();
         list.forEach(d -> {
-            if ("1".equals(d.getMetricsDef().getMetricsType()) && !d.getMetricsDef().getMetricsCode().startsWith("pp.jvm.")) {
-                //如果是pinpoint,需要
-                // 1.获取对象pinpoint组成
-                BizObjMetrics ms = new BizObjMetrics();
-                ms.setObjId(objId);
-                ms.setTplId(tplId);
-                ms.setMetricsId(d.getMetricsId());
-                ms.setMetricsName(pp.getPpType() + "/" + d.getMetricsDef().getMetricsName());
-                ms.setMetricsCode(d.getMetricsDef().getMetricsCode());
-                if (pp.getPpType().equals("REDIS")) {
-                    //redis需要将1s换成100ms 3s换成300ms 5s换成500ms
-                    if (d.getMetricsCode().endsWith("1s")) {
-                        ms.setMetricsName(ms.getMetricsName().replace("1s", "100ms"));
-                        ms.setMetricsCode(ms.getMetricsCode().replace("1s", "100ms"));
-                    }
-                    if (d.getMetricsCode().endsWith("3s")) {
-                        ms.setMetricsName(ms.getMetricsName().replace("3s", "300ms"));
-                        ms.setMetricsCode(ms.getMetricsCode().replace("3s", "300ms"));
-                    }
-                    if (d.getMetricsCode().endsWith("5s")) {
-                        ms.setMetricsName(ms.getMetricsName().replace("5s", "500ms"));
-                        ms.setMetricsCode(ms.getMetricsCode().replace("5s", "500ms"));
-                    }
+            if ("1".equals(d.getMetricsDef().getMetricsType())) {
+                if (!d.getMetricsDef().getMetricsCode().startsWith("pp.jvm.")) {
+                    //如果是pinpoint链路指标,需要
+                    // 1.获取对象pinpoint组成
+                    pps.forEach(pp -> {
+                        BizObjMetrics ms = new BizObjMetrics();
+                        ms.setObjId(objId);
+                        ms.setTplId(tplId);
+                        ms.setMetricsId(d.getMetricsId());
+                        ms.setMetricsName(pp.getPpType() + "/" + d.getMetricsDef().getMetricsName());
+                        ms.setMetricsCode(d.getMetricsDef().getMetricsCode());
+                        if (pp.getPpType().equals("REDIS")) {
+                            //redis需要将1s换成100ms 3s换成300ms 5s换成500ms
+                            if (d.getMetricsCode().endsWith("1s")) {
+                                ms.setMetricsName(ms.getMetricsName().replace("1s", "100ms"));
+                                ms.setMetricsCode(ms.getMetricsCode().replace("1s", "100ms"));
+                            }
+                            if (d.getMetricsCode().endsWith("3s")) {
+                                ms.setMetricsName(ms.getMetricsName().replace("3s", "300ms"));
+                                ms.setMetricsCode(ms.getMetricsCode().replace("3s", "300ms"));
+                            }
+                            if (d.getMetricsCode().endsWith("5s")) {
+                                ms.setMetricsName(ms.getMetricsName().replace("5s", "500ms"));
+                                ms.setMetricsCode(ms.getMetricsCode().replace("5s", "500ms"));
+                            }
+                        }
+                        ms.setDataExp(ms.getMetricsCode());
+                        ms.setAlarmLow(d.getAlarmLow());
+                        ms.setAlarmMid(d.getAlarmMid());
+                        ms.setAlarmHigh(d.getAlarmHigh());
+                        objMetrics.add(ms);
+                    });
+                } else {
+                    agents.forEach(agent -> {
+                        BizObjMetrics ms = new BizObjMetrics();
+                        ms.setObjId(objId);
+                        ms.setTplId(tplId);
+                        ms.setMetricsId(d.getMetricsId());
+                        ms.setMetricsName(agent.getAgentId() + "/" + d.getMetricsDef().getMetricsName());
+                        ms.setMetricsCode(d.getMetricsDef().getMetricsCode());
+                        ms.setDataExp(ms.getMetricsCode());
+                        ms.setAlarmLow(d.getAlarmLow());
+                        ms.setAlarmMid(d.getAlarmMid());
+                        ms.setAlarmHigh(d.getAlarmHigh());
+                        objMetrics.add(ms);
+                    });
                 }
-                ms.setDataExp(ms.getMetricsCode());
-                ms.setAlarmLow(d.getAlarmLow());
-                ms.setAlarmMid(d.getAlarmMid());
-                ms.setAlarmHigh(d.getAlarmHigh());
-                objMetrics.add(ms);
             }
         });
         if (objMetrics.size() > 0) {
@@ -710,43 +774,42 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
      * 更新指标
      *
      * @param objId          对象ID
-     * @param tps            系统压力
-     * @param openFiles      打开文件数量
-     * @param heapUsage      堆内存使用率
-     * @param gcCount        gc次数
+     * @param agentVOList    jvm信息
      * @param pinpointVOList 链路列表数据
      * @param date           时间
      */
-    private void updateBizObjMetrics(Long objId, Float tps, int openFiles, float heapUsage, int gcCount, List<PinpointVO> pinpointVOList, Date date) {
+    private void updateBizObjMetrics(Long objId, List<AgentVO> agentVOList, List<
+            PinpointVO> pinpointVOList, Date date) {
         //查询当前对象所有正在告警列表
         Map<Long, AlarmRecord> recordMap = alarmRecordService.selectAlarmRecordListCurr(objId);
         //查询当前对象未结束事件列表
         Map<Long, HlEvent> eventMap = eventService.selectHlEventListCurr(objId);
-        //TODO 暂时取消jvm相关指标
-//        updateJvmMetrics(objId, tps, heapUsage, openFiles, gcCount, date, recordMap, eventMap);
+        updateJvmMetrics(objId, agentVOList, date, recordMap, eventMap);
         updateLinkMetrics(objId, pinpointVOList, date, recordMap, eventMap);
     }
 
     /**
      * 更新jvm指标
      *
-     * @param objId     对象ID
-     * @param tps       系统压力
-     * @param openFiles 打开文件数量
-     * @param heapUsage 堆内存使用率
-     * @param gcCount   gc次数
-     * @param date      数据时间
+     * @param objId 对象ID
+     *              * @param agentVOList    jvm信息
+     * @param date  数据时间
      */
-    private void updateJvmMetrics(Long objId, Float tps, float heapUsage, int openFiles, int gcCount, Date date, Map<Long, AlarmRecord> recordMap, Map<Long, HlEvent> eventMap) {
+    private void updateJvmMetrics(Long objId, List<AgentVO> agentVOList, Date
+            date, Map<Long, AlarmRecord> recordMap, Map<Long, HlEvent> eventMap) {
         BizObjMetrics jvmMetrics = new BizObjMetrics();
         jvmMetrics.setObjId(objId);
-
         jvmMetrics.setMetricsCode("pp.jvm.");
         List<BizObjMetrics> omList = selectBizObjMetricsList(jvmMetrics);
-        updateMetricsValues(omList, "tps", BigDecimal.valueOf(tps), date, recordMap, eventMap);
-        updateMetricsValues(omList, "heap.usage", BigDecimal.valueOf(heapUsage), date, recordMap, eventMap);
-        updateMetricsValues(omList, "open", BigDecimal.valueOf(openFiles), date, recordMap, eventMap);
-        updateMetricsValues(omList, "gc", BigDecimal.valueOf(gcCount), date, recordMap, eventMap);
+        for (AgentVO vo : agentVOList) {
+            if (vo.getCode() == 100) {
+                updateMetricsValues(omList, "tps", vo.getAgentId(), BigDecimal.valueOf(vo.getTps()), date, recordMap, eventMap);
+                updateMetricsValues(omList, "heap.usage", vo.getAgentId(), BigDecimal.valueOf(vo.getHeapUsage()), date, recordMap, eventMap);
+                updateMetricsValues(omList, "open", vo.getAgentId(), BigDecimal.valueOf(vo.getOpenFiles()), date, recordMap, eventMap);
+                updateMetricsValues(omList, "gc", vo.getAgentId(), BigDecimal.valueOf(vo.getGcCount()), date, recordMap, eventMap);
+            }
+        }
+
     }
 
     /**
@@ -755,16 +818,18 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
      * @param omList       jvm指标列表
      * @param metricSuffix 指标后缀
      * @param value        值
+     * @param agentId      agentId
      * @param date         数据时间
      */
-    private void updateMetricsValues(List<BizObjMetrics> omList, String metricSuffix, BigDecimal value, Date date, Map<Long, AlarmRecord> recordMap, Map<Long, HlEvent> eventMap) {
+    private void updateMetricsValues(List<BizObjMetrics> omList, String metricSuffix, String agentId, BigDecimal value, Date
+            date, Map<Long, AlarmRecord> recordMap, Map<Long, HlEvent> eventMap) {
         List<BizObjMetricsData> dataList = new ArrayList<>();
         List<AlarmRecord> addRList = new ArrayList<>();
         List<AlarmRecord> updateRList = new ArrayList<>();
         List<HlEvent> addEList = new ArrayList<>();
         List<HlEvent> updateEList = new ArrayList<>();
         omList.stream()
-                .filter(om -> om.getMetricsCode().endsWith(metricSuffix))
+                .filter(om -> om.getMetricsCode().endsWith(metricSuffix) && om.getMetricsName().startsWith(agentId + "/"))
                 .forEach(om -> {
                     om.setDValue(value);
                     updateBizObjMetrics(om);
@@ -794,7 +859,8 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
         batchUpdate(null, dataList, addRList, updateRList, addEList, updateEList);
     }
 
-    private void batchUpdate(List<BizObjMetrics> metricsToUpdate, List<BizObjMetricsData> dataList, List<AlarmRecord> addRList, List<AlarmRecord> updateRList, List<HlEvent> addEList, List<HlEvent> updateEList) {
+    private void batchUpdate
+            (List<BizObjMetrics> metricsToUpdate, List<BizObjMetricsData> dataList, List<AlarmRecord> addRList, List<AlarmRecord> updateRList, List<HlEvent> addEList, List<HlEvent> updateEList) {
         // 更新所有需要更新的BizObjMetrics对象
         try (SqlSession sqlSession = factory.openSession(ExecutorType.BATCH, false)) {
             BizObjMetricsMapper mapper = sqlSession.getMapper(BizObjMetricsMapper.class);
@@ -830,7 +896,8 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
      * @param pinpointVOList 链路列表
      * @param date           时间
      */
-    private void updateLinkMetrics(Long objId, List<PinpointVO> pinpointVOList, Date date, Map<Long, AlarmRecord> recordMap, Map<Long, HlEvent> eventMap) {
+    private void updateLinkMetrics(Long objId, List<PinpointVO> pinpointVOList, Date
+            date, Map<Long, AlarmRecord> recordMap, Map<Long, HlEvent> eventMap) {
         Map<String, List<BizObjMetrics>> metricsMap = getAllMetricsForObjId(objId);
         pinpointVOList.forEach(vo -> updateMetricsValues(metricsMap, vo, date, recordMap, eventMap));
     }
@@ -843,7 +910,8 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
      * @param vo         pp链路对象
      * @param date       时间
      */
-    private void updateMetricsValues(Map<String, List<BizObjMetrics>> metricsMap, PinpointVO vo, Date date, Map<Long, AlarmRecord> recordMap, Map<Long, HlEvent> eventMap) {
+    private void updateMetricsValues(Map<String, List<BizObjMetrics>> metricsMap, PinpointVO vo, Date
+            date, Map<Long, AlarmRecord> recordMap, Map<Long, HlEvent> eventMap) {
         List<BizObjMetricsData> dataList = new ArrayList<>();
         List<AlarmRecord> addRList = new ArrayList<>();
         List<AlarmRecord> updateRList = new ArrayList<>();
@@ -870,7 +938,7 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
                         if (time1 == null) {
                             time1 = vo.getTime100ms();
                         }
-                        BigDecimal rate = BigDecimal.valueOf(time1).divide(BigDecimal.valueOf(vo.getTot()), 2, RoundingMode.HALF_UP);
+                        BigDecimal rate = BigDecimal.valueOf(time1).divide(BigDecimal.valueOf(vo.getTot()), 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100));
                         updateMetric(om, "pp.rate", rate, date, dataList);
                         if (om.getDValue() != null) {
                             //处理告警
@@ -922,7 +990,8 @@ public class BizObjMetricsServiceImpl implements IBizObjMetricsService {
      * @param value  值
      * @param date   时间
      */
-    private void updateMetric(BizObjMetrics om, String suffix, Number value, Date date, List<BizObjMetricsData> dataList) {
+    private void updateMetric(BizObjMetrics om, String suffix, Number value, Date
+            date, List<BizObjMetricsData> dataList) {
         if (om.getMetricsCode().endsWith(suffix) && value != null) {
             om.setDValue(BigDecimal.valueOf(value.doubleValue()));
             updateBizObjMetrics(om);

+ 131 - 0
jjt-biz/src/main/java/com/jjt/biz/service/impl/BizObjPpAgentServiceImpl.java

@@ -0,0 +1,131 @@
+package com.jjt.biz.service.impl;
+
+import com.jjt.biz.domain.BizObjPpAgent;
+import com.jjt.biz.mapper.BizObjPpAgentMapper;
+import com.jjt.biz.service.IBizObjPpAgentService;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.List;
+
+/**
+ * 业务对象pinpoint组成agentService业务层处理
+ *
+ * @author jjt
+ * @date 2024-10-14
+ */
+@Service
+public class BizObjPpAgentServiceImpl implements IBizObjPpAgentService {
+    @Resource
+    private BizObjPpAgentMapper bizObjPpAgentMapper;
+    @Resource
+    private JdbcTemplate jdbcTemplate;
+
+    /**
+     * 查询业务对象pinpoint组成agent
+     *
+     * @param objPpAgentId 业务对象pinpoint组成agent主键
+     * @return 业务对象pinpoint组成agent
+     */
+    @Override
+    public BizObjPpAgent selectBizObjPpAgentByObjPpAgentId(Long objPpAgentId) {
+        return bizObjPpAgentMapper.selectBizObjPpAgentByObjPpAgentId(objPpAgentId);
+    }
+
+    /**
+     * 查询业务对象pinpoint组成agent列表
+     *
+     * @param bizObjPpAgent 业务对象pinpoint组成agent
+     * @return 业务对象pinpoint组成agent
+     */
+    @Override
+    public List<BizObjPpAgent> selectBizObjPpAgentList(BizObjPpAgent bizObjPpAgent) {
+        return bizObjPpAgentMapper.selectBizObjPpAgentList(bizObjPpAgent);
+    }
+
+    /**
+     * 新增业务对象pinpoint组成agent
+     *
+     * @param bizObjPpAgent 业务对象pinpoint组成agent
+     * @return 结果
+     */
+    @Override
+    public int insertBizObjPpAgent(BizObjPpAgent bizObjPpAgent) {
+        return bizObjPpAgentMapper.insertBizObjPpAgent(bizObjPpAgent);
+    }
+
+    /**
+     * 修改业务对象pinpoint组成agent
+     *
+     * @param bizObjPpAgent 业务对象pinpoint组成agent
+     * @return 结果
+     */
+    @Override
+    public int updateBizObjPpAgent(BizObjPpAgent bizObjPpAgent) {
+        return bizObjPpAgentMapper.updateBizObjPpAgent(bizObjPpAgent);
+    }
+
+    /**
+     * 批量删除业务对象pinpoint组成agent
+     *
+     * @param objPpAgentIds 需要删除的业务对象pinpoint组成agent主键
+     * @return 结果
+     */
+    @Override
+    public int deleteBizObjPpAgentByObjPpAgentIds(Long[] objPpAgentIds) {
+        return bizObjPpAgentMapper.deleteBizObjPpAgentByObjPpAgentIds(objPpAgentIds);
+    }
+
+    /**
+     * 删除业务对象pinpoint组成agent信息
+     *
+     * @param objPpAgentId 业务对象pinpoint组成agent主键
+     * @return 结果
+     */
+    @Override
+    public int deleteBizObjPpAgentByObjPpAgentId(Long objPpAgentId) {
+        return bizObjPpAgentMapper.deleteBizObjPpAgentByObjPpAgentId(objPpAgentId);
+    }
+
+    /**
+     * 根据对象ID查询
+     *
+     * @param objId 对象ID
+     * @return 列表
+     */
+    @Override
+    public List<BizObjPpAgent> selectBizObjPpAgentListByObjId(Long objId) {
+        BizObjPpAgent pp = new BizObjPpAgent();
+        pp.setObjId(objId);
+        return selectBizObjPpAgentList(pp);
+    }
+
+    /**
+     * 根据对象删除
+     *
+     * @param ag 对象
+     */
+    @Override
+    public void delete(BizObjPpAgent ag) {
+        try {
+            // 开始事务
+            jdbcTemplate.execute("BEGIN");
+            String name = ag.getAgentId() + "/%";
+
+            // 执行删除语句
+            //1.删除指标数据
+            jdbcTemplate.update("DELETE FROM biz_obj_metrics_data WHERE obj_metrics_id IN(SELECT obj_metrics_id FROM biz_obj_metrics WHERE obj_id=? AND metrics_name LIKE ?)", ag.getObjId(), name);
+//            //2.删除指标
+            jdbcTemplate.update("DELETE FROM biz_obj_metrics WHERE obj_id=? AND metrics_name LIKE ? ", ag.getObjId(), name);
+//            //3.删除模板
+            jdbcTemplate.update("DELETE FROM BIZ_OBJ_PP_AGENT WHERE OBJ_PP_AGENT_ID=?", ag.getObjPpAgentId());
+
+            // 提交事务
+            jdbcTemplate.execute("COMMIT");
+        } catch (Exception e) {
+            // 回滚事务
+            jdbcTemplate.execute("ROLLBACK");
+        }
+    }
+}

+ 23 - 8
jjt-biz/src/main/java/com/jjt/biz/service/impl/BizObjTplServiceImpl.java

@@ -1,6 +1,5 @@
 package com.jjt.biz.service.impl;
 
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.jjt.biz.domain.BizObjTpl;
 import com.jjt.biz.domain.MetricsTpl;
 import com.jjt.biz.mapper.BizObjTplMapper;
@@ -8,6 +7,7 @@ import com.jjt.biz.service.IBizObjMetricsService;
 import com.jjt.biz.service.IBizObjTplService;
 import com.jjt.biz.service.IMetricsTplDetailService;
 import com.jjt.common.utils.DateUtils;
+import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.stereotype.Service;
 
 import javax.annotation.Resource;
@@ -27,6 +27,8 @@ public class BizObjTplServiceImpl implements IBizObjTplService {
     private IBizObjMetricsService metricsService;
     @Resource
     private IMetricsTplDetailService tplDetailService;
+    @Resource
+    private JdbcTemplate jdbcTemplate;
 
     /**
      * 查询业务对象模板应用
@@ -165,12 +167,25 @@ public class BizObjTplServiceImpl implements IBizObjTplService {
      */
     @Override
     public int del(Long objId, Long tplId) {
-        //1.先删除指标
-        metricsService.delete(objId, tplId);
-        //2.再删除模板
-        QueryWrapper<BizObjTpl> wrapper = new QueryWrapper<>();
-        wrapper.eq("obj_id", objId);
-        wrapper.eq("tpl_id", tplId);
-        return bizObjTplMapper.delete(wrapper);
+        try {
+            // 开始事务
+            jdbcTemplate.execute("BEGIN");
+
+            // 执行删除语句
+            //1.删除指标数据
+            jdbcTemplate.update("DELETE FROM biz_obj_metrics_data WHERE obj_metrics_id IN(SELECT obj_metrics_id FROM biz_obj_metrics WHERE obj_id=? AND tpl_id=?)", objId, tplId);
+            //2.删除指标
+            jdbcTemplate.update("DELETE FROM biz_obj_metrics WHERE obj_id=? AND tpl_id=?", objId, tplId);
+            //3.删除模板
+            jdbcTemplate.update("DELETE FROM biz_obj_tpl WHERE obj_id=? AND tpl_id=?", objId, tplId);
+
+            // 提交事务
+            jdbcTemplate.execute("COMMIT");
+            return 0;
+        } catch (Exception e) {
+            // 回滚事务
+            jdbcTemplate.execute("ROLLBACK");
+            return 1;
+        }
     }
 }

+ 75 - 1
jjt-biz/src/main/java/com/jjt/biz/service/impl/PinpointServiceImpl.java

@@ -1,9 +1,14 @@
 package com.jjt.biz.service.impl;
 
+import cn.hutool.http.HttpRequest;
+import cn.hutool.http.HttpResponse;
+import cn.hutool.http.HttpUtil;
+import cn.hutool.http.Method;
+import cn.hutool.json.JSONUtil;
 import com.alibaba.fastjson2.JSONArray;
 import com.alibaba.fastjson2.JSONObject;
 import com.jjt.biz.service.IPinpointService;
-import com.jjt.common.constant.CacheConstants;
+import com.jjt.biz.vo.AgentVO;
 import com.jjt.common.core.redis.RedisCache;
 import com.jjt.common.utils.http.HttpUtils;
 import com.jjt.system.service.ISysConfigService;
@@ -12,9 +17,12 @@ import org.springframework.stereotype.Service;
 import javax.annotation.Resource;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
+import java.nio.charset.StandardCharsets;
 import java.time.LocalDateTime;
 import java.time.ZoneOffset;
+import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 /**
@@ -208,4 +216,70 @@ public class PinpointServiceImpl implements IPinpointService {
         return map;
     }
 
+    /**
+     * 清理失效agent
+     */
+    @Override
+    public void cleanAgent() {
+        String uri = baseUri() + "/admin/removeInactiveAgents.pinpoint";
+        Map<String, Object> map = new HashMap<>(16);
+        map.put("password", "admin");
+        HttpRequest request = HttpUtil.createGet(uri);
+        request.setMethod(Method.GET);
+        request.form(map);
+        request.setConnectionTimeout(2000);
+        try (HttpResponse execute = request.execute()) {
+            if (!execute.isOk()) {
+                throw new RuntimeException("status:" + execute.getStatus() + "\tres:" + execute.body());
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 通过应用名称获取agent列表
+     *
+     * @param applicationName 应用名称
+     * @param st              开始时间
+     * @param ed              结束时间
+     * @return 结果
+     */
+    @Override
+    public List<AgentVO> agentList(String applicationName, LocalDateTime st, LocalDateTime ed) {
+        List<AgentVO> result = new ArrayList<>();
+        long end = ed.toEpochSecond(ZoneOffset.ofHours(8)) * 1000;
+        long start = st.toEpochSecond(ZoneOffset.ofHours(8)) * 1000;
+        String uri = baseUri() + "/getAgentList.pinpoint";
+        Map<String, Object> map = new HashMap<>(16);
+        map.put("application", applicationName);
+        map.put("from", start);
+        map.put("to", end);
+        HttpRequest request = HttpUtil.createGet(uri);
+        request.setMethod(Method.GET);
+        request.form(map);
+        request.setConnectionTimeout(2000);
+        try (HttpResponse execute = request.execute()) {
+            if (execute.isOk()) {
+                String res = new String(execute.body().getBytes(), StandardCharsets.UTF_8);
+                cn.hutool.json.JSONObject object = JSONUtil.parseObj(res, true);
+                for (String key : object.keySet()) {
+                    cn.hutool.json.JSONArray arr = object.getJSONArray(key);
+                    for (int i = 0; i < arr.size(); i++) {
+                        AgentVO vo = new AgentVO();
+                        cn.hutool.json.JSONObject obj = arr.getJSONObject(i);
+                        Integer code = obj.getByPath("status.state.code", Integer.class);
+                        String agentId = obj.getByPath("status.agentId", String.class);
+                        vo.setCode(code);
+                        vo.setAgentId(agentId);
+                        result.add(vo);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return result;
+    }
+
 }

+ 19 - 0
jjt-biz/src/main/java/com/jjt/biz/vo/AgentVO.java

@@ -0,0 +1,19 @@
+package com.jjt.biz.vo;
+
+import lombok.Data;
+
+/**
+ * agentId vo
+ *
+ * @author wukai
+ * @date 2024/8/21 10:16
+ */
+@Data
+public class AgentVO {
+    private String agentId;
+    private Integer code;
+    private Float tps;
+    private Integer openFiles;
+    private Float heapUsage;
+    private Integer gcCount;
+}

+ 10 - 0
jjt-biz/src/main/java/com/jjt/task/CleanTask.java

@@ -1,6 +1,7 @@
 package com.jjt.task;
 
 import com.jjt.biz.service.IBizObjMetricsDataService;
+import com.jjt.biz.service.IPinpointService;
 import org.springframework.stereotype.Component;
 
 import javax.annotation.Resource;
@@ -17,6 +18,8 @@ import java.util.Date;
 public class CleanTask {
     @Resource
     private IBizObjMetricsDataService dataService;
+    @Resource
+    private IPinpointService pinpointService;
 
     /**
      * 清理历史数据
@@ -28,5 +31,12 @@ public class CleanTask {
         dataService.clean(date);
     }
 
+    /**
+     * 清理pinpoint失效agent
+     */
+    public void ppAgent() {
+//        dataService.clean(date);
+    }
+
 
 }

+ 100 - 0
jjt-biz/src/main/resources/mapper/obj/BizObjPpAgentMapper.xml

@@ -0,0 +1,100 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE mapper
+        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
+        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
+<mapper namespace="com.jjt.biz.mapper.BizObjPpAgentMapper">
+
+    <resultMap type="BizObjPpAgent" id="BizObjPpAgentResult">
+        <result property="objPpAgentId" column="OBJ_PP_AGENT_ID"/>
+        <result property="objId" column="OBJ_ID"/>
+        <result property="agentId" column="AGENT_ID"/>
+        <result property="status" column="STATUS"/>
+        <result property="remark" column="REMARK"/>
+    </resultMap>
+
+    <sql id="selectBizObjPpAgentVo">
+        select OBJ_PP_AGENT_ID, OBJ_ID, AGENT_ID, STATUS, REMARK
+        from biz_obj_pp_agent
+    </sql>
+
+    <select id="selectBizObjPpAgentList" parameterType="BizObjPpAgent" resultMap="BizObjPpAgentResult">
+        <include refid="selectBizObjPpAgentVo"/>
+        <where>
+            <if test="objId != null ">
+                and OBJ_ID = #{objId}
+            </if>
+            <if test="agentId != null  and agentId != ''">
+                and AGENT_ID = #{agentId}
+            </if>
+            <if test="status != null  and status != ''">
+                and STATUS = #{status}
+            </if>
+            <if test="remark != null  and remark != ''">
+                and REMARK = #{remark}
+            </if>
+        </where>
+    </select>
+
+    <select id="selectBizObjPpAgentByObjPpAgentId" parameterType="Long"
+            resultMap="BizObjPpAgentResult">
+        <include refid="selectBizObjPpAgentVo"/>
+        where OBJ_PP_AGENT_ID = #{objPpAgentId}
+    </select>
+
+    <insert id="insertBizObjPpAgent" parameterType="BizObjPpAgent" useGeneratedKeys="true"
+            keyProperty="objPpAgentId">
+        insert into biz_obj_pp_agent
+        <trim prefix="(" suffix=")" suffixOverrides=",">
+            <if test="objId != null">OBJ_ID,
+            </if>
+            <if test="agentId != null">AGENT_ID,
+            </if>
+            <if test="status != null">STATUS,
+            </if>
+            <if test="remark != null">REMARK,
+            </if>
+        </trim>
+        <trim prefix="values (" suffix=")" suffixOverrides=",">
+            <if test="objId != null">#{objId},
+            </if>
+            <if test="agentId != null">#{agentId},
+            </if>
+            <if test="status != null">#{status},
+            </if>
+            <if test="remark != null">#{remark},
+            </if>
+        </trim>
+    </insert>
+
+    <update id="updateBizObjPpAgent" parameterType="BizObjPpAgent">
+        update biz_obj_pp_agent
+        <trim prefix="SET" suffixOverrides=",">
+            <if test="objId != null">OBJ_ID =
+                #{objId},
+            </if>
+            <if test="agentId != null">AGENT_ID =
+                #{agentId},
+            </if>
+            <if test="status != null">STATUS =
+                #{status},
+            </if>
+            <if test="remark != null">REMARK =
+                #{remark},
+            </if>
+        </trim>
+        where OBJ_PP_AGENT_ID = #{objPpAgentId}
+    </update>
+
+    <delete id="deleteBizObjPpAgentByObjPpAgentId" parameterType="Long">
+        delete
+        from biz_obj_pp_agent
+        where OBJ_PP_AGENT_ID = #{objPpAgentId}
+    </delete>
+
+    <delete id="deleteBizObjPpAgentByObjPpAgentIds" parameterType="String">
+        delete from biz_obj_pp_agent where OBJ_PP_AGENT_ID in
+        <foreach item="objPpAgentId" collection="array" open="(" separator="," close=")">
+            #{objPpAgentId}
+        </foreach>
+    </delete>
+</mapper>