summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authortanghao <default@DESKTOP-7FEGRP2>2020-01-12 15:51:19 +0800
committertanghao <default@DESKTOP-7FEGRP2>2020-01-12 15:51:19 +0800
commit42e1d59b0a260f701d2f04ec14eb29322f5115b3 (patch)
tree699e111ba55852fa28560d91cd393b86029eeda2
parent253f14b922b603129568a6cb2a2742e213091f55 (diff)
fix:confagent组件实现 trap server 接收消息,并组织成alert message 格式
feat: 1.修复细节bug 2.修改部分命名格式 idc-->dc
-rw-r--r--pom.xml19
-rw-r--r--src/main/java/com/nis/ConfagentMain.java16
-rw-r--r--src/main/java/com/nis/dao/AlertRuleDao.java1
-rw-r--r--src/main/java/com/nis/entity/AlertManagerEnum.java13
-rw-r--r--src/main/java/com/nis/entity/AlertRule.java10
-rw-r--r--src/main/java/com/nis/entity/TrapMessage.java162
-rw-r--r--src/main/java/com/nis/job/ConfagentJob.java22
-rw-r--r--src/main/java/com/nis/server/SNMPTrapServer.java474
-rw-r--r--src/main/java/com/nis/service/AlertRuleService.java2
-rw-r--r--src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java10
-rw-r--r--src/main/java/com/nis/service/impl/ConfEventServiceImpl.java3
-rw-r--r--src/main/resources/confagent.properties14
-rw-r--r--src/main/resources/mapper/AlertRuleDao.xml6
-rw-r--r--src/main/resources/spring.xml17
14 files changed, 739 insertions, 30 deletions
diff --git a/pom.xml b/pom.xml
index d273a7d..da3bfa5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -26,7 +26,7 @@
<commons-codec.version>1.9</commons-codec.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<commons-beanutils.version>1.9.1</commons-beanutils.version>
- <jackson.version>2.2.3</jackson.version>
+ <jackson.version>2.9.8</jackson.version>
<fastjson.version>1.1.40</fastjson.version>
<guava.version>17.0</guava.version>
@@ -302,8 +302,12 @@
</dependency>
-
-
+ <!-- snmp -->
+ <dependency>
+ <groupId>org.snmp4j</groupId>
+ <artifactId>snmp4j</artifactId>
+ <version>2.6.2</version>
+ </dependency>
<!-- TEST begin -->
<dependency>
@@ -324,11 +328,18 @@
<version>4.1.19</version>
</dependency>
-
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-web</artifactId>
+ <version>4.0.4.RELEASE</version>
+ <scope>compile</scope>
+ </dependency>
+
</dependencies>
<build>
<outputDirectory>${project.basedir}/src/main/webapp/WEB-INF/classes/</outputDirectory>
+ <finalName>${project.artifactId}</finalName>
<plugins>
<!-- Compiler 插件, 设定JDK版本 -->
<plugin>
diff --git a/src/main/java/com/nis/ConfagentMain.java b/src/main/java/com/nis/ConfagentMain.java
index c3f7cae..1555912 100644
--- a/src/main/java/com/nis/ConfagentMain.java
+++ b/src/main/java/com/nis/ConfagentMain.java
@@ -1,21 +1,25 @@
package com.nis;
+import java.io.IOException;
-import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.nis.server.SNMPTrapServer;
+
/*@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring.xml")*/
public class ConfagentMain {
private static Logger logger = LoggerFactory.getLogger(ConfagentMain.class);
-
public static void main(String[] args) {
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
- System.out.println("initContext successfully");
+
+ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring.xml");
+ /* ApplicationContext ctx = new FileSystemXmlApplicationContext(
+ "file:" + System.getProperty("confagent.dir")
+ + File.separator+ "spring.xml");*/
+
logger.info("initContext successfully");
}
}
diff --git a/src/main/java/com/nis/dao/AlertRuleDao.java b/src/main/java/com/nis/dao/AlertRuleDao.java
index 16ed893..bf7ee7e 100644
--- a/src/main/java/com/nis/dao/AlertRuleDao.java
+++ b/src/main/java/com/nis/dao/AlertRuleDao.java
@@ -8,4 +8,5 @@ public interface AlertRuleDao {
List<AlertRule> selectList();
+ List<AlertRule> selectBulidInRule();
}
diff --git a/src/main/java/com/nis/entity/AlertManagerEnum.java b/src/main/java/com/nis/entity/AlertManagerEnum.java
new file mode 100644
index 0000000..424d5a7
--- /dev/null
+++ b/src/main/java/com/nis/entity/AlertManagerEnum.java
@@ -0,0 +1,13 @@
+package com.nis.entity;
+
+public enum AlertManagerEnum {
+ Alert_api("alert_api"),
+ Alert_path_prefix("alert_path_prefix");
+ private final String paramkey;
+ private AlertManagerEnum(String paramkey) {
+ this.paramkey = paramkey;
+ }
+ public String getValue() {
+ return paramkey;
+ }
+}
diff --git a/src/main/java/com/nis/entity/AlertRule.java b/src/main/java/com/nis/entity/AlertRule.java
index 02bbdf3..93eba40 100644
--- a/src/main/java/com/nis/entity/AlertRule.java
+++ b/src/main/java/com/nis/entity/AlertRule.java
@@ -41,6 +41,10 @@ public class AlertRule implements Serializable{
* 关联id
*/
private Integer linkId;
+ /**
+ * 是否为内置规则
+ */
+ private Boolean buildIn;
public Integer getId() {
return id;
}
@@ -101,4 +105,10 @@ public class AlertRule implements Serializable{
public void setLinkId(Integer linkId) {
this.linkId = linkId;
}
+ public Boolean getBuildIn() {
+ return buildIn;
+ }
+ public void setBuildIn(Boolean buildIn) {
+ this.buildIn = buildIn;
+ }
}
diff --git a/src/main/java/com/nis/entity/TrapMessage.java b/src/main/java/com/nis/entity/TrapMessage.java
new file mode 100644
index 0000000..b69bd74
--- /dev/null
+++ b/src/main/java/com/nis/entity/TrapMessage.java
@@ -0,0 +1,162 @@
+package com.nis.entity;
+
+import java.io.Serializable;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.snmp4j.PDU;
+import org.snmp4j.smi.Variable;
+
+public class TrapMessage implements Serializable{
+
+ private String agentSendIP;
+ private String pduAgentIP;
+ private Timestamp receiverTime;
+ private int trapVersion;
+ private int trapV1GenericType;
+ private int trapV1SpecificType;
+ private String trapName;
+ private String trapOID;
+ private List trapPDUOIDs;
+ private List trapPDUOIDValues;
+ private PDU originalPDU;
+ public static final int TrapVersionV1 = 1;
+ public static final int TrapVersionV2 = 2;
+
+ public TrapMessage()
+ {
+ agentSendIP = "";
+ pduAgentIP = "";
+ receiverTime = new Timestamp(System.currentTimeMillis());
+ trapVersion = 1;
+ trapV1GenericType = -1;
+ trapV1SpecificType = -1;
+ trapName = "";
+ trapOID = "";
+ trapPDUOIDs = new ArrayList();
+ trapPDUOIDValues = new ArrayList();
+ }
+
+ public Variable getOIDValue(String s)
+ {
+ for (int i = 0; i < trapPDUOIDs.size(); i++)
+ {
+ String s1 = (String)trapPDUOIDs.get(i);
+ if (s.equals(s1))
+ return (Variable)trapPDUOIDValues.get(i);
+ }
+
+ return null;
+ }
+
+ public String getAgentSendIP()
+ {
+ return agentSendIP;
+ }
+
+ public void setAgentSendIP(String s)
+ {
+ agentSendIP = s;
+ }
+
+ public Timestamp getReceiverTime()
+ {
+ return receiverTime;
+ }
+
+ public void setReceiverTime(Timestamp timestamp)
+ {
+ receiverTime = timestamp;
+ }
+
+ public int getTrapVersion()
+ {
+ return trapVersion;
+ }
+
+ public void setTrapVersion(int i)
+ {
+ trapVersion = i;
+ }
+
+ public String getTrapName()
+ {
+ return trapName;
+ }
+
+ public void setTrapName(String s)
+ {
+ trapName = s;
+ }
+
+ public String getTrapOID()
+ {
+ return trapOID;
+ }
+
+ public void setTrapOID(String s)
+ {
+ trapOID = s;
+ }
+
+ public String getPduAgentIP()
+ {
+ return pduAgentIP;
+ }
+
+ public void setPduAgentIP(String s)
+ {
+ pduAgentIP = s;
+ }
+
+ public int getTrapV1GenericType()
+ {
+ return trapV1GenericType;
+ }
+
+ public void setTrapV1GenericType(int i)
+ {
+ trapV1GenericType = i;
+ }
+
+ public int getTrapV1SpecificType()
+ {
+ return trapV1SpecificType;
+ }
+
+ public void setTrapV1SpecificType(int i)
+ {
+ trapV1SpecificType = i;
+ }
+
+ public List getTrapPDUOIDs()
+ {
+ return trapPDUOIDs;
+ }
+
+ public void setTrapPDUOIDs(List list)
+ {
+ trapPDUOIDs = list;
+ }
+
+ public List getTrapPDUOIDValues()
+ {
+ return trapPDUOIDValues;
+ }
+
+ public void setTrapPDUOIDValues(List list)
+ {
+ trapPDUOIDValues = list;
+ }
+
+ public void setOriginalPDU(PDU pdu)
+ {
+ originalPDU = pdu;
+ }
+
+ public PDU getOriginalPDU()
+ {
+ return originalPDU;
+ }
+}
diff --git a/src/main/java/com/nis/job/ConfagentJob.java b/src/main/java/com/nis/job/ConfagentJob.java
index 5ae1aaa..03cd926 100644
--- a/src/main/java/com/nis/job/ConfagentJob.java
+++ b/src/main/java/com/nis/job/ConfagentJob.java
@@ -11,6 +11,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.alibaba.fastjson.JSON;
+import com.nis.entity.AlertManagerEnum;
import com.nis.entity.AlertRule;
import com.nis.entity.Endpoint;
import com.nis.entity.Promserver;
@@ -69,7 +70,10 @@ public class ConfagentJob{
// 判断本次表格数据与之前数据是否有变化判断是否执行操作
boolean changeFlag = confEventService.compareData(confEvents);
//先判断conf_event表中是否有数据变化 程序初始进入map数据为空 则全量配置更新同步
+ logger.debug("before confEvents data {} ",JSON.toJSON(confEvents));
if(confEvents==null || changeFlag ) {
+ logger.debug("data had change confEvents data {}",JSON.toJSON(confEvents));
+ logger.debug("data had change flag {}",changeFlag);
if(promserver.getType()==1) {
Map centerResult = centerHandle();
logger.debug("center result info {} ",JSON.toJSON(centerResult));
@@ -107,7 +111,6 @@ public class ConfagentJob{
}
}
logger.info("Synchronization configurator end");
- System.err.println("Synchronization configurator end");
}
/**
@@ -147,7 +150,7 @@ public class ConfagentJob{
Map job2 = new HashMap();
job2.put("targets",list);
Map job3 = new HashMap();
- job3.put("idc", endpointInfos.get(m).getIdc().getName());
+ job3.put("dc", endpointInfos.get(m).getIdc().getName());
job3.put("project", endpointInfos.get(m).getProject().getName());
job3.put("asset",endpointInfos.get(m).getAsset().getHost());
job3.put("module",endpointInfos.get(m).getModule().getName());
@@ -219,7 +222,7 @@ public class ConfagentJob{
Map m3 = new HashMap();
List l4=new ArrayList();
// l4.add("{job=\"prometheus\"}");
- l4.add("{idc=~\".+\"}");
+ l4.add("{dc=~\".+\"}");
m3.put("match[]", l4);
m1.put("params", m3);
@@ -271,14 +274,23 @@ public class ConfagentJob{
List<SysConfig> sysConfigs = sysConfigService.queryList();
Map alertManager =new HashMap();
List staticConfigList=new ArrayList();
- Map staticConfigs =new HashMap();
+ LinkedHashMap staticConfigs =new LinkedHashMap();
staticConfigList.add(staticConfigs);
List staticConfig =new ArrayList();
Map targets =new HashMap();
List target =new ArrayList();
List alertData =new ArrayList();
if(!sysConfigs.isEmpty()) {
- alertData.add(sysConfigs.get(0).getParamValue());
+ for(SysConfig sysconfig : sysConfigs) {
+ if(sysconfig.getParamKey().equals(AlertManagerEnum.Alert_api.getValue())) {
+ alertData.add(sysconfig.getParamValue());
+ }else if(sysconfig.getParamKey().equals(AlertManagerEnum.Alert_path_prefix.getValue())){
+ staticConfigs.put("path_prefix", sysconfig.getParamValue());
+ }
+ }
+ }
+ if(staticConfigs.get("path_prefix")==null) {
+ staticConfigs.put("path_prefix","/");
}
alertManager.put("alertmanagers",staticConfigList);
staticConfigs.put("static_configs", staticConfig);
diff --git a/src/main/java/com/nis/server/SNMPTrapServer.java b/src/main/java/com/nis/server/SNMPTrapServer.java
new file mode 100644
index 0000000..2966ec7
--- /dev/null
+++ b/src/main/java/com/nis/server/SNMPTrapServer.java
@@ -0,0 +1,474 @@
+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.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.druid.util.StringUtils;
+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.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
+ *
+ */
+public class SNMPTrapServer implements CommandResponder{// implements CommandResponder, extends Service
+ private static Logger logger = LoggerFactory.getLogger(SNMPTrapServer.class);
+ private static SNMPTrapServer ts = null;
+ private AlertRule alertRule;
+ @Value("${snmp.ip}")
+ private String snmpIp;
+ @Value("${snmp.trapThredPoolSize}")
+ private String snmpTrapThredPoolSize;
+ @Value("${snmp.trapPort}")
+ private String snmpTrapPort;
+ @Autowired
+ private AlertRuleService alertRuleService;
+ @Autowired
+ private SysConfigService sysConfigService;
+ private String alertApi;
+ private String alertPathPrefix;
+ /*public static SNMPTrapServer getInstance() throws IOException{
+ if(ts == null){
+ ts = new SNMPTrapServer();
+ logger.info("SNMP Trap Server 启动成功");
+ }else{
+ logger.info("SNMP TrapServer 已启动");
+ }
+ return ts;
+ }*/
+
+ public void initServer() throws Exception{
+ System.err.println("-------------------------------");
+ System.err.println("-------------------------------");
+ System.err.println("-------------------------------");
+ System.err.println("-------------------------------");
+ System.err.println("-------------------------------");
+ System.err.println("-------------------------------");
+ //加载alert_rule表内置规则
+ 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("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:" + snmpIp + "/" + snmpTrapPort)); // 本地IP与监听端口
+ logger.info("snmpTrapPort is {}",snmpTrapPort);
+ logger.info("ipaddr is {}",snmpIp);
+ 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
+ {
+ 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(!StringUtils.isEmpty(trapName)) {
+ 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));
+ }
+ catch (Exception exception)
+ {
+ exception.printStackTrace();
+ logger.error((new StringBuilder("Error parsing UDP trap:")).append(exception.getMessage()).toString());
+ }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(int i=0;i<vector.size();i++){
+// VariableBinding vbing = (VariableBinding)vector.elementAt(i);
+// s = vbing.getOid().toString();
+// trapmessageinfo.getTrapPDUOIDs().add(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;
+
+ }
+ public static void main(String [] args) {
+ /*try {
+ SNMPTrapServer.getInstance();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }*/
+ }
+
+ /**
+ * 将十进六制转换成为中文
+ */
+ 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/AlertRuleService.java b/src/main/java/com/nis/service/AlertRuleService.java
index 88e1919..0c490d8 100644
--- a/src/main/java/com/nis/service/AlertRuleService.java
+++ b/src/main/java/com/nis/service/AlertRuleService.java
@@ -9,4 +9,6 @@ import com.nis.entity.ConfEvent;
public interface AlertRuleService {
public List<AlertRule> queryList();
+
+ public AlertRule queryBulidInRule();
}
diff --git a/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java b/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java
index d9d22db..c7a87c2 100644
--- a/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java
+++ b/src/main/java/com/nis/service/impl/AlertRuleServiceImpl.java
@@ -19,4 +19,14 @@ public class AlertRuleServiceImpl implements AlertRuleService {
public List<AlertRule> queryList() {
return alertRuleDao.selectList();
}
+
+ @Override
+ public AlertRule queryBulidInRule() {
+ List<AlertRule> results = alertRuleDao.selectBulidInRule();
+ if(results!=null && results.size()>0) {
+ return results.get(0);
+ }else {
+ return null;
+ }
+ }
}
diff --git a/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java b/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java
index dc6c12d..5a7a4b0 100644
--- a/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java
+++ b/src/main/java/com/nis/service/impl/ConfEventServiceImpl.java
@@ -7,6 +7,7 @@ import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
+import com.alibaba.fastjson.JSON;
import com.nis.dao.ConfEventDao;
import com.nis.entity.ConfEvent;
import com.nis.service.ConfEventService;
@@ -40,7 +41,7 @@ public class ConfEventServiceImpl implements ConfEventService {
}
List<ConfEvent> datas = confEventDao.selectList();
for(ConfEvent data:datas) {
- if(!(data.getValue()==map.get(data.getTable()))) {
+ if(!(data.getValue().equals(map.get(data.getTable())))) {
flag = true;
}
}
diff --git a/src/main/resources/confagent.properties b/src/main/resources/confagent.properties
index e4442df..2993179 100644
--- a/src/main/resources/confagent.properties
+++ b/src/main/resources/confagent.properties
@@ -1,10 +1,20 @@
+## database config
jdbc.driver=com.mysql.jdbc.Driver
-jdbc.url=jdbc:mysql://192.168.40.247:3306/nz-test?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false
+jdbc.url=jdbc:mysql://192.168.40.247:3306/nz?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=111111
ipaddr=192.168.40.247
+
+## prometheus config
ymlPath=F:/prometheus.yml
ruleYmlPath=F:/rule.yml
prometheusPort=9090
-job.cron=0/15 * * * * ? \ No newline at end of file
+
+## job config
+job.cron=0/15 * * * * ?
+
+## snmp trap config
+snmp.trapThredPoolSize=2
+snmp.trapPort=162
+snmp.ip=192.168.41.87 \ No newline at end of file
diff --git a/src/main/resources/mapper/AlertRuleDao.xml b/src/main/resources/mapper/AlertRuleDao.xml
index 0008c0d..569e6df 100644
--- a/src/main/resources/mapper/AlertRuleDao.xml
+++ b/src/main/resources/mapper/AlertRuleDao.xml
@@ -12,10 +12,14 @@
<result property="receiver" column="receiver"/>
<result property="type" column="type"/>
<result property="linkId" column="link_id"/>
+ <result property="buildIn" column="build_in"/>
</resultMap>
<select id="selectList" resultMap="alertRule">
- select * from alert_rule
+ select * from alert_rule where build_in != 1
</select>
+ <select id="selectBulidInRule" resultMap="alertRule">
+ select * from alert_rule where build_in = 1
+ </select>
</mapper> \ No newline at end of file
diff --git a/src/main/resources/spring.xml b/src/main/resources/spring.xml
index 6fe2c2d..eed53d6 100644
--- a/src/main/resources/spring.xml
+++ b/src/main/resources/spring.xml
@@ -15,15 +15,16 @@
<description>Spring Configuration</description>
<!-- 加载配置属性文件 -->
- <context:property-placeholder location="classpath*:confagent.properties" />
+ <!-- <context:property-placeholder location="classpath*:confagent.properties" /> -->
- <bean id="propertyConfigurer" class="com.nis.util.PropertyPlaceholder">
+ <!-- <bean id="propertyConfigurer" class="com.nis.util.PropertyPlaceholder"> -->
+ <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:confagent.properties</value>
+ <!-- <value>file:${confagent.dir}/confagent.properties</value> -->
</property>
</bean>
-
-
+
<!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。 -->
<context:component-scan base-package="com.nis"><!-- base-package 如果多个,用“,”分隔 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
@@ -98,12 +99,6 @@
<property name="filters" value="stat" />
</bean>
- <!-- <bean id="jobFactory" class="com.nis.job.ConfagentJobFactory"/>
-
- <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
- <property name="jobFactory" ref="jobFactory"/>
- </bean> -->
-
<bean id="jobFactory" class="com.nis.job.ConfagentJobFactory"/>
@@ -138,5 +133,5 @@
</bean>
-
+ <bean id="snmpTrapServer" class="com.nis.server.SNMPTrapServer" scope="singleton" init-method="initServer" lazy-init ="false"></bean>
</beans> \ No newline at end of file