付延余
2022-12-16 f0f8ee8c4a945adbc742d9bab69382b28ad311fb
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package com.wgcloud.controller;
 
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.wgcloud.config.CommonConfig;
import com.wgcloud.dto.MessageDto;
import com.wgcloud.entity.AccountInfo;
import com.wgcloud.entity.DbInfo;
import com.wgcloud.service.DbInfoService;
import com.wgcloud.service.DbTableService;
import com.wgcloud.service.LogInfoService;
import com.wgcloud.util.*;
import com.wgcloud.util.jdbc.ConnectionUtil;
import com.wgcloud.util.jdbc.RDSConnection;
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.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * @version v3.3
 * @ClassName:DbInfoController.java
 * @author: http://www.wgstart.com
 * @date: 2021年1月16日
 * @Description: 数据源配置
 * @Copyright: 2019-2021 wgcloud. All rights reserved.
 */
@Controller
@RequestMapping("/dbInfo")
public class DbInfoController {
 
 
    private static final Logger logger = LoggerFactory.getLogger(DbInfoController.class);
 
    @Resource
    private DbInfoService dbInfoService;
    @Resource
    private DbTableService dbTableService;
    @Resource
    private LogInfoService logInfoService;
    @Resource
    private ConnectionUtil connectionUtil;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private MongoDbUtil mongoDbUtil;
    @Autowired
    private CommonConfig commonConfig;
    @Autowired
    private TokenUtils tokenUtils;
 
 
    /**
     * agent查询监控数据源列表
     *
     * @param paramBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "agentList")
    public String agentList(@RequestBody String paramBean) {
        JSONObject agentJsonObject = (JSONObject) JSONUtil.parse(paramBean);
        if (!tokenUtils.checkAgentToken(agentJsonObject)) {
            logger.error(StaticKeys.TOKEN_ERROR);
            return ResDataUtils.resetErrorJson(StaticKeys.TOKEN_ERROR);
        }
        Map<String, Object> params = new HashMap<String, Object>();
        try {
            if (null != agentJsonObject.get("dbInfoNames") && !StringUtils.isEmpty(agentJsonObject.get("dbInfoNames").toString())) {
                params.put("dbInfoNames", agentJsonObject.get("dbInfoNames").toString().split(","));
            }
            List<DbInfo> dbInfoList = dbInfoService.selectAllByParams(params);
            //数据源信息加密处理 begin
            for (DbInfo dbInfo : dbInfoList) {
                dbInfo.setUserName(DESUtil.encryption(dbInfo.getUserName()));
                dbInfo.setDbUrl(DESUtil.encryption(dbInfo.getDbUrl()));
                dbInfo.setPasswd(DESUtil.encryption(dbInfo.getPasswd()));
            }
            //数据源信息加密处理 end
 
            //将server-backup节点处理的数据源,标记起来,server节点就不监控这些数据源了
            ServerBackupUtil.cacheSaveDbInfoId(dbInfoList);
            return ResDataUtils.resetSuccessJson(dbInfoList);
        } catch (Exception e) {
            logger.error("agent获取监控数据源信息错误", e);
            logInfoService.save("agent获取监控数据源信息错误", e.toString(), StaticKeys.LOG_XTCZ);
            return ResDataUtils.resetErrorJson(e.toString());
        }
    }
 
    /**
     * 测试数据库连接
     *
     * @param model
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "validate")
    public String valdateDbInfo(DbInfo DbInfo, Model model, HttpServletRequest request) {
        MessageDto messageDto = new MessageDto();
        try {
            if (RDSConnection.KEY_REDIS.equals(DbInfo.getDbType())) {
                String pong = redisUtil.connectRedis(DbInfo);
                if (StringUtils.isEmpty(pong)) {
                    messageDto.setCode("1");
                    messageDto.setMsg("连接Redis错误,请检查参数是否正确。请在系统信息里查看日志");
                } else {
                    messageDto.setCode("0");
                    messageDto.setMsg("连接Redis成功");
                }
            } else if (RDSConnection.KEY_MONGODB.equals(DbInfo.getDbType())) {
                mongoDbUtil.connectMongoDb(DbInfo);
                if (StaticKeys.DOWN_STATE.equals(DbInfo.getDbState())) {
                    messageDto.setCode("1");
                    messageDto.setMsg("连接MongoDb错误,请检查参数是否正确。请在系统信息里查看日志");
                } else {
                    messageDto.setCode("0");
                    messageDto.setMsg("连接MongoDb成功");
                }
            } else {
                JdbcTemplate JdbcTemplate = connectionUtil.getJdbcTemplate(DbInfo);
                if (JdbcTemplate == null) {
                    messageDto.setCode("1");
                    messageDto.setMsg("连接数据库错误,请检查参数是否正确。请在系统信息里查看日志");
                } else {
                    messageDto.setCode("0");
                    messageDto.setMsg("连接数据库成功");
                }
            }
        } catch (Exception e) {
            logger.error("测试数据源信息错误", e);
            logInfoService.save("测试数据源信息错误", e.toString(), StaticKeys.LOG_XTCZ);
 
        }
        return JSONUtil.toJsonStr(messageDto);
    }
 
 
    /**
     * 根据条件查询列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "list")
    public String dbInfoList(DbInfo DbInfo, Model model, HttpServletRequest request) {
        Map<String, Object> params = new HashMap<String, Object>();
        try {
 
            StringBuffer url = new StringBuffer();
            if (!StringUtils.isEmpty(DbInfo.getAccount())) {
                params.put("account", DbInfo.getAccount());
                url.append("&account=").append(DbInfo.getAccount());
            }
 
            //校验是否需要添加过滤用户查询条件
            HostUtil.addAccountquery(request, params);
 
            PageInfo<DbInfo> pageInfo = dbInfoService.selectByParams(params, DbInfo.getPage(), DbInfo.getPageSize());
            //设置累积告警次数 begin
            if (StaticKeys.TRUE_VAL.equals(commonConfig.getShowWarnCount())) {
                Map<String, Object> paramsLogInfo = new HashMap<String, Object>();
                for (DbInfo dbInfo : pageInfo.getList()) {
                    String warnQueryWd = "数据源连接失败告警:" + dbInfo.getAliasName();
                    paramsLogInfo.clear();
                    paramsLogInfo.put("hostname", warnQueryWd);
                    dbInfo.setWarnCount(logInfoService.countByParams(paramsLogInfo));
                    dbInfo.setWarnQueryWd(warnQueryWd);
                }
            }
            //设置累积告警次数 end
 
            //设置数据库logo
            dbInfoService.dbAddLogo(pageInfo.getList());
 
            PageUtil.initPageNumber(pageInfo, model);
 
            //设置用户列表
            HostUtil.addAccountListModel(model);
 
            model.addAttribute("pageUrl", "/dbInfo/list?1=1" + url.toString());
            model.addAttribute("page", pageInfo);
        } catch (Exception e) {
            logger.error("查询数据源信息错误", e);
            logInfoService.save("查询数据源信息错误", e.toString(), StaticKeys.LOG_XTCZ);
 
        }
        return "mysql/dbList";
    }
 
 
    /**
     * 添加
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "edit")
    public String edit(Model model, HttpServletRequest request) {
        String errorMsg = "添加数据源错误";
        String id = request.getParameter("id");
        DbInfo dbInfo = new DbInfo();
        try {
 
            if (StringUtils.isEmpty(id)) {
                model.addAttribute("dbInfo", dbInfo);
                return "mysql/addDb";
            }
            dbInfo = dbInfoService.selectById(id);
            model.addAttribute("dbInfo", dbInfo);
        } catch (Exception e) {
            logger.error(errorMsg, e);
            logInfoService.save(errorMsg, e.toString(), StaticKeys.LOG_XTCZ);
        }
        return "mysql/addDb";
    }
 
 
    /**
     * 保存数据源信息
     *
     * @param DbInfo
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "save")
    public String saveDbInfo(DbInfo DbInfo, Model model, HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(DbInfo.getId())) {
                AccountInfo accountInfo = HostUtil.getAccountByRequest(request);
                if (null != accountInfo) {
                    if (!StaticKeys.ROLE_ADMIN.equals(accountInfo.getRole())) {
                        DbInfo.setAccount(accountInfo.getAccount());
                    }
                }
                dbInfoService.save(DbInfo);
                dbInfoService.saveLog(request, StaticKeys.LOG_ADD, DbInfo);
            } else {
                dbInfoService.updateById(DbInfo);
                dbInfoService.saveLog(request, StaticKeys.LOG_UPDATE, DbInfo);
            }
        } catch (Exception e) {
            logger.error("保存数据源错误", e);
            logInfoService.save("保存数据源错误", e.toString(), StaticKeys.LOG_XTCZ);
        }
        return "redirect:/dbInfo/list?msg=save";
    }
 
 
    /**
     * 删除数据源
     *
     * @param model
     * @param request
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "del")
    public String delete(Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        String errorMsg = "删除数据源信息错误";
        DbInfo DbInfo = new DbInfo();
        try {
            if (!StringUtils.isEmpty(request.getParameter("id"))) {
                String[] ids = request.getParameter("id").split(",");
                for (String id : ids) {
                    DbInfo = dbInfoService.selectById(id);
                    dbInfoService.saveLog(request, StaticKeys.LOG_DEL, DbInfo);
                    dbTableService.deleteByDbInfoId(DbInfo.getId());
                }
                dbInfoService.deleteById(ids);
            }
        } catch (Exception e) {
            logger.error(errorMsg, e);
            logInfoService.save(errorMsg, e.toString(), StaticKeys.LOG_XTCZ);
        }
        return "redirect:/dbInfo/list?msg=del";
    }
 
}