kongdeqiang
2022-12-16 daf6a95086087ec99232eea8b4648b7541881f7c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package com.wgcloud.controller;
 
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wgcloud.entity.DeskIo;
import com.wgcloud.entity.DiskState;
import com.wgcloud.entity.DiskSmart;
import com.wgcloud.entity.FileSafe;
import com.wgcloud.service.AppInfoService;
import com.wgcloud.service.DockerInfoService;
import com.wgcloud.service.FileSafeService;
import com.wgcloud.util.DateUtil;
import com.wgcloud.util.FormatUtil;
import com.wgcloud.util.ThreadPoolUtil;
import com.wgcloud.util.TokenUtils;
import com.wgcloud.util.msg.WarnMailUtil;
import com.wgcloud.util.staticvar.BatchData;
import com.wgcloud.util.staticvar.StaticKeys;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
/**
 * @version v3.3
 * @ClassName:AgentGoController.java
 * @author: http://www.wgstart.com
 * @date: 2021年3月18日
 * @Description: 每半小时提交一次磁盘信息
 * @Copyright: 2019-2021 wgcloud. All rights reserved.
 */
@Controller
@RequestMapping("/agentDiskGo")
public class AgentDiskController {
 
 
    private static final Logger logger = LoggerFactory.getLogger(AgentDiskController.class);
 
 
    @Autowired
    private DockerInfoService dockerInfoService;
    @Autowired
    private AppInfoService appInfoService;
    @Autowired
    private FileSafeService fileSafeService;
    @Autowired
    private TokenUtils tokenUtils;
 
    /**
     * agent上报数据处理
     *
     * @param paramBean
     * @return
     */
    @ResponseBody
    @RequestMapping("/minTask")
    public JSONObject minTask(@RequestBody String paramBean) {
        JSONObject agentJsonObject = (JSONObject) JSONUtil.parse(paramBean);
        logger.debug("agent上报磁盘数据-------------" + agentJsonObject.toString());
        JSONObject resultJson = new JSONObject();
        if (!tokenUtils.checkAgentToken(agentJsonObject)) {
            logger.error(StaticKeys.TOKEN_ERROR);
            resultJson.set("result", StaticKeys.TOKEN_ERROR);
            return resultJson;
        }
 
        String bindIp = agentJsonObject.getStr("bindIp");
        if (isExists(bindIp)) {
            logger.error("agentDisk multiple times at the same time:" + bindIp);
            resultJson.set("result", "agentDisk multiple times at the same time:" + bindIp);
            return resultJson;
        }
        //磁盘空间信息
        JSONObject diskInfoListJson = agentJsonObject.getJSONObject("diskInfoList");
        //磁盘io信息
        JSONObject diskIoJson = agentJsonObject.getJSONObject("diskIo");
        //磁盘smart信息
        JSONObject diskSmartJson = agentJsonObject.getJSONObject("diskSmart");
        //文件防篡改监测信息
        JSONObject fileSafesJson = agentJsonObject.getJSONObject("fileSafes");
        String hostName = agentJsonObject.getStr("hostName");
 
        Date nowtime = new Date();
 
        if (StringUtils.isEmpty(bindIp)) {
            bindIp = hostName;//bindIp为空时候,用计算机名称
            logger.error("bindIp is null");
            if (StringUtils.isEmpty(bindIp)) {
                resultJson.set("result", "error:bindIp is null");
                return resultJson;
            }
        }
 
        try {
 
            //磁盘信息
            if (diskInfoListJson != null) {
                addDeskState(diskInfoListJson, nowtime, bindIp);
            }
            //磁盘IO信息
            if (diskIoJson != null) {
                addDeskIo(diskIoJson, nowtime, bindIp);
            }
 
            //磁盘smart信息
            if (diskSmartJson != null) {
                addDiskSmart(diskSmartJson, nowtime, bindIp);
            }
 
            //文件防篡改监测信息
            if (fileSafesJson != null) {
                addFileSafes(fileSafesJson, nowtime, bindIp);
            }
 
            resultJson.set("result", "success");
        } catch (Exception e) {
            logger.error("解析磁盘上报数据错误", e);
            resultJson.set("result", "error:" + e.toString());
        } finally {
            return resultJson;
        }
    }
 
 
    private void addDeskState(JSONObject diskInfoListJson, Date nowtime, String bindIp) {
        try {
            List<String> keys = new ArrayList<>(diskInfoListJson.keySet());
            for (String diskname : keys) {
                JSONObject diskJson = diskInfoListJson.getJSONObject(diskname);
                DiskState bean = new DiskState();
                bean.setFileSystem(diskname);
                bean.setHostname(bindIp);
                bean.setCreateTime(nowtime);
                bean.setUsed(FormatUtil.formatDouble((diskJson.getLong("used") / 1024.0 / 1024.0 / 1024.0), 2) + "G");
                bean.setAvail(FormatUtil.formatDouble((diskJson.getLong("free") / 1024.0 / 1024.0 / 1024.0), 2) + "G");
                bean.setDiskSize(FormatUtil.formatDouble((diskJson.getLong("total") / 1024.0 / 1024.0 / 1024.0), 2) + "G");
                bean.setUsePer(FormatUtil.formatDouble(diskJson.getDouble("usedPercent"), 2) + "%");
                BatchData.DISK_STATE_LIST.add(bean);
                Runnable runnable = () -> {
                    WarnMailUtil.sendDiskWarnInfo(bean);
                };
                ThreadPoolUtil.executor.execute(runnable);
            }
        } catch (Exception e) {
            logger.error("解析磁盘上报数据错误", e);
        }
    }
 
    private void addDeskIo(JSONObject diskIoListJson, Date nowtime, String bindIp) {
        try {
            List<String> keys = new ArrayList<>(diskIoListJson.keySet());
            for (String diskname : keys) {
                DeskIo ioBean = new DeskIo();
                JSONObject deskIoJsonObj = diskIoListJson.getJSONObject(diskname);
                if (null != deskIoJsonObj) {
                    ioBean.setFileSystem(diskname);
                    ioBean.setHostname(bindIp);
                    ioBean.setCreateTime(nowtime);
                    ioBean.setReadCount(deskIoJsonObj.getLong("readCount") + "");
                    ioBean.setWriteCount(deskIoJsonObj.getLong("writeCount") + "");
                    ioBean.setReadBytes((deskIoJsonObj.getLong("readBytes") / 1024 / 1024 / 1024) + "G");
                    ioBean.setWriteBytes((deskIoJsonObj.getLong("writeBytes") / 1024 / 1024 / 1024) + "G");
                    ioBean.setReadTime(deskIoJsonObj.getLong("readTime") + "");
                    ioBean.setWriteTime(deskIoJsonObj.getLong("writeTime") + "");
                    BatchData.DESK_IO_LIST.add(ioBean);
                }
            }
        } catch (Exception e) {
            logger.error("解析磁盘IO数据错误", e);
        }
    }
 
 
    private void addDiskSmart(JSONObject diskSmartListJson, Date nowtime, String bindIp) {
        List<String> keys = new ArrayList<>(diskSmartListJson.keySet());
        for (String diskname : keys) {
            try {
                DiskSmart smartBean = new DiskSmart();
                smartBean.setFileSystem(diskname);
                smartBean.setHostname(bindIp);
                smartBean.setCreateTime(nowtime);
                String[] smartStrs = diskSmartListJson.getStr(diskname).split(",");
                smartBean.setDiskState(smartStrs[0]);
                smartBean.setPowerHours(smartStrs[1]);
                smartBean.setPowerCount(smartStrs[2]);
                smartBean.setTemperature(smartStrs[3]);
                BatchData.DISK_SMART_LIST.add(smartBean);
                Runnable runnable = () -> {
                    WarnMailUtil.sendDiskSmartWarnInfo(smartBean);
                };
                ThreadPoolUtil.executor.execute(runnable);
            } catch (Exception e) {
                logger.error("解析磁盘smart数据错误", e);
            }
        }
 
    }
 
    private void addFileSafes(JSONObject fileSafeJson, Date nowtime, String bindIp) {
        List<String> keys = new ArrayList<>(fileSafeJson.keySet());
        for (String fileSafeId : keys) {
            try {
                String fileState = fileSafeJson.getStr(fileSafeId);
                String state = fileState.split(",")[0];
                String fileModtime = fileState.split(",")[1];
                FileSafe fileSafe = new FileSafe();
                fileSafe.setId(fileSafeId);
                fileSafe.setCreateTime(nowtime);
                fileSafe.setState(state);
                fileSafe.setFileModtime(DateUtil.secondToDate(Long.valueOf(fileModtime), "yyyy-MM-dd HH:mm:ss"));
                fileSafe.setHostname(bindIp);
 
                //文件防篡改校验失败,判定下线 begin
                if (!StaticKeys.ON_STATE.equals(state)) {
                    fileSafe.setState(StaticKeys.DOWN_STATE);
                    //下线后,不再更新时间戳
                    fileSafe.setCreateTime(null);
                    BatchData.FILE_SAFE_LIST.add(fileSafe);
                    Runnable runnable = () -> {
                        try {
                            FileSafe portInfoW = fileSafeService.selectById(fileSafeId);
                            if (portInfoW != null) {
                                WarnMailUtil.sendFileSafeDown(portInfoW, true);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
 
                    };
                    ThreadPoolUtil.executor.execute(runnable);
                    continue;
                }
                //文件防篡改校验失败,判定下线 end
                BatchData.FILE_SAFE_LIST.add(fileSafe);
            } catch (Exception e) {
                logger.error("解析文件防篡改监测信息上报数据错误", e);
            }
        }
 
    }
 
    /**
     * 查询agent是否在同一周期上报多次,多次不再受理
     *
     * @param bindIp
     * @return true存在,false不存在
     */
    private boolean isExists(String bindIp) {
        if (StringUtils.isEmpty(bindIp)) {
            return true;
        }
        for (DiskState deskState : BatchData.DISK_STATE_LIST) {
            if (deskState.getHostname().equals(bindIp)) {
                return true;
            }
        }
        for (DeskIo deskIo : BatchData.DESK_IO_LIST) {
            if (deskIo.getHostname().equals(bindIp)) {
                return true;
            }
        }
        for (DiskSmart diskSmart : BatchData.DISK_SMART_LIST) {
            if (diskSmart.getHostname().equals(bindIp)) {
                return true;
            }
        }
        return false;
    }
 
}