summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorshizhendong <[email protected]>2020-04-30 15:34:54 +0800
committershizhendong <[email protected]>2020-04-30 15:34:54 +0800
commit48346ca79b1ef24b8ccbd826fefd5ffc6d80428d (patch)
tree692e83c2c2efc6f6b3766a4cf4c1177442fd38f0
parentb041c34f5bae7f217f561f0205f7cd16fa95c9ab (diff)
fix: 修改traffic接口不能被prometheus服务发现问题
-rw-r--r--src/main/java/com/nis/controller/TrafficController.java2
-rw-r--r--src/main/java/com/nis/entity/Traffic.java25
-rw-r--r--src/main/java/com/nis/service/impl/TrafficServiceImpl.java13
-rw-r--r--src/main/java/com/nis/util/SnmpUtil.java112
-rw-r--r--src/main/resources/mapper/TrafficDao.xml27
5 files changed, 146 insertions, 33 deletions
diff --git a/src/main/java/com/nis/controller/TrafficController.java b/src/main/java/com/nis/controller/TrafficController.java
index 73c498f..6a4284d 100644
--- a/src/main/java/com/nis/controller/TrafficController.java
+++ b/src/main/java/com/nis/controller/TrafficController.java
@@ -19,7 +19,7 @@ public class TrafficController {
@Autowired
private TrafficService trafficService;
- @GetMapping("/traffic")
+ @GetMapping(value = "/traffic", produces = "text/plain;charset=utf-8")
private String traffic(Integer dcId) {
String trafficByIdcId = trafficService.getTrafficByIdcId(dcId);
return trafficByIdcId;
diff --git a/src/main/java/com/nis/entity/Traffic.java b/src/main/java/com/nis/entity/Traffic.java
index 6a600bf..de87981 100644
--- a/src/main/java/com/nis/entity/Traffic.java
+++ b/src/main/java/com/nis/entity/Traffic.java
@@ -16,16 +16,37 @@ import java.io.Serializable;
@TableName("idc_traffic")
@Data
public class Traffic implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
@TableId
private Integer id;
- private String assetId;
private Integer idcId;
private String direction;
private Integer ifIndex;
private String ifdescr;
private String tags;
- @TableField(exist = false)
+ /**
+ * ip地址
+ */
private String host;
+ /**
+ * 端口 默认161
+ */
+ private Integer port;
+ /**
+ * snmp版本 默认v2
+ */
+ private Integer version;
+ /**
+ * snmp团体名 默认 public
+ */
+ private String community;
+ /**
+ * snmp认证信息
+ */
+ private Object auth;
+
@TableField(exist = false)
private String datacenter;
}
diff --git a/src/main/java/com/nis/service/impl/TrafficServiceImpl.java b/src/main/java/com/nis/service/impl/TrafficServiceImpl.java
index 441ac0a..8d4afd8 100644
--- a/src/main/java/com/nis/service/impl/TrafficServiceImpl.java
+++ b/src/main/java/com/nis/service/impl/TrafficServiceImpl.java
@@ -1,5 +1,6 @@
package com.nis.service.impl;
+import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nis.dao.SnmpMibDao;
@@ -63,15 +64,21 @@ public class TrafficServiceImpl implements TrafficService {
String resultOid;
String name, index, direction, descHelp, descType, inOutPrefix, trafficTags, tags, trafficDirection;
List<Map> resultData = new ArrayList<>();
+ Traffic t;
+ Map auth = new HashMap();
for (Map.Entry<String, List<Traffic>> entry : listMap.entrySet()) {
try {
- resultData = SnmpUtil.snmpWalk(entry.getKey(), Constant.IFTABLE_OID);
+ t = entry.getValue().get(0);
+ if (t.getAuth() != null) {
+ auth = JSONObject.parseObject(t.getAuth().toString(), Map.class);
+ }
+ 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);
}
if (CollectionUtils.isEmpty(resultData)) {
- logger.error("通过SNMP采集IfTable失败,ip ->" + entry.getKey() + ",请检查agent 服务是否开启,是否可达。");
+ logger.error("通过SNMP采集IfTable失败,ip ->" + entry.getKey() + ",请检查agent 服务是否开启、是否可达、身份验证信息是否正确。");
continue;
}
@@ -114,7 +121,7 @@ public class TrafficServiceImpl implements TrafficService {
}
if (StringUtils.isNotEmpty(trafficTags)) {
- tags = "tags=" + "\"" + trafficTags + "\"" + ",";
+ tags = "tags=" + JSON.toJSONString(trafficTags) + ",";
}
inOutPrefix = "{ifIndex=" + "\"" + traffic.getIfIndex() + "\"" + ","
+ "ifDescr=" + "\"" + traffic.getIfdescr() + "\"" + ","
diff --git a/src/main/java/com/nis/util/SnmpUtil.java b/src/main/java/com/nis/util/SnmpUtil.java
index 4bea2ef..ed08422 100644
--- a/src/main/java/com/nis/util/SnmpUtil.java
+++ b/src/main/java/com/nis/util/SnmpUtil.java
@@ -1,10 +1,13 @@
package com.nis.util;
+import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
+import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.security.*;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
@@ -32,29 +35,99 @@ public class SnmpUtil {
// 默认端口
private static final Integer DEFAULT_PORT = 161;
- /**
- * 获取target
- *
- * @param ip
- * @return
- */
- public static Target getTatget(String ip) {
- Target target = new CommunityTarget();
- // 默认版本 v2
- target.setVersion(DEFAULT_VERSION);
- // 团体名
- ((CommunityTarget) target).setCommunity(new OctetString(DEFAULT_COMMUNITY));
+ public static Target getTatget(Integer version, String community, Map<String, String> auth, String ip, Integer port) {
+ Target target = null;
+ if (version == SnmpConstants.version3) {
+ // 添加用户
+ OID authProtocolOid = null;
+ String authProtocol = auth.get("authProtocol");
+ if ("MD5".equals(authProtocol)) {
+ authProtocolOid = AuthMD5.ID;
+ } else if ("SHA".equals(authProtocol)) {
+ authProtocolOid = AuthSHA.ID;
+ }
+
+ OID privProtocolOid = null;
+ String privProtocol = auth.get("privProtocol");
+ if ("DES".equals(privProtocol)) {
+ privProtocolOid = PrivDES.ID;
+ } else if ("AES".equals(privProtocol)) {
+ privProtocolOid = PrivAES128.ID;
+ }
+
+ String privPassword = auth.get("privPassword");
+ OctetString octetPrivPassword = null;
+ if(StringUtils.isNotEmpty(privPassword)){
+ octetPrivPassword = new OctetString(privPassword);
+ }
+
+ String password = auth.get("password");
+ OctetString octetpassword = null;
+ if(StringUtils.isNotEmpty(password)){
+ octetpassword = new OctetString(password);
+ }
+
+ OctetString username = new OctetString(auth.get("username"));
+ UsmUser user = new UsmUser(username, authProtocolOid, octetpassword, privProtocolOid, octetPrivPassword);
+ snmp.getUSM().addUser(username, user);
+// snmp.getUSM().addUser(user);
+ target = new UserTarget();
+
+ String level = auth.get("securityLevel");
+ // 不为空时设置安全级别 如果为空则不处理 默认的安全级别为noAuthNoPriv 不认证不加密
+ if(StringUtils.isNotEmpty(level)){
+ // 设置安全级别
+ switch (level) {
+ case "authPriv": {
+ ((UserTarget) target).setSecurityLevel(SecurityLevel.AUTH_PRIV);
+ break;
+ }
+ case "noAuthNoPriv": {
+ ((UserTarget) target).setSecurityLevel(SecurityLevel.NOAUTH_NOPRIV);
+ break;
+ }
+ case "authNoPriv": {
+ ((UserTarget) target).setSecurityLevel(SecurityLevel.AUTH_NOPRIV);
+ break;
+ }
+ }
+ }
+ ((UserTarget) target).setSecurityName(username);
+ target.setVersion(SnmpConstants.version3);
+ } else {
+ target = new CommunityTarget();
+ target.setVersion(SnmpConstants.version2c);
+ // 如果没有设置团体名 默认使用public
+ if (StringUtils.isEmpty(community)) {
+ community = DEFAULT_COMMUNITY;
+ }
+ ((CommunityTarget) target).setCommunity(new OctetString(community));
+ }
// 超时时间
target.setTimeout(DEFAULT_TIMEOUT);
// 重试次数
target.setRetries(DEFAULT_RETRY);
- Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip + "/" + DEFAULT_PORT);
+ Address address = GenericAddress.parse(DEFAULT_PROTOCOL + ":" + ip + "/" + port);
target.setAddress(address);
return target;
}
+ private static PDU getPdu(Integer version) {
+ if (version == SnmpConstants.version3) {
+ ScopedPDU pdu = new ScopedPDU();
+ // 如果agent上设定的contextEngineId和snmpEngineId不一致 这里需要设置引擎id
+ // pdu.setContextEngineID(new OctetString(""));
+ // 如果agent上设定了contextName 这里需要设置contextName
+ // pdu.setContextName(new OctetString(""));
+ return pdu;
+ } else {
+ PDU pdu = new PDU();
+ return pdu;
+ }
+ }
+
/**
* snmpwalk
@@ -64,16 +137,23 @@ public class SnmpUtil {
* @return
* @throws IOException
*/
- public static List<Map> snmpWalk(String ip, String oid) throws IOException {
+ public static List<Map> snmpWalk(String ip, Integer port, Integer version, String community, String oid, Map<String, String> auth) throws IOException {
List<Map> resultData = new ArrayList<>();
try {
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
- Target target = getTatget(ip);
+ // 如果是v3版本
+ if (version == SnmpConstants.version3) {
+ // 设置安全模式
+ USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
+ SecurityModels.getInstance().addSecurityModel(usm);
+ }
+
+ Target target =getTatget(version, community, auth, ip, port);
snmp.listen();
- PDU pdu = new PDU();
+ PDU pdu = getPdu(version);
OID targetOID = new OID(oid);
pdu.add(new VariableBinding(targetOID));
diff --git a/src/main/resources/mapper/TrafficDao.xml b/src/main/resources/mapper/TrafficDao.xml
index 47a1727..be779ae 100644
--- a/src/main/resources/mapper/TrafficDao.xml
+++ b/src/main/resources/mapper/TrafficDao.xml
@@ -1,28 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nis.dao.TrafficDao">
- <resultMap type="com.nis.entity.Traffic" id="trafficMap">
+ <resultMap type="com.nis.entity.Traffic" id="trafficMap">
<result property="id" column="id"/>
- <result property="assetId" column="asset_id"/>
<result property="idcId" column="idc_id"/>
<result property="direction" column="direction"/>
<result property="ifIndex" column="ifIndex"/>
<result property="ifdescr" column="ifdescr"/>
<result property="tags" column="tags"/>
+ <result property="host" column="host"/>
+ <result property="port" column="port"/>
+ <result property="version" column="version"/>
+ <result property="community" column="community"/>
+ <result property="auth" column="auth"/>
+ <result property="datacenter" column="datacenter"/>
</resultMap>
- <select id="selectHost" resultMap="trafficMap">
- SELECT DISTINCT
- (asset.`host`),idc_traffic.*,idc.name as datacenter
+ <select id="selectHost" resultMap="trafficMap">
+ SELECT
+ idc_traffic.*,
+ idc.NAME AS datacenter
FROM
- idc_traffic
- LEFT JOIN asset ON asset.id = idc_traffic.asset_id
+ idc_traffic
LEFT JOIN idc ON idc.id = idc_traffic.idc_id
WHERE
- 1=1
- <if test="idcId!=null">
- and idc_traffic.idc_id = #{idcId}
+ 1=1
+ <if test="idcId != null">
+ and idc_traffic.idc_id = #{idcId}
</if>
- </select>
+ </select>
</mapper>