diff options
| author | wangwenrui <[email protected]> | 2020-11-20 21:25:22 +0800 |
|---|---|---|
| committer | wangwenrui <[email protected]> | 2020-11-20 21:25:22 +0800 |
| commit | 6bf8f563ca8cb99b342ad42c2686bdab2bdedc07 (patch) | |
| tree | 61666367f44c5e22372c7d28fd6e9ff017059485 | |
| parent | 9b3c010eeb0f64a6c452f552062fdc412b7a079e (diff) | |
feat:code scanner init upload
| -rw-r--r-- | .classpath | 65 | ||||
| -rw-r--r-- | .settings/org.eclipse.jdt.core.prefs | 13 | ||||
| -rw-r--r-- | src/main/java/com/nis/job/ConfagentJob.java | 47 | ||||
| -rw-r--r-- | src/main/java/com/nis/server/SNMPTrapServer.java | 917 | ||||
| -rw-r--r-- | src/main/java/com/nis/service/impl/TrafficServiceImpl.java | 3 | ||||
| -rw-r--r-- | src/main/java/com/nis/util/BufferReaderWrapper.java | 15 | ||||
| -rw-r--r-- | src/main/java/com/nis/util/Constant.java | 2 | ||||
| -rw-r--r-- | src/main/java/com/nis/util/LogPrintUtil.java | 14 | ||||
| -rw-r--r-- | src/main/java/com/nis/util/MybatisPlusConfig.java | 2 | ||||
| -rw-r--r-- | src/main/java/com/nis/util/RuntimeUtil.java | 675 | ||||
| -rw-r--r-- | src/main/java/com/nis/util/SnmpUtil.java | 6 | ||||
| -rw-r--r-- | src/main/java/com/nis/util/YamlUtil.java | 914 |
12 files changed, 1334 insertions, 1339 deletions
@@ -1,32 +1,33 @@ -<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" output="target/classes" path="src/main/java">
- <attributes>
- <attribute name="optional" value="true"/>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5"/>
- <classpathentry kind="src" output="target/test-classes" path="src/test/java">
- <attributes>
- <attribute name="optional" value="true"/>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
- <attributes>
- <attribute name="maven.pomderived" value="true"/>
- </attributes>
- </classpathentry>
- <classpathentry kind="output" path="target/classes"/>
-</classpath>
+<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="src" output="target/classes" path="src/main/java"> + <attributes> + <attribute name="optional" value="true"/> + <attribute name="maven.pomderived" value="true"/> + </attributes> + </classpathentry> + <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"> + <attributes> + <attribute name="maven.pomderived" value="true"/> + </attributes> + </classpathentry> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"> + <attributes> + <attribute name="maven.pomderived" value="true"/> + </attributes> + </classpathentry> + <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5"/> + <classpathentry kind="src" output="target/test-classes" path="src/test/java"> + <attributes> + <attribute name="optional" value="true"/> + <attribute name="maven.pomderived" value="true"/> + <attribute name="test" value="true"/> + </attributes> + </classpathentry> + <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"> + <attributes> + <attribute name="maven.pomderived" value="true"/> + </attributes> + </classpathentry> + <classpathentry kind="output" path="target/classes"/> +</classpath> diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs index d59e09c..2f5cc74 100644 --- a/.settings/org.eclipse.jdt.core.prefs +++ b/.settings/org.eclipse.jdt.core.prefs @@ -1,5 +1,8 @@ -eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
-org.eclipse.jdt.core.compiler.compliance=1.8
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
-org.eclipse.jdt.core.compiler.source=1.8
+eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/src/main/java/com/nis/job/ConfagentJob.java b/src/main/java/com/nis/job/ConfagentJob.java index f7389b3..b4426ed 100644 --- a/src/main/java/com/nis/job/ConfagentJob.java +++ b/src/main/java/com/nis/job/ConfagentJob.java @@ -1,9 +1,11 @@ package com.nis.job; import com.alibaba.fastjson.JSON; +import com.mchange.v2.log.LogUtils; import com.nis.entity.*; import com.nis.service.*; import com.nis.util.Constant; +import com.nis.util.LogPrintUtil; import com.nis.util.YamlUtil; import org.apache.commons.lang3.StringUtils; import org.quartz.JobExecutionContext; @@ -18,6 +20,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.scheduling.quartz.QuartzJobBean; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; +import sun.rmi.runtime.Log; import java.util.*; import java.util.stream.Collectors; @@ -61,6 +64,8 @@ public class ConfagentJob extends QuartzJobBean { @Value("${confagent.promServerType}") private Integer promServerType; + @Value("${http.protocol:http}") + private String httpProtocol; @Autowired private RedisTemplate<Object,Object> redisTemplate; @@ -116,17 +121,16 @@ public class ConfagentJob extends QuartzJobBean { ResponseEntity<String> responseEntity = null; try { RestTemplate restTemplate = new RestTemplate(); - responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); + responseEntity = restTemplate.postForEntity(String.format("%s://%s:%s%s",httpProtocol, ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); } catch (RestClientException e) { - logger.error("热加载 global prometheus api 接口失败,API 地址是:" + String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD) + ",错误信息是:" + e.getMessage(), e); + logger.error("热加载 global prometheus api 接口失败,API 地址是:{},错误信息是:{}" , String.format("%s://%s:%s%s",httpProtocol, ipaddr, promServerPort, Constant.API_RELOAD), LogPrintUtil.print(e)); } if (responseEntity != null && responseEntity.getStatusCodeValue() == 200) { - logger.info(String.format("http://%s:%s", ipaddr, promServerPort) + " global prometheus 热加载配置文件成功"); + logger.info(String.format("%s://%s:%s%s",httpProtocol,ipaddr, promServerPort) + " global prometheus 热加载配置文件成功"); } } } catch (Exception e) { - logger.error("yamlHanlde center error", e); - e.printStackTrace(); + logger.error("yamlHanlde center error{}", LogPrintUtil.print(e)); } } } else if (promserverType.equals(Constant.PromserverType.PER_DATACENTER.getValue())) {// datacenter角色 @@ -142,17 +146,16 @@ public class ConfagentJob extends QuartzJobBean { ResponseEntity<String> responseEntity = null; try { RestTemplate restTemplate = new RestTemplate(); - responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); + responseEntity = restTemplate.postForEntity(String.format("%s://%s:%s%s", httpProtocol,ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); } catch (RestClientException e) { - logger.error("热加载 per-datacenter prometheus api 接口失败,API 地址是:" + String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD) + ",错误信息是:" + e.getMessage(), e); + logger.error("热加载 per-datacenter prometheus api 接口失败,API 地址是:{},错误信息是:{}" , String.format("%s://%s:%s%s",httpProtocol, ipaddr, promServerPort, Constant.API_RELOAD) ,LogPrintUtil.print(e)); } if (responseEntity != null && responseEntity.getStatusCodeValue() == 200) { - logger.info(String.format("http://%s:%s", ipaddr, promServerPort) + " per datacenter prometheus 热加载配置文件成功"); + logger.info(String.format("%s://%s:%s",httpProtocol, ipaddr, promServerPort) + " per datacenter prometheus 热加载配置文件成功"); } } } catch (Exception e) { - logger.error("yamlHanlde sub error", e); - e.printStackTrace(); + logger.error("yamlHanlde sub error{}", LogPrintUtil.print(e)); } } } @@ -168,17 +171,16 @@ public class ConfagentJob extends QuartzJobBean { ResponseEntity<String> responseEntity = null; try { RestTemplate restTemplate = new RestTemplate(); - responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); + responseEntity = restTemplate.postForEntity(String.format("%s://%s:%s%s",httpProtocol, ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); } catch (RestClientException e) { - logger.error("热加载 prometheusSettingHandle 接口失败,API 地址是:" + String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD) + ",错误信息是:" + e.getMessage(), e); + logger.error("热加载 prometheusSettingHandle 接口失败,API 地址是:" + String.format("%s://%s:%s%s",httpProtocol, ipaddr, promServerPort, Constant.API_RELOAD) + ",错误信息是:" + e.getMessage(), e); } if (responseEntity != null && responseEntity.getStatusCodeValue() == 200) { - logger.info(String.format("http://%s:%s", ipaddr, promServerPort) + " prometheusSettingHandle 热加载配置文件成功"); + logger.info(String.format("%s://%s:%s",httpProtocol, ipaddr, promServerPort) + " prometheusSettingHandle 热加载配置文件成功"); } } } catch (Exception e) { - logger.error("prometheus global setting error : ", e); - e.printStackTrace(); + logger.error("prometheus global setting error :{} ", LogPrintUtil.print(e)); } //prometheus启动项相关修改 每次需要判断是否更改来确定是否执行方法 会关闭prometheus并重启 confagent首次启动不会进行prometheus开关操作 @@ -199,8 +201,7 @@ public class ConfagentJob extends QuartzJobBean { } } } catch (Exception e) { - logger.error("prometheus startup setting error : ", e); - e.printStackTrace(); + logger.error("prometheus startup setting error : {}", LogPrintUtil.print(e)); } } else if (promserverType.equals(Constant.PromserverType.THANOS_RULE.getValue())) { // thanos rule 处理 @@ -216,12 +217,12 @@ public class ConfagentJob extends QuartzJobBean { ResponseEntity<String> responseEntity = null; try { RestTemplate restTemplate = new RestTemplate(); - responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); + responseEntity = restTemplate.postForEntity(String.format("%s://%s:%s%s", httpProtocol,ipaddr, promServerPort, Constant.API_RELOAD), null, String.class); } catch (RestClientException e) { - logger.error("热加载 thanos rule api 接口失败,API 地址是:" + String.format("http://%s:%s%s", ipaddr, promServerPort, Constant.API_RELOAD) + ",错误信息是:" + e.getMessage(), e); + logger.error("热加载 thanos rule api 接口失败,API 地址是:{},错误信息是:{}" , String.format("%s://%s:%s%s",httpProtocol, ipaddr, promServerPort, Constant.API_RELOAD) ,LogPrintUtil.print(e)); } if (responseEntity != null && responseEntity.getStatusCodeValue() == 200) { - logger.info(String.format("http://%s:%s", ipaddr, promServerPort) + " thanos rule 热加载配置文件成功"); + logger.info(String.format("%s://%s:%s",httpProtocol,ipaddr, promServerPort) + " thanos rule 热加载配置文件成功"); } } } @@ -361,12 +362,12 @@ public class ConfagentJob extends QuartzJobBean { ResponseEntity<String> responseEntity = null; try { RestTemplate restTemplate = new RestTemplate(); - responseEntity = restTemplate.postForEntity(String.format("http://%s:%s%s", ipaddr, snmpPort, Constant.API_RELOAD), null, String.class); + responseEntity = restTemplate.postForEntity(String.format("%s://%s:%s%s",httpProtocol, ipaddr, snmpPort, Constant.API_RELOAD), null, String.class); } catch (RestClientException e) { - logger.error("热加载 snmp_exporter api 接口失败,API 地址是:" + String.format("http://%s:%s%s", ipaddr, snmpPort, Constant.API_RELOAD) + ",错误信息是:" + e.getMessage(), e); + logger.error("热加载 snmp_exporter api 接口失败,API 地址是:{},错误信息是:{}", String.format("%s://%s:%s%s",httpProtocol, ipaddr, snmpPort, Constant.API_RELOAD),LogPrintUtil.print(e)); } if (responseEntity != null && responseEntity.getStatusCodeValue() == 200) { - logger.info(String.format("http://%s:%s", ipaddr, snmpPort) + " snmp_exporter 热加载配置文件成功"); + logger.info(String.format("%s://%s:%s",httpProtocol, ipaddr, snmpPort) + " snmp_exporter 热加载配置文件成功"); } } } diff --git a/src/main/java/com/nis/server/SNMPTrapServer.java b/src/main/java/com/nis/server/SNMPTrapServer.java index 29a9c95..82c183e 100644 --- a/src/main/java/com/nis/server/SNMPTrapServer.java +++ b/src/main/java/com/nis/server/SNMPTrapServer.java @@ -1,458 +1,459 @@ -package com.nis.server;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
-import javax.annotation.PostConstruct;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.snmp4j.CommandResponder;
-import org.snmp4j.CommandResponderEvent;
-import org.snmp4j.MessageDispatcherImpl;
-import org.snmp4j.PDU;
-import org.snmp4j.PDUv1;
-import org.snmp4j.Snmp;
-import org.snmp4j.TransportMapping;
-import org.snmp4j.mp.MPv1;
-import org.snmp4j.mp.MPv2c;
-import org.snmp4j.mp.MPv3;
-import org.snmp4j.mp.SnmpConstants;
-import org.snmp4j.security.AuthMD5;
-import org.snmp4j.security.AuthSHA;
-import org.snmp4j.security.PrivAES128;
-import org.snmp4j.security.PrivAES192;
-import org.snmp4j.security.PrivAES256;
-import org.snmp4j.security.PrivDES;
-import org.snmp4j.security.SecurityModels;
-import org.snmp4j.security.SecurityProtocols;
-import org.snmp4j.security.USM;
-import org.snmp4j.smi.Address;
-import org.snmp4j.smi.GenericAddress;
-import org.snmp4j.smi.OID;
-import org.snmp4j.smi.OctetString;
-import org.snmp4j.smi.TcpAddress;
-import org.snmp4j.smi.UdpAddress;
-import org.snmp4j.smi.Variable;
-import org.snmp4j.smi.VariableBinding;
-import org.snmp4j.transport.DefaultTcpTransportMapping;
-import org.snmp4j.transport.DefaultUdpTransportMapping;
-import org.snmp4j.util.MultiThreadedMessageDispatcher;
-import org.snmp4j.util.ThreadPool;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.boot.ApplicationArguments;
-import org.springframework.boot.ApplicationRunner;
-import org.springframework.core.annotation.Order;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
-import org.springframework.http.converter.StringHttpMessageConverter;
-import org.springframework.stereotype.Component;
-import org.springframework.stereotype.Service;
-import org.springframework.web.client.RestTemplate;
-
-import com.alibaba.fastjson.JSON;
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.JSONObject;
-import com.nis.entity.AlertManagerEnum;
-import com.nis.entity.AlertRule;
-import com.nis.entity.ConfagentMetrics;
-import com.nis.entity.SysConfig;
-import com.nis.entity.TrapMessage;
-import com.nis.service.AlertRuleService;
-import com.nis.service.SysConfigService;
-
-
-
-
-/**
- * 本类用于监听代理进程的Trap信息
- * 1.加载alert_rule表内置规则(有且只有一条)
- * 2.启动snmp_server
- * 3.接收trap信息
- * 4.组装prometheus_alert格式
- * 5.发送到web端接口处理
- *
- * @author YJS
- *
- */
-@Component
-@Order(1)
-public class SNMPTrapServer implements CommandResponder,ApplicationRunner{// implements CommandResponder, extends Service
- private static Logger logger = LoggerFactory.getLogger(SNMPTrapServer.class);
- private static SNMPTrapServer ts = null;
- @Value("${confagent.snmp.trapThredPoolSize}")
- private String snmpTrapThredPoolSize;
- @Value("${confagent.snmp.trapPort}")
- private String snmpTrapPort;
- @Autowired
- private AlertRuleService alertRuleService;
- @Autowired
- private SysConfigService sysConfigService;
- private String alertApi;
- private String alertPathPrefix;
- @Autowired
- private ConfagentMetrics confagentMetrics;
-
- @Override
- public void run(ApplicationArguments args) throws Exception {
- initServer();
- }
-
- public void initServer() throws Exception{
- logger.info("snmpTrapThredPoolSize is {}",snmpTrapThredPoolSize);
- ThreadPool threadPool = ThreadPool.create("Trap", Integer.valueOf(snmpTrapThredPoolSize));
- logger.info("snmpTrapThredPoolSize is {}",snmpTrapThredPoolSize);
- MultiThreadedMessageDispatcher dispatcher = new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());
- Address listenAddress = GenericAddress.parse(System.getProperty("snmp4j.listenAddress", "udp:0.0.0.0/" + snmpTrapPort)); // 本地IP与监听端口
- logger.info("snmpTrapPort is {}",snmpTrapPort);
- TransportMapping transport = null;
-
-// 对TCP与UDP协议进行处理
- if (listenAddress instanceof UdpAddress) {
- transport = new DefaultUdpTransportMapping((UdpAddress) listenAddress);
- logger.debug("this listenAddress type is UDP");
- } else {
- transport = new DefaultTcpTransportMapping((TcpAddress) listenAddress);
- logger.debug("this listenAddress type is TCP");
- }
-
- Snmp snmp = new Snmp(dispatcher, transport);
- snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1());
- snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c());
- snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3());
- USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
- SecurityModels.getInstance().addSecurityModel(usm);
- snmp.listen();
- snmp.addCommandResponder(this);
- }
-
- private OID getAuthProtocol(String auth){
- if (auth.equals("MD5")) {
- return AuthMD5.ID;
- } else if (auth.equals("SHA")) {
- return AuthSHA.ID;
- }else{
- return null;
- }
- }
-
- private OID getPrivProtocol(String priv){
- if (priv.equals("DES")) {
- return PrivDES.ID;
- } else if ((priv.equals("AES128"))
- || (priv.equals("AES"))) {
- return PrivAES128.ID;
- } else if (priv.equals("AES192")) {
- return PrivAES192.ID;
- } else if (priv.equals("AES256")) {
- return PrivAES256.ID;
- }else{
- return null;
- }
- }
-
-
-
-
- /**
- * 实现CommandResponder的processPdu方法, 用于处理传入的请求、PDU等信息 当接收到trap时,会自动进入这个方法
- *
- * @param respEvnt
- */
-
- public void processPdu(CommandResponderEvent commandresponderevent)
- {
- try
- {
- //考虑数据库数据可能存在变化 由仅查询一次更改为每次都确认一下数据信息
- //加载alert_rule表内置规则
- AlertRule alertRule=alertRuleService.queryBulidInRule();
- List<SysConfig> sysConfigs = sysConfigService.queryList();
- if(!sysConfigs.isEmpty()) {
- for(SysConfig sysconfig : sysConfigs) {
- if(sysconfig.getParamKey().equals(AlertManagerEnum.ALERT_API.getValue())) {
- alertApi=sysconfig.getParamValue();
- }else if(sysconfig.getParamKey().equals(AlertManagerEnum.ALERT_PATH_PREFIX.getValue())){
- alertPathPrefix=sysconfig.getParamValue();
- }
- }
- logger.info("sysconfig alert api info {}",alertApi);
- logger.info("sysconfig alert path prefix info {}",alertPathPrefix);
- }else {
- logger.error("Sysconfig missing alert_api or alert_path_prefix data");
- return;
- }
- logger.info("processPdu start");
- logger.info("alertRule info is {}",JSON.toJSON(alertRule));
- if(alertRule==null) {
- logger.error(" alert rule info is null ");
- return;
- }
- logger.info((new StringBuilder("receive snmp event:")).append(commandresponderevent.getPDU()).toString());
- UdpAddress udpaddress = (UdpAddress)commandresponderevent.getPeerAddress();
- String s = udpaddress.getInetAddress().getHostAddress();
- PDU pdu = commandresponderevent.getPDU();
- logger.info((new StringBuilder("receive TRap:")).append(pdu).toString());
- TrapMessage trapmessageinfo = new TrapMessage();
- trapmessageinfo.setAgentSendIP(s);
- setOIDList(trapmessageinfo, pdu);
- setValueList(trapmessageinfo, pdu);
- trapmessageinfo.setOriginalPDU(pdu);
- if (pdu instanceof PDUv1)
- {
- PDUv1 pduv1 = (PDUv1)pdu;
- trapmessageinfo.setTrapVersion(1);
- String s1 = pduv1.getEnterprise().toString();
- trapmessageinfo.setTrapOID(s1);
- String s2 = pduv1.getAgentAddress().toString();
- trapmessageinfo.setPduAgentIP(s);
- trapmessageinfo.setTrapV1SpecificType(pduv1.getSpecificTrap());
- trapmessageinfo.setTrapV1GenericType(pduv1.getGenericTrap());
- trapmessageinfo.setTrapName(trapmessageinfo.getTrapOID());
- switch (pduv1.getGenericTrap())
- {
- case 0: // '\0'
-// trapmessageinfo.setTrapName("设备冷启动");
- trapmessageinfo.setTrapName("Device Cold Start");
- break;
-
- case 1: // '\001'
-// trapmessageinfo.setTrapName("设备热启动");
- trapmessageinfo.setTrapName("Device Hot Start");
- break;
-
- case 2: // '\002'
-// trapmessageinfo.setTrapName("接口关闭");
- trapmessageinfo.setTrapName("The Interface Is Closed");
- break;
-
- case 3: // '\003'
-// trapmessageinfo.setTrapName("接口启用");
- trapmessageinfo.setTrapName("Interface Enabled");
- break;
-
- case 4: // '\004'
-// trapmessageinfo.setTrapName("SNMP认证失败");
- trapmessageinfo.setTrapName("SNMP Authentication Failed");
- break;
-
- case 5: // '\005'
-// trapmessageinfo.setTrapName("EGP邻居丢失");
- trapmessageinfo.setTrapName("EGP Neighbor Lost");
- break;
- }
- } else
- {
- trapmessageinfo.setTrapVersion(2);
- Variable variable = trapmessageinfo.getOIDValue(SnmpConstants.snmpTrapAddress.toString());
- logger.info("pdu.snmpTrapAddress() =-=-= "+variable);
- if (variable != null)
- trapmessageinfo.setPduAgentIP(variable.toString());
- Variable variable1 = trapmessageinfo.getOIDValue(SnmpConstants.snmpTrapOID.toString());
- if (variable1 != null)
- trapmessageinfo.setTrapOID(variable1.toString());
- trapmessageinfo.setTrapName(trapmessageinfo.getTrapOID());
- if (variable1 != null)
- if (variable1.equals(SnmpConstants.coldStart))
-// trapmessageinfo.setTrapName("设备冷启动");
- trapmessageinfo.setTrapName("Device Cold Start");
- else
- if (variable1.equals(SnmpConstants.warmStart))
-// trapmessageinfo.setTrapName("设备热启动");
- trapmessageinfo.setTrapName("Device Hot Start");
- else
- if (variable1.equals(SnmpConstants.linkDown))
-// trapmessageinfo.setTrapName("接口关闭");
- trapmessageinfo.setTrapName("The Interface Is Closed");
- else
- if (variable1.equals(SnmpConstants.linkUp))
-// trapmessageinfo.setTrapName("接口启用");
- trapmessageinfo.setTrapName("Interface Enabled");
- else
- if (variable1.equals(SnmpConstants.authenticationFailure))
-// trapmessageinfo.setTrapName("SNMP认证失败");
- trapmessageinfo.setTrapName("SNMP Authentication Failed");
- /*else //系统默认的类别不能匹配时,再使用自定义的trap信息库。是否需要分别自定义snmpV1和snmpValue2的trap信息库(定义到文件或者定义到数据库,必须体统重新加载的界面接口)
- if(getTrapName(variable1)!=null &&!variable1.equals("")){
- trapmessageinfo.setTrapName(getTrapName(variable1));
- }else{
-// throw new Exception("未被定义的SNMPTRAP类型!");
- throw new Exception("Undefined SNMPTRAP type!");
- }*/
- }
- StringBuffer trapInfo = new StringBuffer();
- trapInfo.append("trapmessageinfo.getTrapName():"+trapmessageinfo.getTrapName());
- trapInfo.append("; trapmessageinfo.getAgentSendIP():"+trapmessageinfo.getAgentSendIP());
- trapInfo.append("; trapmessageinfo.getOriginalPDU():"+trapmessageinfo.getOriginalPDU());
- trapInfo.append("; trapmessageinfo.getTrapVersion():"+trapmessageinfo.getTrapVersion());
- trapInfo.append("; trapmessageinfo.getTrapOID():"+trapmessageinfo.getTrapOID());
- trapInfo.append("; trapmessageinfo.getPduAgentIP():"+trapmessageinfo.getPduAgentIP());
- trapInfo.append("; trapmessageinfo.getTrapV1GenericType():"+trapmessageinfo.getTrapV1GenericType());
- trapInfo.append("; trapmessageinfo.getTrapV1SpecificType():"+trapmessageinfo.getTrapV1SpecificType());
- logger.info("agent IP:"+s+" trap message:"+trapInfo.toString());
-
- // 组装prometheus_alert格式
- Integer alertName = alertRule.getId();
- String severity = alertRule.getSeverity();
- String asset = trapmessageinfo.getAgentSendIP();
- String oid = trapmessageinfo.getTrapOID();
- String value=trapmessageinfo.getOriginalPDU().getVariableBindings().toString();
-
- StringBuilder description = new StringBuilder();
- description.append("version:"+trapmessageinfo.getTrapVersion());
- description.append(",agentip:"+trapmessageinfo.getAgentSendIP());
- description.append(",oid:"+trapmessageinfo.getTrapOID());
- description.append(",value:"+value);
- String trapName = trapmessageinfo.getTrapName();
- if(trapName!=null&&trapName.length()>0) {
- description.append(",trapName:"+trapName);
- }
- StringBuilder summary=new StringBuilder("snmptrap:");
- summary.append(trapmessageinfo.getAgentSendIP()+"(");
- summary.append(trapmessageinfo.getTrapOID()+":"+value+")");
- boolean snmptrap=true;
- SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
- String startsAt = sdf.format(new Date());
-
- JSONObject labels =new JSONObject();
- labels.put("alertname", alertName.toString());
- labels.put("severity",severity);
- labels.put("asset", asset);
- labels.put("oid", oid);
-
- JSONObject annotations =new JSONObject();
- annotations.put("description", description.toString());
- annotations.put("summary", summary.toString());
-
- JSONObject result =new JSONObject();
- result.put("labels", labels);
- result.put("annotations", annotations);
- result.put("snmptrap", snmptrap);
- result.put("startsAt", startsAt);
-
- JSONArray mess =new JSONArray();
- mess.add(result);
-
- logger.info("send alert info is {}",JSON.toJSON(mess));
-
- // 将告警信息发送到web端处理
- RestTemplate restTemplate=new RestTemplate();
- restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
- MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
- HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON);
- HttpEntity entity =new HttpEntity(mess,headers);
- String url="http://"+alertApi+alertPathPrefix+"/api/v1/alerts";
- Object postForEntity = restTemplate.postForEntity(url, entity,Object.class);
- logger.info("post success info {}",JSON.toJSON(postForEntity));
- confagentMetrics.snmpCounter.increment();
- }
- catch (Exception exception)
- {
- exception.printStackTrace();
- logger.error("Error parsing UDP trap: {}",exception.getMessage());
- }finally{
-
- }
- }
-
- public String getTrapName(Variable variable1){
- String trapName = "";
- Map allTrapTypeDefine = new HashMap();
- trapName = allTrapTypeDefine.get(variable1.toString()).toString();
- return trapName;
- }
-
- void setOIDList(TrapMessage trapmessageinfo, PDU pdu)
- {
- Vector vector = pdu.getVariableBindings();
- String s;
-
- for (Iterator iterator = vector.iterator(); iterator.hasNext(); trapmessageinfo.getTrapPDUOIDs().add(s))
- {
- VariableBinding variablebinding = (VariableBinding)iterator.next();
- s = variablebinding.getOid().toString();
- }
-
- }
-
- void setValueList(TrapMessage trapmessageinfo, PDU pdu)
- {
- Vector vector = pdu.getVariableBindings();
- Variable variable;
- for (Iterator iterator = vector.iterator(); iterator.hasNext(); trapmessageinfo.getTrapPDUOIDValues().add(variable))
- {
- VariableBinding variablebinding = (VariableBinding)iterator.next();
- variable = variablebinding.getVariable();
- }
-
- }
-
-
- /** */
- /**
- * 解决snmp4j中文乱码问题
- */
- public static String getChinese(String octetString) {
- try {
- String[] temps = octetString.split(":");
- byte[] bs = new byte[temps.length];
- for (int i = 0; i < temps.length; i++)
- bs[i] = (byte) Integer.parseInt(temps[i], 16);
-
- return new String(bs, "GB2312");
- } catch (Exception e) {
- return null;
- }
- }
-
- /*protected static String printVariableBindings(PDU response) {
- String strCom = "";
- for (int i = 0; i < response.size(); i++) {
- VariableBinding vb = response.get(i);
- String[] str = vb.getVariable().toString().toUpperCase().split(":");
-
- String strOut = "";
- int intLength = str.length;
- System.out.println("长度==> " + intLength);
- for (int j = 0; j < intLength; j++) {
- strOut += str[j];
- }
- strCom += vb.getVariable();
- if (str.length != 1) {
- System.out.println("==第行=vb.getVariable()=" + SNMPTrapServer.toStringHex(strOut));//显示中文
- }
- }
- return strCom;
-
- }*/
-
- /**
- * 将十进六制转换成为中文
- */
- private static String hexString = "0123456789ABCDEF";
-
- public static String toStringHex(String bytes) {
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream(
- bytes.length() / 2);
- //将每2位16进制整数组装成一个字节
- for (int i = 0; i < bytes.length(); i += 2) {
- baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
- .indexOf(bytes.charAt(i + 1))));
- }
- return new String(baos.toByteArray());
- }
-}
+package com.nis.server; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import javax.annotation.PostConstruct; + +import com.nis.util.LogPrintUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.snmp4j.CommandResponder; +import org.snmp4j.CommandResponderEvent; +import org.snmp4j.MessageDispatcherImpl; +import org.snmp4j.PDU; +import org.snmp4j.PDUv1; +import org.snmp4j.Snmp; +import org.snmp4j.TransportMapping; +import org.snmp4j.mp.MPv1; +import org.snmp4j.mp.MPv2c; +import org.snmp4j.mp.MPv3; +import org.snmp4j.mp.SnmpConstants; +import org.snmp4j.security.AuthMD5; +import org.snmp4j.security.AuthSHA; +import org.snmp4j.security.PrivAES128; +import org.snmp4j.security.PrivAES192; +import org.snmp4j.security.PrivAES256; +import org.snmp4j.security.PrivDES; +import org.snmp4j.security.SecurityModels; +import org.snmp4j.security.SecurityProtocols; +import org.snmp4j.security.USM; +import org.snmp4j.smi.Address; +import org.snmp4j.smi.GenericAddress; +import org.snmp4j.smi.OID; +import org.snmp4j.smi.OctetString; +import org.snmp4j.smi.TcpAddress; +import org.snmp4j.smi.UdpAddress; +import org.snmp4j.smi.Variable; +import org.snmp4j.smi.VariableBinding; +import org.snmp4j.transport.DefaultTcpTransportMapping; +import org.snmp4j.transport.DefaultUdpTransportMapping; +import org.snmp4j.util.MultiThreadedMessageDispatcher; +import org.snmp4j.util.ThreadPool; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.nis.entity.AlertManagerEnum; +import com.nis.entity.AlertRule; +import com.nis.entity.ConfagentMetrics; +import com.nis.entity.SysConfig; +import com.nis.entity.TrapMessage; +import com.nis.service.AlertRuleService; +import com.nis.service.SysConfigService; + + + + +/** + * 本类用于监听代理进程的Trap信息 + * 1.加载alert_rule表内置规则(有且只有一条) + * 2.启动snmp_server + * 3.接收trap信息 + * 4.组装prometheus_alert格式 + * 5.发送到web端接口处理 + * + * @author YJS + * + */ +@Component +@Order(1) +public class SNMPTrapServer implements CommandResponder,ApplicationRunner{// implements CommandResponder, extends Service + private static Logger logger = LoggerFactory.getLogger(SNMPTrapServer.class); + private static SNMPTrapServer ts = null; + @Value("${confagent.snmp.trapThredPoolSize}") + private String snmpTrapThredPoolSize; + @Value("${confagent.snmp.trapPort}") + private String snmpTrapPort; + @Autowired + private AlertRuleService alertRuleService; + @Autowired + private SysConfigService sysConfigService; + private String alertApi; + private String alertPathPrefix; + @Autowired + private ConfagentMetrics confagentMetrics; + + @Override + public void run(ApplicationArguments args) throws Exception { + // initServer(); + } + + public void initServer() throws Exception{ + logger.info("snmpTrapThredPoolSize is {}",snmpTrapThredPoolSize); + ThreadPool threadPool = ThreadPool.create("Trap", Integer.valueOf(snmpTrapThredPoolSize)); + logger.info("snmpTrapThredPoolSize is {}",snmpTrapThredPoolSize); + MultiThreadedMessageDispatcher dispatcher = new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl()); + Address listenAddress = GenericAddress.parse(System.getProperty("snmp4j.listenAddress", "udp:0.0.0.0/" + snmpTrapPort)); // 本地IP与监听端口 + logger.info("snmpTrapPort is {}",snmpTrapPort); + TransportMapping transport = null; + +// 对TCP与UDP协议进行处理 + if (listenAddress instanceof UdpAddress) { + transport = new DefaultUdpTransportMapping((UdpAddress) listenAddress); + logger.debug("this listenAddress type is UDP"); + } else { + transport = new DefaultTcpTransportMapping((TcpAddress) listenAddress); + logger.debug("this listenAddress type is TCP"); + } + + Snmp snmp = new Snmp(dispatcher, transport); + snmp.getMessageDispatcher().addMessageProcessingModel(new MPv1()); + snmp.getMessageDispatcher().addMessageProcessingModel(new MPv2c()); + snmp.getMessageDispatcher().addMessageProcessingModel(new MPv3()); + USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0); + SecurityModels.getInstance().addSecurityModel(usm); + snmp.listen(); + snmp.addCommandResponder(this); + } + + private OID getAuthProtocol(String auth){ + if (auth.equals("MD5")) { + return AuthMD5.ID; + } else if (auth.equals("SHA")) { + return AuthSHA.ID; + }else{ + return null; + } + } + + private OID getPrivProtocol(String priv){ + if (priv.equals("DES")) { + return PrivDES.ID; + } else if ((priv.equals("AES128")) + || (priv.equals("AES"))) { + return PrivAES128.ID; + } else if (priv.equals("AES192")) { + return PrivAES192.ID; + } else if (priv.equals("AES256")) { + return PrivAES256.ID; + }else{ + return null; + } + } + + + + + /** + * 实现CommandResponder的processPdu方法, 用于处理传入的请求、PDU等信息 当接收到trap时,会自动进入这个方法 + * + * @param commandresponderevent + */ + + public void processPdu(CommandResponderEvent commandresponderevent) + { + try + { + //考虑数据库数据可能存在变化 由仅查询一次更改为每次都确认一下数据信息 + //加载alert_rule表内置规则 + AlertRule alertRule=alertRuleService.queryBulidInRule(); + List<SysConfig> sysConfigs = sysConfigService.queryList(); + if(!sysConfigs.isEmpty()) { + for(SysConfig sysconfig : sysConfigs) { + if(sysconfig.getParamKey().equals(AlertManagerEnum.ALERT_API.getValue())) { + alertApi=sysconfig.getParamValue(); + }else if(sysconfig.getParamKey().equals(AlertManagerEnum.ALERT_PATH_PREFIX.getValue())){ + alertPathPrefix=sysconfig.getParamValue(); + } + } + logger.info("sysconfig alert api info {}",alertApi); + logger.info("sysconfig alert path prefix info {}",alertPathPrefix); + }else { + logger.error("Sysconfig missing alert_api or alert_path_prefix data"); + return; + } + logger.info("processPdu start"); + logger.info("alertRule info is {}",JSON.toJSON(alertRule)); + if(alertRule==null) { + logger.error(" alert rule info is null "); + return; + } + logger.info((new StringBuilder("receive snmp event:")).append(commandresponderevent.getPDU()).toString()); + UdpAddress udpaddress = (UdpAddress)commandresponderevent.getPeerAddress(); +// String s = udpaddress.getInetAddress().getHostAddress(); + String s = "127.0.0.1"; + PDU pdu = commandresponderevent.getPDU(); + logger.info((new StringBuilder("receive TRap:")).append(pdu).toString()); + TrapMessage trapmessageinfo = new TrapMessage(); + trapmessageinfo.setAgentSendIP(s); + setOIDList(trapmessageinfo, pdu); + setValueList(trapmessageinfo, pdu); + trapmessageinfo.setOriginalPDU(pdu); + if (pdu instanceof PDUv1) + { + PDUv1 pduv1 = (PDUv1)pdu; + trapmessageinfo.setTrapVersion(1); + String s1 = pduv1.getEnterprise().toString(); + trapmessageinfo.setTrapOID(s1); + String s2 = pduv1.getAgentAddress().toString(); + trapmessageinfo.setPduAgentIP(s); + trapmessageinfo.setTrapV1SpecificType(pduv1.getSpecificTrap()); + trapmessageinfo.setTrapV1GenericType(pduv1.getGenericTrap()); + trapmessageinfo.setTrapName(trapmessageinfo.getTrapOID()); + switch (pduv1.getGenericTrap()) + { + case 0: // '\0' +// trapmessageinfo.setTrapName("设备冷启动"); + trapmessageinfo.setTrapName("Device Cold Start"); + break; + + case 1: // '\001' +// trapmessageinfo.setTrapName("设备热启动"); + trapmessageinfo.setTrapName("Device Hot Start"); + break; + + case 2: // '\002' +// trapmessageinfo.setTrapName("接口关闭"); + trapmessageinfo.setTrapName("The Interface Is Closed"); + break; + + case 3: // '\003' +// trapmessageinfo.setTrapName("接口启用"); + trapmessageinfo.setTrapName("Interface Enabled"); + break; + + case 4: // '\004' +// trapmessageinfo.setTrapName("SNMP认证失败"); + trapmessageinfo.setTrapName("SNMP Authentication Failed"); + break; + + case 5: // '\005' +// trapmessageinfo.setTrapName("EGP邻居丢失"); + trapmessageinfo.setTrapName("EGP Neighbor Lost"); + break; + } + } else + {/* + trapmessageinfo.setTrapVersion(2); + Variable variable = trapmessageinfo.getOIDValue(SnmpConstants.snmpTrapAddress.toString()); + logger.info("pdu.snmpTrapAddress() =-=-= "+variable); + if (variable != null) + trapmessageinfo.setPduAgentIP(variable.toString()); + Variable variable1 = trapmessageinfo.getOIDValue(SnmpConstants.snmpTrapOID.toString()); + if (variable1 != null) + trapmessageinfo.setTrapOID(variable1.toString()); + trapmessageinfo.setTrapName(trapmessageinfo.getTrapOID()); + if (variable1 != null) + if (variable1.equals(SnmpConstants.coldStart)) +// trapmessageinfo.setTrapName("设备冷启动"); + trapmessageinfo.setTrapName("Device Cold Start"); + else + if (variable1.equals(SnmpConstants.warmStart)) +// trapmessageinfo.setTrapName("设备热启动"); + trapmessageinfo.setTrapName("Device Hot Start"); + else + if (variable1.equals(SnmpConstants.linkDown)) +// trapmessageinfo.setTrapName("接口关闭"); + trapmessageinfo.setTrapName("The Interface Is Closed"); + else + if (variable1.equals(SnmpConstants.linkUp)) +// trapmessageinfo.setTrapName("接口启用"); + trapmessageinfo.setTrapName("Interface Enabled"); + else + if (variable1.equals(SnmpConstants.authenticationFailure)) +// trapmessageinfo.setTrapName("SNMP认证失败"); + trapmessageinfo.setTrapName("SNMP Authentication Failed"); + *//*else //系统默认的类别不能匹配时,再使用自定义的trap信息库。是否需要分别自定义snmpV1和snmpValue2的trap信息库(定义到文件或者定义到数据库,必须体统重新加载的界面接口) + if(getTrapName(variable1)!=null &&!variable1.equals("")){ + trapmessageinfo.setTrapName(getTrapName(variable1)); + }else{ +// throw new Exception("未被定义的SNMPTRAP类型!"); + throw new Exception("Undefined SNMPTRAP type!"); + }*//* + */} + StringBuffer trapInfo = new StringBuffer(); + trapInfo.append("trapmessageinfo.getTrapName():"+trapmessageinfo.getTrapName()); + trapInfo.append("; trapmessageinfo.getAgentSendIP():"+trapmessageinfo.getAgentSendIP()); + trapInfo.append("; trapmessageinfo.getOriginalPDU():"+trapmessageinfo.getOriginalPDU()); + trapInfo.append("; trapmessageinfo.getTrapVersion():"+trapmessageinfo.getTrapVersion()); + trapInfo.append("; trapmessageinfo.getTrapOID():"+trapmessageinfo.getTrapOID()); + trapInfo.append("; trapmessageinfo.getPduAgentIP():"+trapmessageinfo.getPduAgentIP()); + trapInfo.append("; trapmessageinfo.getTrapV1GenericType():"+trapmessageinfo.getTrapV1GenericType()); + trapInfo.append("; trapmessageinfo.getTrapV1SpecificType():"+trapmessageinfo.getTrapV1SpecificType()); + logger.info("agent IP:"+s+" trap message:"+trapInfo.toString()); + + // 组装prometheus_alert格式 + Integer alertName = alertRule.getId(); + String severity = alertRule.getSeverity(); + String asset = trapmessageinfo.getAgentSendIP(); + String oid = trapmessageinfo.getTrapOID(); + String value=trapmessageinfo.getOriginalPDU().getVariableBindings().toString(); + + StringBuilder description = new StringBuilder(); + description.append("version:"+trapmessageinfo.getTrapVersion()); + description.append(",agentip:"+trapmessageinfo.getAgentSendIP()); + description.append(",oid:"+trapmessageinfo.getTrapOID()); + description.append(",value:"+value); + String trapName = trapmessageinfo.getTrapName(); + if(trapName!=null&&trapName.length()>0) { + description.append(",trapName:"+trapName); + } + StringBuilder summary=new StringBuilder("snmptrap:"); + summary.append(trapmessageinfo.getAgentSendIP()+"("); + summary.append(trapmessageinfo.getTrapOID()+":"+value+")"); + boolean snmptrap=true; + SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + String startsAt = sdf.format(new Date()); + + JSONObject labels =new JSONObject(); + labels.put("alertname", alertName.toString()); + labels.put("severity",severity); + labels.put("asset", asset); + labels.put("oid", oid); + + JSONObject annotations =new JSONObject(); + annotations.put("description", description.toString()); + annotations.put("summary", summary.toString()); + + JSONObject result =new JSONObject(); + result.put("labels", labels); + result.put("annotations", annotations); + result.put("snmptrap", snmptrap); + result.put("startsAt", startsAt); + + JSONArray mess =new JSONArray(); + mess.add(result); + + logger.info("send alert info is {}",JSON.toJSON(mess)); + + // 将告警信息发送到web端处理 + RestTemplate restTemplate=new RestTemplate(); + restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); + MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8"); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity entity =new HttpEntity(mess,headers); + String url=String.format("%s://%s%s%s","http",alertApi,alertPathPrefix,"/api/v1/alerts"); + Object postForEntity = restTemplate.postForEntity(url, entity,Object.class); +// logger.info("post success info {}",JSON.toJSON(postForEntity)); + confagentMetrics.snmpCounter.increment(); + } + catch (Exception exception) + { + logger.error("Error parsing UDP trap: {}", LogPrintUtil.print(exception)); + }finally{ + + } + } + + public String getTrapName(Variable variable1){ + String trapName = ""; + Map allTrapTypeDefine = new HashMap(); + trapName = allTrapTypeDefine.get(variable1.toString()).toString(); + return trapName; + } + + void setOIDList(TrapMessage trapmessageinfo, PDU pdu) + { + Vector vector = pdu.getVariableBindings(); + String s; + + for (Iterator iterator = vector.iterator(); iterator.hasNext(); trapmessageinfo.getTrapPDUOIDs().add(s)) + { + VariableBinding variablebinding = (VariableBinding)iterator.next(); + s = variablebinding.getOid().toString(); + } + + } + + void setValueList(TrapMessage trapmessageinfo, PDU pdu) + { + Vector vector = pdu.getVariableBindings(); + Variable variable; + for (Iterator iterator = vector.iterator(); iterator.hasNext(); trapmessageinfo.getTrapPDUOIDValues().add(variable)) + { + VariableBinding variablebinding = (VariableBinding)iterator.next(); + variable = variablebinding.getVariable(); + } + + } + + + /** */ + /** + * 解决snmp4j中文乱码问题 + */ + public static String getChinese(String octetString) { + try { + String[] temps = octetString.split(":"); + byte[] bs = new byte[temps.length]; + for (int i = 0; i < temps.length; i++) + bs[i] = (byte) Integer.parseInt(temps[i], 16); + + return new String(bs, "GB2312"); + } catch (Exception e) { + return null; + } + } + + /*protected static String printVariableBindings(PDU response) { + String strCom = ""; + for (int i = 0; i < response.size(); i++) { + VariableBinding vb = response.get(i); + String[] str = vb.getVariable().toString().toUpperCase().split(":"); + + String strOut = ""; + int intLength = str.length; + System.out.println("长度==> " + intLength); + for (int j = 0; j < intLength; j++) { + strOut += str[j]; + } + strCom += vb.getVariable(); + if (str.length != 1) { + System.out.println("==第行=vb.getVariable()=" + SNMPTrapServer.toStringHex(strOut));//显示中文 + } + } + return strCom; + + }*/ + + /** + * 将十进六制转换成为中文 + */ + private static String hexString = "0123456789ABCDEF"; + + public static String toStringHex(String bytes) { + + ByteArrayOutputStream baos = new ByteArrayOutputStream( + bytes.length() / 2); + //将每2位16进制整数组装成一个字节 + for (int i = 0; i < bytes.length(); i += 2) { + baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString + .indexOf(bytes.charAt(i + 1)))); + } + return new String(baos.toByteArray()); + } +} diff --git a/src/main/java/com/nis/service/impl/TrafficServiceImpl.java b/src/main/java/com/nis/service/impl/TrafficServiceImpl.java index 2e32974..2b743f5 100644 --- a/src/main/java/com/nis/service/impl/TrafficServiceImpl.java +++ b/src/main/java/com/nis/service/impl/TrafficServiceImpl.java @@ -5,6 +5,7 @@ import com.nis.dao.TrafficDao; import com.nis.entity.Traffic; import com.nis.service.TrafficService; import com.nis.util.Constant; +import com.nis.util.LogPrintUtil; import com.nis.util.SnmpUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; @@ -67,7 +68,7 @@ public class TrafficServiceImpl implements TrafficService { } resultData = SnmpUtil.snmpWalk(entry.getKey(), t.getPort(), t.getVersion(), t.getCommunity(), Constant.IFTABLE_OID, auth); } catch (IOException e) { - logger.error("通过SNMP采集IfTable失败,ip ->" + entry.getKey(), e); + logger.error("通过SNMP采集IfTable失败,ip ->{},{}", entry.getKey(), LogPrintUtil.print(e)); } if (CollectionUtils.isEmpty(resultData)) { diff --git a/src/main/java/com/nis/util/BufferReaderWrapper.java b/src/main/java/com/nis/util/BufferReaderWrapper.java new file mode 100644 index 0000000..771e154 --- /dev/null +++ b/src/main/java/com/nis/util/BufferReaderWrapper.java @@ -0,0 +1,15 @@ +package com.nis.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; + +public class BufferReaderWrapper extends BufferedReader +{ + public BufferReaderWrapper(Reader in) { + super(in); + } + public String load() throws IOException { + return super.readLine(); + } +} diff --git a/src/main/java/com/nis/util/Constant.java b/src/main/java/com/nis/util/Constant.java index b194861..6db9f59 100644 --- a/src/main/java/com/nis/util/Constant.java +++ b/src/main/java/com/nis/util/Constant.java @@ -78,7 +78,7 @@ public class Constant { try { databaseId = databaseIdProvider.getDatabaseId(dataSource); } catch (SQLException e) { - e.printStackTrace(); + System.out.println(LogPrintUtil.print(e)); } DB_TYPE = databaseId; } diff --git a/src/main/java/com/nis/util/LogPrintUtil.java b/src/main/java/com/nis/util/LogPrintUtil.java new file mode 100644 index 0000000..1289766 --- /dev/null +++ b/src/main/java/com/nis/util/LogPrintUtil.java @@ -0,0 +1,14 @@ +package com.nis.util; + + +import java.io.PrintWriter; +import java.io.StringWriter; + + +public class LogPrintUtil { + public static String print(Throwable t){ + StringWriter sw = new StringWriter(); + t.printStackTrace(new PrintWriter(sw)); + return sw.toString(); + } +} diff --git a/src/main/java/com/nis/util/MybatisPlusConfig.java b/src/main/java/com/nis/util/MybatisPlusConfig.java index 56d2237..0a0ce3f 100644 --- a/src/main/java/com/nis/util/MybatisPlusConfig.java +++ b/src/main/java/com/nis/util/MybatisPlusConfig.java @@ -58,7 +58,7 @@ public class MybatisPlusConfig { try { databaseId = databaseIdProvider.getDatabaseId(dataSource); } catch (SQLException e) { - e.printStackTrace(); + System.out.println(LogPrintUtil.print(e)); } switch (databaseId){ diff --git a/src/main/java/com/nis/util/RuntimeUtil.java b/src/main/java/com/nis/util/RuntimeUtil.java index 590d019..26e164f 100644 --- a/src/main/java/com/nis/util/RuntimeUtil.java +++ b/src/main/java/com/nis/util/RuntimeUtil.java @@ -1,358 +1,317 @@ -package com.nis.util;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.StringReader;
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-/**
- * Runtime工具类,用于本机执行某些命令
- *
- * @author fox
- * @version 0.1.0
- */
-public class RuntimeUtil {
- // Log
- private static Log log = LogFactory.getLog(RuntimeUtil.class);
- // 当前Runtime
- private static Runtime runtime = Runtime.getRuntime();
-
- // 工具类不可实例化
- private RuntimeUtil() {
- }
-
- /**
- * 以非阻塞模式执行命令
- *
- * @param callback
- * 回调类,当命令全部执行完成后会执行其onExit方法,null表示不进行回调
- * @param envp
- * 运行的上下文环境变量,每项都应该写成name=value的格式;null表示直接继承当前Java进程的全部环境变量
- * @param dir
- * 命令执行的工作目录;null表示继承当前Java进程的工作目录
- * @param startCommand
- * 起始命令
- * @param commands
- * 其他后续命令,如果有设置,会使用管道来关联前后命令的标准输出流和标准输入流
- */
- public static void runAsUnblocking(final RuntimeCallback callback, final String[] envp, final File dir,
- final String[] startCommand, final String[]... commands) {
- // 非阻塞的实现就是交给其他函数执行
- new Thread(new Runnable() {
- @Override
- public void run() {
- StringReader result = RuntimeUtil.run(envp, dir, startCommand, commands);
-
- // 如果需要回调的话,调用回调函数
- if (callback != null) {
- callback.onExit(result, envp, dir, startCommand, commands);
- }
- }
- }).start();
- }
-
- /**
- * 以阻塞模式执行命令
- *
- * @param envp
- * 运行的上下文环境变量,每项都应该写成name=value的格式;null表示直接继承当前Java进程的全部环境变量
- * @param dir
- * 命令执行的工作目录;null表示继承当前Java进程的工作目录
- * @param startCommand
- * 起始命令
- * @param commands
- * 其他后续命令,如果有设置,会使用管道来关联前后命令的标准输出流和标准输入流
- * @return 命令执行后的最终结果
- */
- public static StringReader run(String[] envp, File dir, String[] startCommand, String[]... commands) {
- // 生成一个命令id,只是为日志区别用
- String commandId = UUID.randomUUID().toString();
- log.info("Command(" + commandId + ") start");
-
- StringBuilder result = new StringBuilder();
- Process currentProcess = null;
- Process nextProcess = null;
-
- try {
- // 见执行起始命令
- currentProcess = run(commandId, startCommand, envp, dir);
- // 用于管道的字节输出流
- BufferedOutputStream out = null;
- // 用于标准错误输出和最终结果的字符输入流
- BufferedReader reader = null;
- // 用于管道的字节输入流
- BufferedInputStream in = null;
- // 用于管道的IO缓冲
- byte[] buffer = new byte[1024];
- try {
- // 遍历后续命令
- for (String[] command : commands) {
- try {
- // 获取当前命令的标准错误流
- reader = new BufferedReader(new InputStreamReader(currentProcess.getErrorStream()));
-
- // 输出错误
- for (String temp = readLine(reader); temp != null; temp = readLine(reader)) {
- log.warn("Command(" + commandId + ") Error: " + temp);
- }
- // 获取当前命令的标准输出流
- in = new BufferedInputStream(currentProcess.getInputStream());
- // 启动下一条命令
- nextProcess = run(commandId, command, envp, dir);
- // 获取下一条命令的标准输入流
- out = new BufferedOutputStream(nextProcess.getOutputStream());
-
- // 管道的实现
- for (int c = read(in, buffer); c >= 0; c = read(in, buffer)) {
- write(out, buffer, c);
- }
-
- // 当前命令全部输出都已经输入到下一条命令中后,将下一条命令作为当前命令
- currentProcess = nextProcess;
- } finally { // 流关闭操作
- if (out != null) {
- out.flush();
- out.close();
- out = null;
- }
-
- if (in != null) {
- in.close();
- in = null;
- }
-
- if (reader != null) {
- reader.close();
- reader = null;
- }
- }
- }
-
- // 获取最终命令的标准错误流,
- reader = new BufferedReader(new InputStreamReader(currentProcess.getErrorStream()));
- // 输出错误
- for (String temp = readLine(reader); temp != null; temp = readLine(reader)) {
- log.warn("Command(" + commandId + ") Error: " + temp);
- }
- // 关闭
- reader.close();
- reader = null;
-
- // 获取最终命令的标准输出流
- reader = new BufferedReader(new InputStreamReader(currentProcess.getInputStream()));
- // 将输出添加到结果缓冲中
- for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
- result.append(temp + "\n");
- }
- } finally { // 流关闭操作
- if (out != null) {
- out.flush();
- out.close();
- out = null;
- }
-
- if (in != null) {
- in.close();
- in = null;
- }
-
- if (reader != null) {
- reader.close();
- reader = null;
- }
- }
- } catch (Exception e) { // 出现异常,尝试把启动的进程都销毁
- log.warn("Command(" + commandId + ") Error", e);
-
- if (currentProcess != null) {
- currentProcess.destroy();
- currentProcess = null;
- }
-
- if (nextProcess != null) {
- nextProcess.destroy();
- nextProcess = null;
- }
- }
-
- log.info("Command(" + commandId + ") end");
- // 用结果缓冲构建StringReader
- return new StringReader(result.toString());
- }
-
- /**
- * 读取StringReader为String
- *
- * @param stringReader
- * StringReader
- * @param skipWhiteLine
- * 是否需要跳过空行
- * @return
- */
- public static String readStringReader(StringReader stringReader, boolean skipWhiteLine) {
- StringBuilder result = new StringBuilder();
- BufferedReader reader = new BufferedReader(stringReader);
-
- for (String temp = readLine(reader); temp != null; temp = readLine(reader)) {
- if (skipWhiteLine == false || !temp.trim().equals("")) {
- result.append(temp + "\n");
- }
- }
-
- return result.toString();
-
- }
-
- /**
- * 运行一个命令
- *
- * @param commandId
- * 命令id, 日志区别用
- * @param command
- * 执行的命令
- * @param envp
- * 运行的上下文环境变量,每项都应该写成name=value的格式;null表示直接继承当前Java进程的全部环境变量
- * @param dir
- * 命令执行的工作目录;null表示继承当前Java进程的工作目录
- * @return 命令对应的Process对象Process
- * @throws Exception
- */
- private static Process run(String commandId, String[] command, String[] envp, File dir) throws Exception {
- log.info("Command(" + commandId + ") exec: " + Arrays.toString(command));
-
- return runtime.exec(command, envp, dir);
- }
-
- /**
- * 从输入流中读取数据进入buffer中,忽略异常
- *
- * @param in
- * 输入流
- * @param buffer
- * 缓冲
- * @return 基本等同于in.read(buffer)的返回值,不过在出现异常时,不会抛出异常而是返回-1
- */
- private static int read(InputStream in, byte[] buffer) {
- int result = -1;
-
- try {
- result = in.read(buffer);
- } catch (IOException e) {
- result = -1;
- }
-
- return result;
- }
-
- /**
- * 从输入流中读取一行字符串,忽略异常
- *
- * @param reader
- * 输入流
- * @return 基本等同于reader.readLine()的返回值,不过在出现异常时,不会抛出异常而是返回null
- */
- private static String readLine(BufferedReader reader) {
- String result = null;
-
- try {
- result = reader.readLine();
- } catch (IOException e) {
- result = null;
- }
-
- return result;
- }
-
- /**
- * 向输出流写入buffer从0~length位置的数据,忽略异常
- *
- * @param out
- * 输出流
- * @param buffer
- * 缓冲
- * @param length
- * 最大位序号
- */
- private static void write(OutputStream out, byte[] buffer, int length) {
- try {
- out.write(buffer, 0, length);
- } catch (IOException e) {
- }
- }
-
- /**
- * 非阻塞模式回调
- *
- * @author fox
- */
- public static interface RuntimeCallback {
- /**
- * 非阻塞模式回调函数
- *
- * @param result
- * 命令执行结果
- * @param startCommand
- * 起始命令
- * @param commands
- * 其他后续命令,如果有设置,会使用管道来关联前后命令的标准输出流和标准输入流
- */
- public void onExit(StringReader result, String[] envp, File dir, String[] startCommand, String[]... commands);
- }
-
- public static void main(String[] args) {
-
- System.out.println(readStringReader(run(null, null, new String[] { "c:/promtool", "check", "rules", "d:/test.yml" }), false));
- // 例子 ps -ef (注意用String[]方式来表示命令是不需要做转移的)
- /*System.out.println(readStringReader(run(null, null, new String[] { "ps", "-ef" }), true));
- System.out.println("-----------------------------------------------------------------");
- // 例子 ps -ef | grep -i java
- System.out.println(readStringReader(
- run(null, null, new String[] { "ps", "-ef" }, new String[] { "grep", "-i", "java" }), true));*/
- }
-
-
- public static List<String> run(String command) throws IOException {
- List<String> result = new ArrayList<>();
- Scanner input = null;
- //String result = "";
- Process process = null;
- log.info("执行扫描命令===>"+command);
- try {
- process = Runtime.getRuntime().exec(command);
- try {
- //等待命令执行完成
- process.waitFor(10, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- InputStream is = process.getInputStream();
- input = new Scanner(is);
- while (input.hasNextLine()) {
- String[] tmp= input.nextLine().split("::");
- if("IF-MIB".equalsIgnoreCase(tmp[0])
- &&(tmp[1].contains("ifOut")||tmp[1].contains("ifIn"))&&
- !tmp[1].contains("ifIndex")){
- result.add(tmp[1]);
- }
- }
- } finally {
- if (input != null) {
- input.close();
- }
- if (process != null) {
- process.destroy();
- }
- }
- return result;
- }
-}
+package com.nis.util; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.StringReader; +import java.util.*; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Runtime工具类,用于本机执行某些命令 + * + * @author fox + * @version 0.1.0 + */ +public class RuntimeUtil { + // Log + private static Log log = LogFactory.getLog(RuntimeUtil.class); + // 当前Runtime + private static Runtime runtime = Runtime.getRuntime(); + + // 工具类不可实例化 + private RuntimeUtil() { + } + + /** + * 以非阻塞模式执行命令 + * + * @param callback + * 回调类,当命令全部执行完成后会执行其onExit方法,null表示不进行回调 + * @param envp + * 运行的上下文环境变量,每项都应该写成name=value的格式;null表示直接继承当前Java进程的全部环境变量 + * @param dir + * 命令执行的工作目录;null表示继承当前Java进程的工作目录 + * @param startCommand + * 起始命令 + * @param commands + * 其他后续命令,如果有设置,会使用管道来关联前后命令的标准输出流和标准输入流 + */ + public static void runAsUnblocking(final RuntimeCallback callback, final String[] envp, final File dir, + final String[] startCommand, final String[]... commands) { + // 非阻塞的实现就是交给其他函数执行 + new Thread(new Runnable() { + @Override + public void run() { + StringReader result = RuntimeUtil.run(envp, dir, startCommand, commands); + + // 如果需要回调的话,调用回调函数 + if (callback != null) { + callback.onExit(result, envp, dir, startCommand, commands); + } + } + }).start(); + } + + /** + * 以阻塞模式执行命令 + * + * @param envp + * 运行的上下文环境变量,每项都应该写成name=value的格式;null表示直接继承当前Java进程的全部环境变量 + * @param dir + * 命令执行的工作目录;null表示继承当前Java进程的工作目录 + * @param startCommand + * 起始命令 + * @param commands + * 其他后续命令,如果有设置,会使用管道来关联前后命令的标准输出流和标准输入流 + * @return 命令执行后的最终结果 + */ + public static StringReader run(String[] envp, File dir, String[] startCommand, String[]... commands) { + // 生成一个命令id,只是为日志区别用 + String commandId = UUID.randomUUID().toString(); +// log.info("Command(" + commandId + ") start"); + + StringBuilder result = new StringBuilder(); + Process currentProcess = null; + Process nextProcess = null; + + try { + // 见执行起始命令 + currentProcess = run(commandId, startCommand, envp, dir); + // 用于管道的字节输出流 + BufferedOutputStream out = null; + // 用于标准错误输出和最终结果的字符输入流 + BufferReaderWrapper reader = null; + // 用于管道的字节输入流 + BufferedInputStream in = null; + // 用于管道的IO缓冲 + byte[] buffer = new byte[1024]; + try { + // 遍历后续命令 + for (String[] command : commands) { + try { + // 获取当前命令的标准错误流 + reader = new BufferReaderWrapper(new InputStreamReader(currentProcess.getErrorStream())); + + // 输出错误 + for (String temp = readLine(reader); temp != null; temp = readLine(reader)) { +// log.warn("Command(" + commandId + ") Error: " + temp); + } + // 获取当前命令的标准输出流 + in = new BufferedInputStream(currentProcess.getInputStream()); + // 启动下一条命令 + nextProcess = run(commandId, command, envp, dir); + // 获取下一条命令的标准输入流 + out = new BufferedOutputStream(nextProcess.getOutputStream()); + + // 管道的实现 + for (int c = read(in, buffer); c >= 0; c = read(in, buffer)) { + write(out, buffer, c); + } + + // 当前命令全部输出都已经输入到下一条命令中后,将下一条命令作为当前命令 + currentProcess = nextProcess; + } finally { // 流关闭操作 + /*if (out != null) { + out.flush(); + out.close(); + out = null; + } + + if (in != null) { + in.close(); + in = null; + } + + if (reader != null) { + reader.close(); + reader = null; + }*/ + IOUtils.closeQuietly(out,in,reader); + } + } + + // 获取最终命令的标准错误流, + reader = new BufferReaderWrapper(new InputStreamReader(currentProcess.getErrorStream())); + // 输出错误 + for (String temp = readLine(reader); temp != null; temp = readLine(reader)) { +// log.warn("Command(" + commandId + ") Error: " + temp); + } + // 关闭 + reader.close(); + reader = null; + + // 获取最终命令的标准输出流 + reader = new BufferReaderWrapper(new InputStreamReader(currentProcess.getInputStream())); + // 将输出添加到结果缓冲中 + for (String temp = reader.load(); temp != null; temp = reader.load()) { + result.append(temp + "\n"); + } + } finally { // 流关闭操作 + /*if (out != null) {BufferReaderWrapper + out.flush(); + out.close(); + out = null; + } + + if (in != null) { + in.close(); + in = null; + } + + if (reader != null) { + reader.close(); + reader = null; + }*/ + IOUtils.closeQuietly(out,in,reader); + } + } catch (Exception e) { // 出现异常,尝试把启动的进程都销毁 +// log.warn("Command(" + commandId + ") Error", e); + + if (currentProcess != null) { + currentProcess.destroy(); + currentProcess = null; + } + + if (nextProcess != null) { + nextProcess.destroy(); + nextProcess = null; + } + } + + log.info("Command(" + commandId + ") end"); + // 用结果缓冲构建StringReader + return new StringReader(result.toString()); + } + + /** + * 读取StringReader为String + * + * @param stringReader + * StringReader + * @param skipWhiteLine + * 是否需要跳过空行 + * @return + */ + public static String readStringReader(StringReader stringReader, boolean skipWhiteLine) { + StringBuilder result = new StringBuilder(); + BufferReaderWrapper reader = new BufferReaderWrapper(stringReader); + + for (String temp = readLine(reader); temp != null; temp = readLine(reader)) { + if (skipWhiteLine == false || !temp.trim().equals("")) { + result.append(temp + "\n"); + } + } + + return result.toString(); + + } + + /** + * 运行一个命令 + * + * @param commandId + * 命令id, 日志区别用 + * @param command + * 执行的命令 + * @param envp + * 运行的上下文环境变量,每项都应该写成name=value的格式;null表示直接继承当前Java进程的全部环境变量 + * @param dir + * 命令执行的工作目录;null表示继承当前Java进程的工作目录 + * @return 命令对应的Process对象Process + * @throws Exception + */ + private static Process run(String commandId, String[] command, String[] envp, File dir) throws Exception { +// log.info("Command(" + commandId + ") exec: " + Arrays.toString(command)); + + return runtime.exec(command, envp, dir); + } + + /** + * 从输入流中读取数据进入buffer中,忽略异常 + * + * @param in + * 输入流 + * @param buffer + * 缓冲 + * @return 基本等同于in.read(buffer)的返回值,不过在出现异常时,不会抛出异常而是返回-1 + */ + private static int read(InputStream in, byte[] buffer) { + int result = -1; + + try { + result = in.read(buffer); + } catch (IOException e) { + result = -1; + } + + return result; + } + + /** + * 从输入流中读取一行字符串,忽略异常 + * + * @param reader + * 输入流 + * @return 基本等同于reader.readLine()的返回值,不过在出现异常时,不会抛出异常而是返回null + */ + private static String readLine(BufferReaderWrapper reader) { + String result = null; + + try { + result = reader.load(); + } catch (IOException e) { + result = null; + } + + return result; + } + + /** + * 向输出流写入buffer从0~length位置的数据,忽略异常 + * + * @param out + * 输出流 + * @param buffer + * 缓冲 + * @param length + * 最大位序号 + */ + private static void write(OutputStream out, byte[] buffer, int length) { + try { + out.write(buffer, 0, length); + } catch (IOException e) {LogPrintUtil.print(e); + } + } + + /** + * 非阻塞模式回调 + * + * @author fox + */ + public static interface RuntimeCallback { + /** + * 非阻塞模式回调函数 + * + * @param result + * 命令执行结果 + * @param startCommand + * 起始命令 + * @param commands + * 其他后续命令,如果有设置,会使用管道来关联前后命令的标准输出流和标准输入流 + */ + public void onExit(StringReader result, String[] envp, File dir, String[] startCommand, String[]... commands); + } + + + +} diff --git a/src/main/java/com/nis/util/SnmpUtil.java b/src/main/java/com/nis/util/SnmpUtil.java index 6f018e7..ee7bf39 100644 --- a/src/main/java/com/nis/util/SnmpUtil.java +++ b/src/main/java/com/nis/util/SnmpUtil.java @@ -202,21 +202,21 @@ public class SnmpUtil { } } } catch (IOException e) { - logger.error("snmp采集失败,错误信息是:" + e.getMessage() + " pdu是:" + pdu.toString() + " target是:" + target.toString(), e); + logger.error("snmp采集失败,pdu是:{},target是:{},错误信息是:{}" , pdu.toString() ,target.toString(), LogPrintUtil.print(e)); } } finally { if (snmp != null) { try { snmp.close(); } catch (Exception e) { - logger.error("关闭snmp失败", e); + logger.error("关闭snmp失败{}", LogPrintUtil.print(e)); } } if (transport != null) { try { transport.close(); } catch (Exception e) { - logger.error("关闭transport失败", e); + logger.error("关闭transport失败{}",LogPrintUtil.print(e)); } } } diff --git a/src/main/java/com/nis/util/YamlUtil.java b/src/main/java/com/nis/util/YamlUtil.java index e598d1b..72a2cd3 100644 --- a/src/main/java/com/nis/util/YamlUtil.java +++ b/src/main/java/com/nis/util/YamlUtil.java @@ -1,457 +1,457 @@ -package com.nis.util;
-
-
-import com.alibaba.fastjson.JSON;
-import org.yaml.snakeyaml.DumperOptions;
-import org.yaml.snakeyaml.Yaml;
-
-import java.io.*;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-public class YamlUtil {
-
- private static Yaml y;
-
- static {
- DumperOptions options = new DumperOptions();
- options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
- y = new Yaml(options);
- }
-
- /**
- * snmp配置相关
- * @param param
- * @param ymlPath
- * @return
- */
- @SuppressWarnings("unchecked")
- public static boolean snmpYmlHandle(Set<String> param,String ymlPath) {
- boolean flag=false;
- if(param!=null && !param.isEmpty() && ymlPath != null && ymlPath.length() != 0) {
- OutputStream out = null;
- OutputStreamWriter osw = null;
- try {
- File file = new File(ymlPath);
- out=new FileOutputStream(file);
- osw=new OutputStreamWriter(out, "UTF-8");
- for(String s : param) {
-// Object load = y.load(s);
- Object load = JSON.parse(s);
-// y.dump(y.load(s),osw);
- y.dump(load,osw);
- }
-// RuntimeUtil.run(null, null, new String[]{"kill","-hup","`ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'`"});
-// RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","ps -ef |grep snmp_exporter|grep -v grep|awk \'{print $2}\'|xargs kill -hup"});
- flag = true;
- out.close();
- osw.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if(out!=null) {
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(osw!=null) {
- try {
- osw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- return flag;
- }
-
- /**
- * datacenter相关配置
- * @param param
- * @param ymlPath
- * @return
- */
- @SuppressWarnings("unchecked")
- public static boolean subYmlHandle(List<Object> param,String ymlPath,String ruleYmlPath) {
- boolean flag=false;
- if(param!=null && ymlPath != null && ymlPath.length() != 0) {
- FileInputStream fileInputStream =null;
- OutputStream out = null;
- OutputStreamWriter osw = null;
- try {
- File file = new File(ymlPath);
- fileInputStream = new FileInputStream(file);
- Map<String,Object> map = y.loadAs(fileInputStream, Map.class);
- if(map==null) {
- map=new HashMap();
- }
- //修改 rule.yml配置文件
- File ruleYmlfile = new File(ruleYmlPath);
- if(ruleYmlfile.exists()){
- // 文件存在则删除文件信息
- ruleYmlfile.delete();
- }
- map.remove("rule_files");
- map.put("scrape_configs", param);
- out=new FileOutputStream(file);
- osw=new OutputStreamWriter(out, "UTF-8");
- y.dump(map,osw);
-
-// RuntimeUtil.run(null, null, new String[]{"kill","-hup","`ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'`"});
-// RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'|xargs kill -hup"});
- flag = true;
- fileInputStream.close();
- out.close();
- osw.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if(fileInputStream!=null) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(out!=null) {
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(osw!=null) {
- try {
- osw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- return flag;
- }
-
- /**
- * global相关配置设置
- * @param param
- * @param ymlPath
- * @param ruleYmlPath
- * @return
- */
- @SuppressWarnings("unchecked")
- public static boolean centerYmlHandle(Map<String,Object> param,String ymlPath,String ruleYmlPath){
- boolean flag=false;
- if(param!=null && !param.isEmpty() && ymlPath != null && ymlPath.length() != 0) {
- FileInputStream fileInputStream =null;
- OutputStream out = null;
- OutputStreamWriter osw = null;
- try {
- // 修改prometheus.yml配置文件
- File ymlfile = new File(ymlPath);
- fileInputStream = new FileInputStream(ymlfile);
- Map<String,Object> map = y.loadAs(fileInputStream, Map.class);
- if(map==null) {
- map=new HashMap();
- }
- map.put("scrape_configs", param.get("scrape_configs"));
- map.put("alerting", param.get("alerting"));
- map.put("rule_files", param.get("rule_files"));
- out = new FileOutputStream(ymlfile);
- osw = new OutputStreamWriter(out, "UTF-8");
- y.dump(map,osw);
-
- //修改 rule.yml配置文件
- File ruleYmlfile = new File(ruleYmlPath);
- if(!ruleYmlfile.exists()){
- // 文件不存在 创建文件
- ruleYmlfile.createNewFile();
- }
- FileInputStream fileInputStream2 = new FileInputStream(ruleYmlfile);
- Map<String,Object> map2 = y.loadAs(fileInputStream2, Map.class);
- if(map2==null) {
- map2=new HashMap();
- }
- map2.put("groups", param.get("groups"));
- OutputStream out2 = new FileOutputStream(ruleYmlfile);
- OutputStreamWriter osw2 = new OutputStreamWriter(out2, "UTF-8");
- y.dump(map2,osw2);
-
-// RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'|xargs kill -hup"});
-// RuntimeUtil.run(null, null, new String[]{"kill","-hup","`ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'`"});
- flag = true;
- osw.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if(fileInputStream!=null) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(out!=null) {
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(osw!=null) {
- try {
- osw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- return flag;
- }
-
-
- /**
- * thanos rule 角色所需 rule.yml 配置文件处理
- *
- * @param param
- * @param ruleYmlPath
- * @return
- */
- public static boolean thanosRuleYmlHandle(Map<String, Object> param, String ruleYmlPath) {
- boolean flag = false;
- if (param != null && !param.isEmpty()) {
- FileInputStream fileInputStream = null;
- OutputStream out = null;
- try {
- // 修改 rule.yml配置文件
- File ruleYmlfile = new File(ruleYmlPath);
- if (!ruleYmlfile.exists()) {
- // 文件不存在 创建文件
- ruleYmlfile.createNewFile();
- }
- FileInputStream fileInputStream2 = new FileInputStream(ruleYmlfile);
- Map<String, Object> map2 = y.loadAs(fileInputStream2, Map.class);
- if (map2 == null) {
- map2 = new HashMap();
- }
- map2.put("groups", param.get("groups"));
- OutputStream out2 = new FileOutputStream(ruleYmlfile);
- OutputStreamWriter osw2 = new OutputStreamWriter(out2, "UTF-8");
- y.dump(map2, osw2);
- flag = true;
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if (fileInputStream != null) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (out != null) {
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- return flag;
- }
-
- /**
- * prometheus启动项修改
- * @param filePath
- * @param param
- * @return
- */
- public static boolean prometheusStartHandle(String filePath,String param) {
- boolean flag=false;
- RandomAccessFile raf = null;
- try {
- raf = new RandomAccessFile(new File(filePath), "rw");
- String readLine = null;
- long lastPoint = 0; //记住上一次的偏移量
- while((readLine=raf.readLine())!=null) {
- final long ponit = raf.getFilePointer();
- if(readLine.startsWith("ExecStart")) {
- String replace = readLine.replaceAll("--storage.tsdb.retention.time=\\d+d", "--storage.tsdb.retention.time="+param+"d");
- raf.seek(lastPoint);
- raf.writeBytes(replace);
- }
- lastPoint = ponit;
- }
- raf.close();
- RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl daemon-reload"});
- RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl stop prometheus"});
- RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl start prometheus"});
- flag=true;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if(raf!=null) {
- try {
- raf.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return flag;
- }
-
- /**
- * prometheus全局配置修改
- * @param param
- * @return
- */
- @SuppressWarnings("unchecked")
- public static boolean prometheusSettingHandle(Map<String, Object> param, String ymlPath) {
- boolean flag=false;
- if(param!=null && !param.isEmpty() &&ymlPath != null && ymlPath.length() != 0) { //
- FileInputStream fileInputStream =null;
- OutputStream out = null;
- OutputStreamWriter osw = null;
- try {
- // 修改prometheus.yml配置文件
- File ymlfile = new File(ymlPath);
- fileInputStream = new FileInputStream(ymlfile);
- Map<String,Object> map = y.loadAs(fileInputStream, Map.class);
- if(map==null) {
- return false;
- }
- Map object = (Map) map.get("global");
- object.put(Constant.SCRAPE_INTERVAL, param.get(Constant.SCRAPE_INTERVAL)+"s");
-
- out = new FileOutputStream(ymlfile);
- osw = new OutputStreamWriter(out, "UTF-8");
- y.dump(map,osw);
-
- // RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'|xargs kill -hup"});
- flag = true;
- osw.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if(fileInputStream!=null) {
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(out!=null) {
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if(osw!=null) {
- try {
- osw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- return flag;
- }
- /*public static void main(String[] args) throws Exception {
-// File file = new File("F:/workspace/nz-web/nz-admin/tmp/promRuleCheck1574925561786.yml");
- File file = new File("F:/prometheus.yml");
- FileInputStream fileInputStream = new FileInputStream(file);
- Map map = y.loadAs(fileInputStream, Map.class);
-
- *//**
- List l = new ArrayList();
- Map m1 = new LinkedHashMap();
- m1.put("job_name", "federate");
-
-
- m1.put("scrape_interval", "15s");
- m1.put("honor_labels", true);
- m1.put("metrics_path", "/federate");
-
-
- List l2 =new ArrayList();
- List l3 =new ArrayList();
- l3.add("192.168.1.1:9090");
- l3.add("192.168.2.2:9090");
- Map m2 =new HashMap();
- m2.put("targets", l3);
- l2.add(m2);
- m1.put("static_configs", l2);
-
- Map m3 = new HashMap();
- List l4=new ArrayList();
- l4.add("{job=\"prometheus\"}");
- l4.add("{__name__=~\"job:.*\"}");
- m3.put("match[]", l4);
- m1.put("params", m3);
-
-
- l.add(m1);
- map.put("scrape_configs", l);
- **//*
-
- Map toCheck = new HashMap();
-
- List groups = new ArrayList();
-
- Map group = new HashMap();
- groups.add(group);
-
- List rules = new ArrayList();
- group.put("name", "example");
- group.put("rules", rules);
-
- for(int i=0;i<3;i++) {
- Map labels = new HashMap();
- labels.put("severity", "warning");
- Map annotations = new HashMap();
- annotations.put("summary", "hhh");
- annotations.put("description", "1111");
- Map rule = new HashMap();
- rule.put("alert", "tttt");
- rule.put("expr", "up == 0");
- rule.put("for", "70s");
- rule.put("labels", labels);
- rule.put("annotations", annotations);
- rules.add(rule);
- }
- map.put("groups", groups);
-
- Map alertManager =new HashMap();
- List staticConfigList=new ArrayList();
- Map staticConfigs =new HashMap();
- staticConfigList.add(staticConfigs);
- List staticConfig =new ArrayList();
- Map targets =new HashMap();
- List target =new ArrayList();
- List alertData =new ArrayList();
- alertData.add("192.168.41.134:8008");
- alertManager.put("alertmanagers",staticConfigList);
- staticConfigs.put("static_configs", staticConfig);
- staticConfig.add(targets);
- targets.put("targets", alertData);
- map.put("alerting", alertManager);
- OutputStream out = new FileOutputStream(file);
- OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
- y.dump(map,osw);
- }*/
-}
+package com.nis.util; + + +import com.alibaba.fastjson.JSON; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; + +import java.io.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class YamlUtil { + + private static Yaml y; + + static { + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + y = new Yaml(options); + } + + /** + * snmp配置相关 + * @param param + * @param ymlPath + * @return + */ + @SuppressWarnings("unchecked") + public static boolean snmpYmlHandle(Set<String> param,String ymlPath) { + boolean flag=false; + if(param!=null && !param.isEmpty() && ymlPath != null && ymlPath.length() != 0) { + OutputStream out = null; + OutputStreamWriter osw = null; + try { + File file = new File(ymlPath); + out=new FileOutputStream(file); + osw=new OutputStreamWriter(out, "UTF-8"); + for(String s : param) { +// Object load = y.load(s); + Object load = JSON.parse(s); +// y.dump(y.load(s),osw); + y.dump(load,osw); + } +// RuntimeUtil.run(null, null, new String[]{"kill","-hup","`ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'`"}); +// RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","ps -ef |grep snmp_exporter|grep -v grep|awk \'{print $2}\'|xargs kill -hup"}); + flag = true; + out.close(); + osw.close(); + } catch (Exception e) { + System.out.println(LogPrintUtil.print(e)); + } finally { + if(out!=null) { + try { + out.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + if(osw!=null) { + try { + osw.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + } + } + return flag; + } + + /** + * datacenter相关配置 + * @param param + * @param ymlPath + * @return + */ + @SuppressWarnings("unchecked") + public static boolean subYmlHandle(List<Object> param,String ymlPath,String ruleYmlPath) { + boolean flag=false; + if(param!=null && ymlPath != null && ymlPath.length() != 0) { + FileInputStream fileInputStream =null; + OutputStream out = null; + OutputStreamWriter osw = null; + try { + File file = new File(ymlPath); + fileInputStream = new FileInputStream(file); + Map<String,Object> map = y.loadAs(fileInputStream, Map.class); + if(map==null) { + map=new HashMap(); + } + //修改 rule.yml配置文件 + File ruleYmlfile = new File(ruleYmlPath); + if(ruleYmlfile.exists()){ + // 文件存在则删除文件信息 + ruleYmlfile.delete(); + } + map.remove("rule_files"); + map.put("scrape_configs", param); + out=new FileOutputStream(file); + osw=new OutputStreamWriter(out, "UTF-8"); + y.dump(map,osw); + +// RuntimeUtil.run(null, null, new String[]{"kill","-hup","`ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'`"}); +// RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'|xargs kill -hup"}); + flag = true; + fileInputStream.close(); + out.close(); + osw.close(); + } catch (Exception e) { + System.out.println(LogPrintUtil.print(e)); + } finally { + if(fileInputStream!=null) { + try { + fileInputStream.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + if(out!=null) { + try { + out.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + if(osw!=null) { + try { + osw.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + } + } + return flag; + } + + /** + * global相关配置设置 + * @param param + * @param ymlPath + * @param ruleYmlPath + * @return + */ + @SuppressWarnings("unchecked") + public static boolean centerYmlHandle(Map<String,Object> param,String ymlPath,String ruleYmlPath){ + boolean flag=false; + if(param!=null && !param.isEmpty() && ymlPath != null && ymlPath.length() != 0) { + FileInputStream fileInputStream =null; + OutputStream out = null; + OutputStreamWriter osw = null; + try { + // 修改prometheus.yml配置文件 + File ymlfile = new File(ymlPath); + fileInputStream = new FileInputStream(ymlfile); + Map<String,Object> map = y.loadAs(fileInputStream, Map.class); + if(map==null) { + map=new HashMap(); + } + map.put("scrape_configs", param.get("scrape_configs")); + map.put("alerting", param.get("alerting")); + map.put("rule_files", param.get("rule_files")); + out = new FileOutputStream(ymlfile); + osw = new OutputStreamWriter(out, "UTF-8"); + y.dump(map,osw); + + //修改 rule.yml配置文件 + File ruleYmlfile = new File(ruleYmlPath); + if(!ruleYmlfile.exists()){ + // 文件不存在 创建文件 + ruleYmlfile.createNewFile(); + } + FileInputStream fileInputStream2 = new FileInputStream(ruleYmlfile); + Map<String,Object> map2 = y.loadAs(fileInputStream2, Map.class); + if(map2==null) { + map2=new HashMap(); + } + map2.put("groups", param.get("groups")); + OutputStream out2 = new FileOutputStream(ruleYmlfile); + OutputStreamWriter osw2 = new OutputStreamWriter(out2, "UTF-8"); + y.dump(map2,osw2); + +// RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'|xargs kill -hup"}); +// RuntimeUtil.run(null, null, new String[]{"kill","-hup","`ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'`"}); + flag = true; + osw.close(); + } catch (Exception e) { + // TODO Auto-generated catch block + System.out.println(LogPrintUtil.print(e)); + } finally { + if(fileInputStream!=null) { + try { + fileInputStream.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + if(out!=null) { + try { + out.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + if(osw!=null) { + try { + osw.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + } + } + return flag; + } + + + /** + * thanos rule 角色所需 rule.yml 配置文件处理 + * + * @param param + * @param ruleYmlPath + * @return + */ + public static boolean thanosRuleYmlHandle(Map<String, Object> param, String ruleYmlPath) { + boolean flag = false; + if (param != null && !param.isEmpty()) { + FileInputStream fileInputStream = null; + OutputStream out = null; + try { + // 修改 rule.yml配置文件 + File ruleYmlfile = new File(ruleYmlPath); + if (!ruleYmlfile.exists()) { + // 文件不存在 创建文件 + ruleYmlfile.createNewFile(); + } + FileInputStream fileInputStream2 = new FileInputStream(ruleYmlfile); + Map<String, Object> map2 = y.loadAs(fileInputStream2, Map.class); + if (map2 == null) { + map2 = new HashMap(); + } + map2.put("groups", param.get("groups")); + OutputStream out2 = new FileOutputStream(ruleYmlfile); + OutputStreamWriter osw2 = new OutputStreamWriter(out2, "UTF-8"); + y.dump(map2, osw2); + flag = true; + } catch (Exception e) { + // TODO Auto-generated catch block + System.out.println(LogPrintUtil.print(e)); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + } + } + return flag; + } + + /** + * prometheus启动项修改 + * @param filePath + * @param param + * @return + */ + public static boolean prometheusStartHandle(String filePath,String param) { + boolean flag=false; + RandomAccessFile raf = null; + try { + raf = new RandomAccessFile(new File(filePath), "rw"); + String readLine = null; + long lastPoint = 0; //记住上一次的偏移量 + while((readLine=raf.readLine())!=null) { + final long ponit = raf.getFilePointer(); + if(readLine.startsWith("ExecStart")) { + String replace = readLine.replaceAll("--storage.tsdb.retention.time=\\d+d", "--storage.tsdb.retention.time="+param+"d"); + raf.seek(lastPoint); + raf.writeBytes(replace); + } + lastPoint = ponit; + } + raf.close(); + RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl daemon-reload"}); + RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl stop prometheus"}); + RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","systemctl start prometheus"}); + flag=true; + } catch (FileNotFoundException e) { + System.out.println(LogPrintUtil.print(e)); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } finally { + if(raf!=null) { + try { + raf.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + } + return flag; + } + + /** + * prometheus全局配置修改 + * @param param + * @return + */ + @SuppressWarnings("unchecked") + public static boolean prometheusSettingHandle(Map<String, Object> param, String ymlPath) { + boolean flag=false; + if(param!=null && !param.isEmpty() &&ymlPath != null && ymlPath.length() != 0) { // + FileInputStream fileInputStream =null; + OutputStream out = null; + OutputStreamWriter osw = null; + try { + // 修改prometheus.yml配置文件 + File ymlfile = new File(ymlPath); + fileInputStream = new FileInputStream(ymlfile); + Map<String,Object> map = y.loadAs(fileInputStream, Map.class); + if(map==null) { + return false; + } + Map object = (Map) map.get("global"); + object.put(Constant.SCRAPE_INTERVAL, param.get(Constant.SCRAPE_INTERVAL)+"s"); + + out = new FileOutputStream(ymlfile); + osw = new OutputStreamWriter(out, "UTF-8"); + y.dump(map,osw); + + // RuntimeUtil.run(null, null, new String[]{"/bin/sh", "-c","ps -ef |grep prometheus|grep -v grep|awk \'{print $2}\'|xargs kill -hup"}); + flag = true; + osw.close(); + } catch (Exception e) { + // TODO Auto-generated catch block + System.out.println(LogPrintUtil.print(e)); + } finally { + if(fileInputStream!=null) { + try { + fileInputStream.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + if(out!=null) { + try { + out.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + if(osw!=null) { + try { + osw.close(); + } catch (IOException e) { + System.out.println(LogPrintUtil.print(e)); + } + } + } + } + return flag; + } + /*public static void main(String[] args) throws Exception { +// File file = new File("F:/workspace/nz-web/nz-admin/tmp/promRuleCheck1574925561786.yml"); + File file = new File("F:/prometheus.yml"); + FileInputStream fileInputStream = new FileInputStream(file); + Map map = y.loadAs(fileInputStream, Map.class); + + *//** + List l = new ArrayList(); + Map m1 = new LinkedHashMap(); + m1.put("job_name", "federate"); + + + m1.put("scrape_interval", "15s"); + m1.put("honor_labels", true); + m1.put("metrics_path", "/federate"); + + + List l2 =new ArrayList(); + List l3 =new ArrayList(); + l3.add("192.168.1.1:9090"); + l3.add("192.168.2.2:9090"); + Map m2 =new HashMap(); + m2.put("targets", l3); + l2.add(m2); + m1.put("static_configs", l2); + + Map m3 = new HashMap(); + List l4=new ArrayList(); + l4.add("{job=\"prometheus\"}"); + l4.add("{__name__=~\"job:.*\"}"); + m3.put("match[]", l4); + m1.put("params", m3); + + + l.add(m1); + map.put("scrape_configs", l); + **//* + + Map toCheck = new HashMap(); + + List groups = new ArrayList(); + + Map group = new HashMap(); + groups.add(group); + + List rules = new ArrayList(); + group.put("name", "example"); + group.put("rules", rules); + + for(int i=0;i<3;i++) { + Map labels = new HashMap(); + labels.put("severity", "warning"); + Map annotations = new HashMap(); + annotations.put("summary", "hhh"); + annotations.put("description", "1111"); + Map rule = new HashMap(); + rule.put("alert", "tttt"); + rule.put("expr", "up == 0"); + rule.put("for", "70s"); + rule.put("labels", labels); + rule.put("annotations", annotations); + rules.add(rule); + } + map.put("groups", groups); + + Map alertManager =new HashMap(); + List staticConfigList=new ArrayList(); + Map staticConfigs =new HashMap(); + staticConfigList.add(staticConfigs); + List staticConfig =new ArrayList(); + Map targets =new HashMap(); + List target =new ArrayList(); + List alertData =new ArrayList(); + alertData.add("192.168.41.134:8008"); + alertManager.put("alertmanagers",staticConfigList); + staticConfigs.put("static_configs", staticConfig); + staticConfig.add(targets); + targets.put("targets", alertData); + map.put("alerting", alertManager); + OutputStream out = new FileOutputStream(file); + OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8"); + y.dump(map,osw); + }*/ +} |
