Authored by 王凤

合并分支 'master_zmm' 到 'master'

添加主机状态监控。

添加主机状态监控。

查看合并请求 !2
... ... @@ -32,8 +32,7 @@ CREATE MEMORY TABLE TB_CFG_SNMP_PRI_KPI_CONVERT(KPI_ID VARCHAR(20) NOT NULL,SYS_
CREATE MEMORY TABLE TB_CFG_SNMP_PRI_OID(SYS_OBJECT_ID VARCHAR(512),NAME VARCHAR(32),OID VARCHAR(512))
CREATE MEMORY TABLE TB_CFG_OID_MIB(GUID VARCHAR(37) NOT NULL PRIMARY KEY,KPI_ID VARCHAR(20) NOT NULL,UNIT_ID VARCHAR(255),OID VARCHAR(100))
CREATE MEMORY TABLE TB_TOPO_PHYSICAL_DEVICE(DEVICE_ID VARCHAR(50),DEVICE_IP VARCHAR(30),DEVICE_ALIAS VARCHAR(100),DEVICE_CATALOG VARCHAR(100),DEVICE_CNAME VARCHAR(100),KBP_CLASS VARCHAR(100),DEVICE_DESC VARCHAR(500),DEVICE_ROOM VARCHAR(100),DEVICE_RACK VARCHAR(100),CREATE_DATE TIMESTAMP)
CREATE MEMORY TABLE TB_DOWNTIME_HOST(DEVICE_ID VARCHAR(50),DEVICE_IP VARCHAR(30),DEVICE_ALIAS VARCHAR(100),KBP_CLASS VARCHAR(100),PROTOCOL VARCHAR(10),PROTOCOL_PORT VARCHAR(10),USER_NAME VARCHAR(50),PASSWORD VARCHAR(100),CREATE_DATE TIMESTAMP)
CREATE MEMORY TABLE TB_DOWNTIME_HOST_HISTORY(DEVICE_ID VARCHAR(50),DEVICE_IP VARCHAR(30),CREATE_DATE VARCHAR(10))
CREATE MEMORY TABLE TB_CONNECTION_STATE(DEVICE_ID VARCHAR(50),DEVICE_IP VARCHAR(30),DEVICE_STATE VARCHAR(4),CREATE_DATE BIGINT)
CREATE USER SA PASSWORD ""
GRANT DBA TO SA
SET WRITE_DELAY 20
... ...
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"
"http://www.ibatis.com/dtd/sql-map-2.dtd">
<sqlMap namespace="TB_CONNECTION_STATE">
<typeAlias alias="connectionStateBean" type="com.sitech.ismp.check.downtime.ConnectionStateBean" />
<insert id="addPingConnectionState" parameterClass="connectionStateBean">
INSERT INTO TB_CONNECTION_STATE (DEVICE_ID,DEVICE_IP,DEVICE_STATE,CREATE_DATE)
VALUES (#DEVICE_ID#,#DEVICE_IP#,#DEVICE_STATE#,#CREATE_DATE#);
</insert>
<select id="getStatByParam" parameterClass="java.util.HashMap">
SELECT DEVICE_STATE FROM TB_CONNECTION_STATE
WHERE DEVICE_STATE='DOWN' AND DEVICE_IP= #DEVICE_IP# ORDER BY CREATE_DATE DESC
</select>
</sqlMap>
... ...
package com.sitech.ismp.check.downtime;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.sitech.util.SqlMapFactory;
import org.apache.log4j.Logger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @author frank zmm@honggroup.com.cn
* @Description: 检查主机,数据库,中间件的连接状态dao.
* @Package com.sitech.ismp.check.downtime
* @ClassName: com.sitech.ismp.check.downtime.CheckConnectionDao
* @date 2017年04月22日 15:05
*/
public class CheckConnectionDao {
protected static SqlMapClient sqlmapClient;
protected static SqlMapClient oracleSqlMapClient ;
/**
* 因为继承 basedao 后,报basedao 找不到,因此写到方法里面。
*/
static {
sqlmapClient = SqlMapFactory.getDefaultSqlMapClient();
oracleSqlMapClient= SqlMapFactory.getOracleSqlMapClient("oracle_sqlmap.xml");
}
private static Logger log=Logger.getLogger(CheckConnectionDao.class);
/**
* 插入ping结果。
* @param bean
*/
public void addPingConnectionState(ConnectionStateBean bean){
try {
sqlmapClient.insert("addPingConnectionState", bean);
log.info("******* CheckConnectionDao **** execute method addPingConnectionState ******");
} catch (SQLException e) {
log.error("Exception while addPingConnectionState.",e);
}
}
/**
* 根据IP获取该IP对应ping不通的次数。
* @param map
* @return
*/
public List<ConnectionStateBean> getStatByParam(HashMap<String, Object> map){
List<ConnectionStateBean> beanList=new ArrayList<ConnectionStateBean>();
try {
beanList=sqlmapClient.queryForList("getStatByParam", map);
} catch (SQLException e) {
e.printStackTrace();
}
return beanList;
}
}
... ...
package com.sitech.ismp.check.downtime;
import com.sitech.util.upload.RomoteController;
import com.sitech.util.upload.SSHThread;
import com.sitech.util.upload.TelnetThread;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.UdpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
/**
* @author frank zmm@honggroup.com.cn
* @Description: 检查主机,数据库,中间件的连接状态实现类。
* @Package com.sitech.ismp.check.downtime
* @ClassName: com.sitech.ismp.check.downtime.CheckConnectionService
* @date 2017年04月22日 14:36
*/
public class CheckConnectionService {
private static Logger log= Logger.getLogger(CheckConnectionService.class);
private Snmp mSnmp = null;
private CommunityTarget mCommunityTarget = null;
public String getDbConnectionState(ParamterBean bean){
boolean state=contentWithJdbc(bean);
String flag=null;
if(state){
flag="UP";
}else{
flag="DOWN";
}
// addDbConnectionState(bean,flag);
return flag;
}
/**
* 使用snmp协议连接Windows主机。
* @param bean
* @return
*/
private boolean contentWithJdbc(ParamterBean bean){
String type=bean.getType(); // 数据库类型
String className=null;
if("oracle".equalsIgnoreCase(type)){
className="oracle.jdbc.driver.OracleDriver";
}else if("mysql".equalsIgnoreCase(type)){
className="com.mysql.jdbc.Driver";
}else if("sqlServer".equalsIgnoreCase(type)){
className="com.microsoft.jdbc.sqlserver.SQLServerDriver";
}else if("db2".equalsIgnoreCase(type)){
className="com.ibm.db2.jcc.DB2Driver";
}
Connection conn=null;
String dsUser=bean.getUSER_NAME();
String dsPassword=bean.getPASSWORD();
String url=bean.getURL();
try {
Class.forName(className);
} catch (ClassNotFoundException e) {
log.error("没有找到对应的驱动程序!",e);
}
try {
conn= DriverManager.getConnection(url, dsUser, dsPassword);
} catch (SQLException e) {
log.error("根据用户信息,URL获取连接异常!",e);
}
boolean temp=false;
if(null !=conn){
temp=true;
try {
conn.close();
conn=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
return temp;
}
/**
* 使用 SSH 或 Telnet 协议 获取设备的连接结果,能连接返回 UP,否则返回 DOWN.
* @param bean
* @return
*/
public String getConnectionState4Snmp(ParamterBean bean){
boolean state=contentWithSnmp(bean);
String flag=null;
if(state){
flag="UP";
}else{
flag="DOWN";
}
return flag;
}
/**
* 使用snmp协议连接Windows主机。
* 初始化snmp后,获取主机名称,如果能获取到的话说明能连接,否则不能连接。
* @param bean
* @return
*/
private boolean contentWithSnmp(ParamterBean bean){
init(bean);
String nameoid=".1.3.6.1.2.1.1.5.0";
String result = null;
PDU pdu = new PDU();
VariableBinding var = new VariableBinding(new OID(nameoid), new OctetString());
pdu.add(var);
pdu.setType(PDU.GET);
ResponseEvent res = null;
try {
res = mSnmp.send(pdu, mCommunityTarget);
} catch (IOException e) {
log.error("mSnmp.send() has error!");
e.printStackTrace();
}
PDU result_pdu = res.getResponse();
if (result_pdu != null) {
VariableBinding vb = result_pdu.get(0);
result = vb.getVariable().toString();
}
boolean isConnection=false;
if(!StringUtils.isEmpty(result)){
isConnection=true;
}
return isConnection;
}
/**
* 初始化snmp。
* @param bean
*/
private void init(ParamterBean bean){
String ip=bean.getDEVICE_IP();
String communityStr=bean.getCOMMUNITY();
int port=bean.getPROTOCOL_PORT();
String addr = "udp:" + ip + "/" + port;
OctetString community = new OctetString(communityStr);
Address address = GenericAddress.parse(addr);
mCommunityTarget = new CommunityTarget(address, community);
TransportMapping vTransport = null;
try {
vTransport = new DefaultUdpTransportMapping();
} catch (IOException e) {
log.error(" create vTransport has error!",e);
}
mSnmp = new Snmp(vTransport);
try {
vTransport.listen();
} catch (IOException e) {
log.error(" vTransport.listen() has error!",e);
}
mCommunityTarget.setCommunity(community);
try {
mCommunityTarget.setAddress(new UdpAddress(InetAddress.getByName(ip), port));
} catch (UnknownHostException e) {
log.error(" setAddress() has error!",e);
}
mCommunityTarget.setRetries(2);
mCommunityTarget.setTimeout(5000);
mCommunityTarget.setVersion(SnmpConstants.version2c);
}
/**
* 使用 SSH 或 Telnet 协议 获取设备的连接结果,能连接返回 UP,否则返回 DOWN.
* @param bean
* @return
*/
public String getConnectionState4SshOrTelnet(ParamterBean bean){
boolean sshState=contentWithSsh(bean);
String flag=null;
if(sshState){
flag="UP";
}else{
flag="DOWN";
}
return flag;
}
/**
* 进行ssh连接,判断是否可以连接成功。
* windows操作系统使用 TelnetThread类连接。 Windows的客户端需要配置并开启Telnet相关的服务。
* @return
*/
private boolean contentWithSsh(ParamterBean bean){
String protocol=bean.getPROTOCOL();
String ipAddr=bean.getDEVICE_IP();
int protocolPort=bean.getPROTOCOL_PORT();
String userName=bean.getUSER_NAME();
String password=bean.getPASSWORD();
boolean temp=false;
RomoteController tt = null;
log.info("execute contentWithSsh method,params is: ipAddr="+ipAddr+",protocol="+protocol+",protocolPort="+protocolPort+",userName="+userName);
if(loginParamterIsOk(protocol,ipAddr,protocolPort,userName,password)){
try {
if (protocol != null && protocol.equalsIgnoreCase("telnet")) {
tt = new TelnetThread(ipAddr, protocolPort, userName, password);
} else if (protocol != null && protocol.equalsIgnoreCase("ssh")) {
tt = new SSHThread(ipAddr, protocolPort, userName, password);
}else{
log.error("===================== unknown protocol =====================");
}
}catch (Exception e){
log.error(protocol+"connect have exception!");
}
tt.initial();
boolean flag=tt.isAuthorized();
if (flag){ // 认证通过
log.info(ipAddr+" SSH connect,Authorized result is true authorized success!");
temp=true;
}else{
log.info(ipAddr+" SSH connect,Authorized result is false authorized fail!");
}
}
return temp;
}
/**
* 获取ping的结果,UP 或 DOWN。
* 该方法负责一个采集周期内的3次ping操作。
* @return
*/
public String getPingState(ParamterBean bean){
String ipAddr =bean.getDEVICE_IP();
String result=null;
boolean flag=false;
if(!StringUtils.isEmpty(ipAddr)){
int pingErrorCount=0; // ping 不通的次数,ping3次。
int interval=8; // 时间间隔8秒。
boolean temp=false;
for(int i=0;i<3;i++){
temp=executeCommand(ipAddr); // ping不通返回false。
log.info("["+ipAddr+"]ping result is ["+temp+"],(true:can connect;false:can't connect)");
if(!temp){
pingErrorCount++;
}
try {
Thread.sleep(interval*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(pingErrorCount == 3){
log.info("["+ipAddr+"] can't connect 3 times.");
}else{
flag=true;
log.info("["+ipAddr+"] can connect.");
}
if(flag){
result="UP";
}else{
result="DOWN";
}
}
return result;
}
/**
* 返回ping后的结果。
* @param ipAddr ip 地址。
* @return
*/
private boolean executeCommand(String ipAddr){
boolean flag=false;
if(!StringUtils.isEmpty(ipAddr)){
String command = "/bin/ping -c 3 -w 3 " + ipAddr;;
// 执行command 命令。
String line = null;
StringBuilder sb = new StringBuilder();
Runtime runtime = Runtime.getRuntime();
Process process = null;
try {
process = runtime.exec(command);
} catch (IOException e) {
log.error("execute command ["+command+"] has some error!");
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
log.error("======== bufferedReader.readLine() has some error!");
}
String pingResult=sb.toString();
/**
* 当执行结果出现下面字符说明已经执行完成。
* ping 通的时候 结果包含【min/avg/max/mdev】
* ping 不通的时候 结果包含【100% packet loss】
*/
if(pingResult.contains("100% packet loss") || (pingResult.contains("min/avg/max/mdev"))){
process.destroy();
log.info("execute command ["+command+"] finish!");
}
String os = System.getProperty("os.name").toLowerCase();
log.info("------------ operator system is :" + os);
// 解析command命令结果,包含【100% packet loss】 意味着ping不通,返回 false。
if(os.indexOf("linux") >= 0){
if (!StringUtils.isEmpty(pingResult)) {
if(!pingResult.contains("100% packet loss")){
flag = true;
}
}
}
}
return flag;
}
/**
* 判断所有的参数是否为空。
* @param protocol 协议类型
* @param ipAddr IP地址
* @param protocolPort 协议端口
* @param userName 用户名
* @param password 密码
* @return
*/
private boolean loginParamterIsOk(String protocol,String ipAddr,int protocolPort,String userName,String password){
boolean flag=true;
if(StringUtils.isEmpty(protocol))
flag=false;
if(StringUtils.isEmpty(ipAddr))
flag=false;
if(StringUtils.isEmpty(protocolPort+""))
flag=false;
if(StringUtils.isEmpty(userName))
flag=false;
if(StringUtils.isEmpty(password))
flag=false;
return flag;
}
/**
* 插入ping结果。
* @param bean
*/
public void addPingConnectionState(ConnectionStateBean bean){
CheckConnectionDao dao=new CheckConnectionDao();
dao.addPingConnectionState(bean);
}
/**
* 将ParamterBean与state设置到ConnectionStateBean的属性上。
* @param bean
* @param state
* @return
*/
public ConnectionStateBean getBean(ParamterBean bean,String state){
ConnectionStateBean stateBean=new ConnectionStateBean();
stateBean.setDEVICE_ID(UUID.randomUUID().toString());
stateBean.setDEVICE_IP(bean.getDEVICE_IP());
stateBean.setCREATE_DATE(new Date().getTime());
return stateBean;
}
/**
* 根据IP与时间获取该时间段内ping不通的次数。
* 按照降序查询头3条,如果3条数据状态都为down,则视为宕机。
* @param ip
* @return
*/
public List<ConnectionStateBean> getStatByParam(String ip){
CheckConnectionDao dao=new CheckConnectionDao();
HashMap<String, Object> map=new HashMap<String, Object>();
map.put("DEVICE_IP",ip);
return dao.getStatByParam(map);
}
public static void main(String [] args){
long beforeTime = 15*60*1000+500;//15.5分钟前
long afterTime = 30*1000;//半分钟后
Date now = new Date();
long nn=now.getTime();
long before = nn - beforeTime;
long after = nn + afterTime;
System.out.println(nn);
System.out.println(after);
System.out.println(before);
}
}
... ...
package com.sitech.ismp.check.downtime;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author frank zmm@honggroup.com.cn
* @Description: 检查主机,数据库,中间件的连接状态。
* 其中主机包含 Linux/unix ping ssh 2种状态;Windows ping snmp 2种状态;
* 数据库 ping jdbc 2种状态; 中间件(Tomcat) ping jmx状态
*
* 需要区分 Windows与其他系统。在方法参数上,将map转换成CheckConnectionBean再使用。
* @Package com.sitech.ismp.check.downtime
* @ClassName: com.sitech.ismp.check.downtime.CheckConnectionState
* @date 2017年04月22日 14:17
*/
public class CheckConnectionState {
private static Logger log= Logger.getLogger(CheckConnectionState.class);
CheckConnectionService service=new CheckConnectionService();
//******************************* 获取主机相关状态代码 *******************************//
//******* 主机分为Linux/unix与Windows两大类,连接的时候前者使用ssh后者使用snmp ************//
//******************************* 获取主机相关状态代码 *******************************//
/**
* 获取设备的ping结果,能ping通返回 UP,否则返回 DOWN.
* 需要连续ping3次,将ping的结果插入到 TB_CONNECTION_STATE.
* @param bean
* @return
*/
public String getPingState(ParamterBean bean){
String state=service.getPingState(bean);
String type=bean.getType();
if("windows".equals(type) || "linux".equals(type)|| "unix".equals(type)){
String ip=bean.getDEVICE_IP();
if(!StringUtils.isEmpty(ip)){
ConnectionStateBean stateBean=new ConnectionStateBean();
stateBean.setDEVICE_STATE(state); // 设备状态
stateBean.setDEVICE_ID(UUID.randomUUID().toString());
stateBean.setDEVICE_IP(bean.getDEVICE_IP());
stateBean.setCREATE_DATE(new Date().getTime());
service.addPingConnectionState(stateBean);
}
}
return state;
}
/**
* 根据IP获取ping不通的次数。只取集合中的前3条数据。当都为down的时候表明已经宕机,少于3次不算宕机。
* @param ip
* @return
*/
public String getPingErrorState(String ip){
List<ConnectionStateBean> list=service.getStatByParam(ip);
int temp=0;
String state=null;
ConnectionStateBean bean=null;
if(null !=list && list.size()>0){
for(int i=0;i<3;i++){
bean=list.get(i);
state=bean.getDEVICE_STATE();
if("DOWN".equals(state)){
temp++;
}
}
}
String stat="UP";
if(temp==3){
stat="DOWN";
}
return stat;
}
/**
* 使用 SSH 或 Telnet 协议 获取设备的连接结果,能连接返回 UP,否则返回 DOWN.
* @param bean
*/
public String getConnectionState4SshOrTelnet(ParamterBean bean){
String state=service.getConnectionState4SshOrTelnet(bean);
return state;
}
/**
* 使用 SNMP 协议 获取设备的连接结果,能连接返回 UP,否则返回 DOWN.
* @param bean
*/
public String getConnectionState4Snmp(ParamterBean bean){
String state=service.getConnectionState4Snmp(bean);
log.info("***** getConnectionState4Snmp ***state= "+state+"**************");
return state;
}
/**
* Oracle数据库连接状态
* @param bean
*/
public String getOracleConnectionState(ParamterBean bean){
bean.setType("oracle");
String state=service.getDbConnectionState(bean);
return state;
}
public static void main(String [] args){
CheckConnectionState ss=new CheckConnectionState();
ParamterBean bean1=new ParamterBean();
bean1.setUSER_NAME("Administrator");
bean1.setPASSWORD("0213");
bean1.setPROTOCOL_PORT(161);
bean1.setDEVICE_IP("192.168.1.141");
ss.getConnectionState4Snmp(bean1);
ParamterBean bean=new ParamterBean();
bean.setPASSWORD("tiger");
bean.setUSER_NAME("scott");
bean.setURL("jdbc:oracle:thin:@192.168.1.130:1521:ORCL");
System.out.println(ss.getOracleConnectionState(bean));
}
/**
* Mysql 数据库连接状态
* @param bean
*/
public String getMysqlConnectionState(ParamterBean bean){
bean.setType("Mysql");
String state=service.getDbConnectionState(bean);
return state;
}
/**
* SqlServer 数据库连接状态
* @param bean
*/
public void getSqlServerConnectionState(ParamterBean bean){
bean.setType("SqlServer");
String state=service.getDbConnectionState(bean);
}
/**
* Db2 数据库连接状态
* @param bean
*/
public void getDb2ConnectionState(ParamterBean bean){
bean.setType("Db2");
String state=service.getDbConnectionState(bean);
}
}
... ...
package com.sitech.ismp.check.downtime;
/**
* @author frank zmm@honggroup.com.cn
* @Description: 存放检测主机连接的各种参数。
* @Package com.sitech.ismp.check.downtime
* @ClassName: com.sitech.ismp.check.downtime.ConnectionStateBean
* @date 2017年04月22日 14:34
*/
public class ConnectionStateBean {
// ID
private String DEVICE_ID;
// 设备IP地址
private String DEVICE_IP;
// 设备状态
private String DEVICE_STATE;
// 创建时间
private Long CREATE_DATE;
public String getDEVICE_ID() {
return DEVICE_ID;
}
public void setDEVICE_ID(String DEVICE_ID) {
this.DEVICE_ID = DEVICE_ID;
}
public String getDEVICE_IP() {
return DEVICE_IP;
}
public void setDEVICE_IP(String DEVICE_IP) {
this.DEVICE_IP = DEVICE_IP;
}
public String getDEVICE_STATE() {
return DEVICE_STATE;
}
public void setDEVICE_STATE(String DEVICE_STATE) {
this.DEVICE_STATE = DEVICE_STATE;
}
public Long getCREATE_DATE() {
return CREATE_DATE;
}
public void setCREATE_DATE(Long CREATE_DATE) {
this.CREATE_DATE = CREATE_DATE;
}
@Override
public String toString() {
return "ConnectionStateBean{" +
"DEVICE_ID='" + DEVICE_ID + '\'' +
", DEVICE_IP='" + DEVICE_IP + '\'' +
", DEVICE_STATE='" + DEVICE_STATE + '\'' +
", CREATE_DATE=" + CREATE_DATE +
'}';
}
}
... ...
package com.sitech.ismp.check.downtime;
/**
* @author frank zmm@honggroup.com.cn
* @Description: 存放检测主机连接的各种参数。
* @Package com.sitech.ismp.check.downtime
* @ClassName: com.sitech.ismp.check.downtime.ParamterBean
* @date 2017年04月22日 15:08
*/
public class ParamterBean {
// 设备IP地址
private String DEVICE_IP;
// 连接协议(ssh/telnet)
private String PROTOCOL;
// 协议端口
private int PROTOCOL_PORT;
// 用户名(分主机与数据库)
private String USER_NAME;
// 密码(分主机与数据库)
private String PASSWORD;
private String URL;
private String COMMUNITY;
private String Type;
public ParamterBean() {
}
public ParamterBean(String DEVICE_IP) {
this.DEVICE_IP = DEVICE_IP;
}
public String getDEVICE_IP() {
return DEVICE_IP;
}
public void setDEVICE_IP(String DEVICE_IP) {
this.DEVICE_IP = DEVICE_IP;
}
public String getPROTOCOL() {
return PROTOCOL;
}
public void setPROTOCOL(String PROTOCOL) {
this.PROTOCOL = PROTOCOL;
}
public int getPROTOCOL_PORT() {
return PROTOCOL_PORT;
}
public void setPROTOCOL_PORT(int PROTOCOL_PORT) {
this.PROTOCOL_PORT = PROTOCOL_PORT;
}
public String getUSER_NAME() {
return USER_NAME;
}
public void setUSER_NAME(String USER_NAME) {
this.USER_NAME = USER_NAME;
}
public String getPASSWORD() {
return PASSWORD;
}
public void setPASSWORD(String PASSWORD) {
this.PASSWORD = PASSWORD;
}
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
public String getCOMMUNITY() {
return COMMUNITY;
}
public void setCOMMUNITY(String COMMUNITY) {
this.COMMUNITY = COMMUNITY;
}
@Override
public String toString() {
return "ParamterBean{" +
"DEVICE_IP='" + DEVICE_IP + '\'' +
", PROTOCOL='" + PROTOCOL + '\'' +
", COMMUNITY='" + COMMUNITY + '\'' +
", PROTOCOL_PORT=" + PROTOCOL_PORT +
", USER_NAME='" + USER_NAME + '\'' +
", PASSWORD='" + PASSWORD + '\'' +
'}';
}
}
... ...
... ... @@ -29,6 +29,11 @@ public class CollMySQL implements CollMySQLMBean {
}
}
/**
* 获取数据库jdbc的连接状态。
* @param params
* @return
*/
@Override
public Vector<TblATO_KPIDETAIL> getStatus(HashMap<String, String> params) {
try {
... ... @@ -40,6 +45,22 @@ public class CollMySQL implements CollMySQLMBean {
}
}
/**
* 获取数据库ping状态。
* @param params
* @return
*/
@Override
public Vector<TblATO_KPIDETAIL> getPingStatus(HashMap<String, String> params) {
try {
CollMySQLBySql collector = new CollMySQLBySql();
return collector.getPingStatus(params);
} catch (Exception e) {
logger.error("Exception while getPingStatus", e);
return new Vector<TblATO_KPIDETAIL>();
}
}
@Override
public Vector<TblATO_KPIDETAIL> getPerformance(HashMap<String, String> params) {
try {
... ...
package com.sitech.ismp.coll;
import com.sitech.ismp.check.downtime.CheckConnectionState;
import com.sitech.ismp.check.downtime.ParamterBean;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.util.DES3;
import com.sitech.util.Formater;
import com.sitech.util.JSONUtil;
import org.apache.log4j.Logger;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;
... ... @@ -19,6 +22,7 @@ import java.util.Vector;
*/
public class CollMySQLBySql {
private Logger logger = Logger.getLogger("COLL");
private static Logger log = Logger.getLogger(CollMySQLBySql.class);
private String KBP_CLASS = "10-11-35";
private String DB_TYPE = "MySQL";
... ... @@ -27,22 +31,33 @@ public class CollMySQLBySql {
private String dburl = null;
private String dbuser = null;
private String passwd = null;
private String ip = null; // 2017-04-24 frank 添加,用于获取数据库所在主机的ping状态
private String device_id = null;
private String NEATENSID = null;
private boolean getParams(HashMap<String, String> params) {
try {
dburl = params.get("DB_URL");
int start=dburl.indexOf("/");
int end=dburl.lastIndexOf(":");
ip=dburl.substring(start+2,end);
dbuser = params.get("USERNAME");
passwd = DES3.decrypt(params.get("PASSWORD"));
device_id = (String) params.get("DEVICE_ID");
NEATENSID = Formater.neatenunitid(this.device_id);
log.info("*****ip ="+ip+"**dbuser="+dbuser+"*************************");
} catch (Exception e) {
throw new RuntimeException("Exception while init params:" + JSONUtil.toJSON(params), e);
}
return true;
}
/**
* 获取数据库基本信息,frank 2017-04-24 修改,添加设备状态(UP/DOWN)即主机ping的结果。
* @param params
* @return
* @throws Exception
*/
public Vector<TblATO_KPIDETAIL> getSystem(HashMap<String, String> params) throws Exception {
getParams(params);
SQLTarget colldb = new SQLTarget();
... ... @@ -53,6 +68,10 @@ public class CollMySQLBySql {
return sets;
}
/**
* 获取数据库基本信息
* @param colldb
*/
private void getSystem(SQLTarget colldb) {
String UNIT_ID = KBP_CLASS + "-10" + ":" + NEATENSID + "-SYS";
// CM-00-03-001-02
... ... @@ -228,21 +247,65 @@ public class CollMySQLBySql {
return sets;
}
/**
* 获取数据库ping状态。
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getPingStatus(HashMap<String,String> params) {
String url = params.get("DB_URL");
String deviceId = params.get("DEVICE_ID");
log.info(" ***//////url="+url+"///////////// deviceId="+deviceId+"//////////////////");
int start=url.indexOf("/");
int end=url.lastIndexOf(":");
String ipAddr=url.substring(start+2,end);
log.info(" ***/////////////////// ipAddr="+ipAddr+"//////////////////");
String kpiId="FM-00-10-001-999"; // mysql 主机连接状态
CheckConnectionState server=new CheckConnectionState();
String unitId = KBP_CLASS + "-10" + ":" + deviceId + "-SYS";
ParamterBean bean=new ParamterBean();
bean.setType("mysql");
bean.setDEVICE_IP(ipAddr);
String stat=server.getPingState(bean);
log.info(" **** getPingStatus ****UNIT_ID ="+unitId+"****stat="+stat+"**");
TblATO_KPIDETAIL kpidetail=new TblATO_KPIDETAIL();
try {
kpidetail.setUNIT_ID(unitId);
kpidetail.setKPI_ID(kpiId);
kpidetail.setCLL_TIME(new Date());
kpidetail.setKPI_VALUE(stat);
} catch (ParseException e) {
log.error(" ****** kpidetail.setUNIT_ID(unitId) has error!");
e.printStackTrace();
}
Vector<TblATO_KPIDETAIL> vector=new Vector<TblATO_KPIDETAIL>();
vector.add(kpidetail);
return vector;
}
/**
* 获取数据库的连接(jdbc)状态
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getStatus(HashMap<String,String> params) {
getParams(params);
SQLTarget colldb = new SQLTarget();
colldb.initWithClassname(DB_TYPE, CLASSNAME, dburl, dbuser, passwd);
String UNIT_ID = KBP_CLASS + "-10" + ":" + NEATENSID + "-SYS";
// 修改状态的值 UP:连接正常/DOWN:连接异常
if (colldb.getState()) {
colldb.addKPI(UNIT_ID, "FM-00-03-001-01", "active");
colldb.addKPI(UNIT_ID, "FM-00-03-001-01", "UP");
} else {
colldb.addKPI(UNIT_ID, "FM-00-03-001-01", "disconnected");
colldb.addKPI(UNIT_ID, "FM-00-03-001-01", "DOWN");
logger.error("----mysql--- " + device_id + "--state--err----");
}
Vector sets = colldb.getKPISet();
colldb.release();
return sets;
}
... ...
... ... @@ -16,8 +16,19 @@ public abstract interface CollMySQLMBean {
public Vector<TblATO_KPIDETAIL> getSystem(HashMap<String, String> params);
/**
* 获取数据库jdbc的连接状态。
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getStatus(HashMap<String, String> params);
/**
* 获取数据库所在主机的ping状态
* @param params
*/
public Vector<TblATO_KPIDETAIL> getPingStatus(HashMap<String, String> params);
public Vector<TblATO_KPIDETAIL> getPerformance(HashMap<String, String> params);
public Vector<TblATO_KPIDETAIL> getInnodb(HashMap<String, String> params);
... ...
package com.sitech.ismp.coll;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.util.DES3;
import com.sitech.util.JSONUtil;
import org.apache.log4j.Logger;
... ... @@ -96,6 +95,22 @@ public class CollOracle implements CollOracleMBean {
}
}
/**
* 获取数据库所在主机的ping状态
* @param params
* @return
*/
@Override
public Vector<TblATO_KPIDETAIL> getPingStatus(HashMap<String, String> params) {
try {
CollOracleBySql collector = new CollOracleBySql();
return collector.getPingStatus(params);
} catch (Exception e) {
logger.error("Exception while getPingStatus", e);
return new Vector<TblATO_KPIDETAIL>();
}
}
@Override
public Vector<TblATO_KPIDETAIL> getSpecialTable(
HashMap<String, String> params) {
... ... @@ -174,93 +189,4 @@ public class CollOracle implements CollOracleMBean {
return scanner.nextLine();
}
public static void main(String[] args) {
System.out.println("***************ORACLE Collect Test Begin*********************");
/*String ipAddr = "172.21.0.69";
String username = "ssdbomc";
String password = "ssdbomc";
String port = "1525";
String sid = "e3cloud";
String deviceId = "bnms";
String methodStr = "9";
String methodStr = "6";*/
String ipAddr = read("IP_ADDR(remote oracle service ip):\n");
String username = read("USERNAME:\n");
String password = read("PASSWORD:\n");
String port = read("PORT:\n");
String sid = read("SID:\n");
String deviceId = read("DEVICE_ID\n");
String methodStr = read("METHOD(0:getAll, 1:getExtendKPI, 2:getStatus, 3:getSystem, 4:getTableSpaces, 5:getTableSpacesSpecial, 6:getTotalData):\n");
// String methodStr = read("METHOD(0:getAll, 1:getExtendKPI, 2:getStatus, 3:getSystem,
// 4:getTableSpaces, 5:getTableSpacesSpecial, 6:getTotalData, 7:getHeadroom, 8:getAsmDiskGroup):\n");
HashMap params = new HashMap();
params.put("IP_ADDR", ipAddr);
params.put("USERNAME", username);
params.put("PASSWORD", DES3.encrypt(password));
params.put("PORT", port);
params.put("DEVICE_ID", deviceId);
params.put("SID", sid);
CollOracle coll = new CollOracle();
Vector lst = new Vector<TblATO_KPIDETAIL>();
int method = Integer.parseInt(methodStr);
switch (method) {
case 0:
lst.addAll(coll.getExtendKPI(params));
lst.addAll(coll.getStatus(params));
lst.addAll(coll.getSystem(params));
lst.addAll(coll.getTableSpaces(params));
lst.addAll(coll.getTableSpacesSpecial(params));
lst.addAll(coll.getTotalData(params));
lst.addAll(coll.getHeadroom(params));
lst.addAll(coll.getAsmDiskGroup(params));
lst.addAll(coll.getSessionWait(params));
break;
case 1:
lst.addAll(coll.getExtendKPI(params));
break;
case 2:
lst.addAll(coll.getStatus(params));
break;
case 3:
lst.addAll(coll.getSystem(params));
break;
case 4:
lst.addAll(coll.getTableSpaces(params));
break;
case 5:
lst.addAll(coll.getTableSpacesSpecial(params));
break;
case 6:
lst.addAll(coll.getTotalData(params));
break;
case 7:
lst.addAll(coll.getHeadroom(params));
break;
case 8:
lst.addAll(coll.getAsmDiskGroup(params));
break;
case 9:
lst.addAll(coll.getSessionWait(params));
break;
default:
break;
}
System.out.println("***************ORACLE Collect Test End*********************");
System.out.println("lst.size() is " + lst.size());
for (int i = 0; i < lst.size(); i++) {
TblATO_KPIDETAIL record = (TblATO_KPIDETAIL) lst.get(i);
// System.out.println(kpidetail.UNIT_ID + "|" + kpidetail.KPI_ID + "|" + kpidetail.CLL_TIME + "|" + kpidetail.KPI_VALUE);
String insSql = "INSERT INTO TB_ATO_KPIDETAIL (KPI_ID, UNIT_ID, CLL_TIME, KPI_VALUE, EXT_INFO, DB_TIME, EXT_UNIT_ID, INTERVAL) " +
"VALUES ('#KPI_ID#', '#UNIT_ID#', sysdate, '#KPI_VALUE#', 'null', sysdate, '10-11-30:bnms', #INTERVAL#);";
insSql = insSql.replace("#KPI_ID#", record.KPI_ID);
insSql = insSql.replace("#UNIT_ID#", record.UNIT_ID);
insSql = insSql.replace("#KPI_VALUE#", record.KPI_VALUE);
insSql = insSql.replace("#INTERVAL#", record.INTERVAL);
System.out.println(insSql);
}
}
}
\ No newline at end of file
... ...
package com.sitech.ismp.coll;
import java.util.*;
import com.sitech.ismp.check.downtime.CheckConnectionState;
import com.sitech.ismp.check.downtime.ParamterBean;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import org.apache.log4j.Logger;
import com.sitech.util.DES3;
import com.sitech.util.Formater;
import com.sitech.util.JSONUtil;
import com.sitech.util.upload.RomoteController;
import com.sitech.util.upload.SSHThread;
import com.sitech.util.upload.TelnetThread;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
public class CollOracleBySql {
... ... @@ -27,6 +30,7 @@ public class CollOracleBySql {
RomoteController tt = null;
private Logger logger = Logger.getLogger("COLL");
private static Logger log = Logger.getLogger(CollOracleBySql.class);
// public void init(HashMap params) {
// String hostip = (String) params.get("IP_ADDR");
... ... @@ -102,7 +106,7 @@ public class CollOracleBySql {
return result;
}
public java.util.Vector getSystem(String IP_ADDR, String USERNAME,
public Vector getSystem(String IP_ADDR, String USERNAME,
String PASSWORD, String KBP_ID, String SID) throws Exception {
this.KBP_ID = KBP_ID;
this.NEATENSID = Formater.neatenunitid(this.device_id);
... ... @@ -110,14 +114,9 @@ public class CollOracleBySql {
collectiondbbase.init(IP_ADDR, PORT, SID, USERNAME, PASSWORD);
getSystem(collectiondbbase);
collectiondbbase.addKPI(KBP_ID + "-10" + ":" + NEATENSID + "-SYS",
"CM-00-03-001-50", IP_ADDR);
collectiondbbase.addKPI(KBP_ID + "-10" + ":" + NEATENSID + "-SYS","CM-00-03-001-50", IP_ADDR);
Vector aa = collectiondbbase.getKPISet();
// System.out.println(aa.size());
collectiondbbase.release();
// collectiondbbase.displayKPI();
return aa;
}
... ... @@ -198,8 +197,7 @@ public class CollOracleBySql {
return getUndoTableSpaces(hostip, user, passwd, kbp_id, SID);
}
public java.util.Vector getSystem(java.util.HashMap params)
throws Exception {
public java.util.Vector getSystem(java.util.HashMap params)throws Exception {
getParams(params);
return getSystem(hostip, user, passwd, kbp_id, SID);
}
... ... @@ -327,29 +325,50 @@ public class CollOracleBySql {
return getStatus(hostip, user, passwd, kbp_id, SID);
}
/**
* 获取数据库所在主机的ping状态
* @param params
* @return
*/
public Vector getPingStatus(HashMap params)throws Exception {
getParams(params);
CheckConnectionState server=new CheckConnectionState();
String KBP_ID = "10-11-30-10:" + this.NEATENSID + "-SYS";
SQLTarget collectiondbbase = new SQLTarget();
ParamterBean bean=new ParamterBean();
bean.setType("oracle");
bean.setDEVICE_IP(hostip);
String stat=server.getPingState(bean);
collectiondbbase.addKPI(KBP_ID, "FM-00-11-001-999", stat);
log.info(" ************************* getPingStatus ****UNIT_ID ="+KBP_ID+"****stat="+stat+"**");
return collectiondbbase.getKPISet();
}
/**
* 数据库jdbc连接状态
* @param IP_ADDR
* @param USERNAME
* @param PASSWORD
* @param KBP_ID
* @param SID
* @return
* @throws Exception
*/
private java.util.Vector getStatus(String IP_ADDR, String USERNAME,
String PASSWORD, String KBP_ID, String SID) throws Exception {
this.KBP_ID = KBP_ID;
//this.NEATENSID = Formater.neatenunitid(SID);
this.NEATENSID = Formater.neatenunitid(this.device_id);
System.out.println("--采集数据库状态--");
KBP_ID = KBP_ID + "-10:" + this.NEATENSID + "-SYS";
SQLTarget collectiondbbase = new SQLTarget();
collectiondbbase.init(IP_ADDR, PORT, SID, USERNAME, PASSWORD);
if (collectiondbbase.getState()) {
logger.info("----db----" + SID + "--state--connected----");
collectiondbbase.addKPI(KBP_ID, "FM-00-03-001-04", "connected");
String verionInfo = collectiondbbase.getSQLKPIInfo("select status from v$instance").toLowerCase();
collectiondbbase.addKPI(KBP_ID, "FM-00-03-001-01", verionInfo);
// 获取数据库连接状态 UP:连接正常/DOWN:连接异常
if (collectiondbbase.getState()){
collectiondbbase.addKPI(KBP_ID, "FM-00-03-001-01", "UP");
} else {
logger.error("----db----" + SID + "--state--disconnected----");
collectiondbbase.addKPI(KBP_ID, "FM-00-03-001-04", "disconnected");
collectiondbbase.addKPI(KBP_ID, "FM-00-03-001-01", "Unknown");
collectiondbbase.addKPI(KBP_ID, "FM-00-03-001-01", "DOWN");
}
Vector kpi_value = collectiondbbase.getKPISet();
collectiondbbase.release();
return kpi_value;
... ... @@ -394,11 +413,13 @@ public class CollOracleBySql {
//add start 活动会话数量
String sqlActiveSession = "select STATUS,count(*) from v$session where status='ACTIVE' group by STATUS";
Vector activeSessionDetail = collectiondbbase.getSQLKPIResult(sqlActiveSession);
/* PM-00-03-009-04 定义的为 JDBC可链接性,这里不统一,注释掉。
int activeSessionNum = 0;
Vector activeSessionDetailVector = (Vector) activeSessionDetail.elementAt(0);
String num = (String) activeSessionDetailVector.get(1);
activeSessionNum = Integer.parseInt(num);
collectiondbbase.addKPI(KBP_ID, "PM-00-03-009-04", String.valueOf(activeSessionNum));
collectiondbbase.addKPI(KBP_ID, "PM-00-03-009-04", String.valueOf(activeSessionNum));*/
//add end
int sessionNum = 0;
for (int i = 0; i < sessionDetail.size(); i++) {
... ... @@ -683,6 +704,7 @@ public class CollOracleBySql {
private void getSystem(SQLTarget collectiondbbase) {
String KBP_ID = this.KBP_ID + "-10" + ":" + NEATENSID + "-SYS";
collectiondbbase.addKPI(KBP_ID, "CM-00-03-001-01", collectiondbbase
.getSQLKPIInfo("select NAME from v$database"));
collectiondbbase
... ... @@ -741,12 +763,17 @@ public class CollOracleBySql {
collectiondbbase.addKPI(KBP_ID, "CM-00-03-001-05", collectiondbbase
.getSQLKPIInfo("select LOG_MODE from v$database"));
String logDir = collectiondbbase
/*String logDir = collectiondbbase
.getSQLKPISetInfo("select value from v$parameter where name = 'log_archive_dest'");
logDir = logDir == null ? "" : logDir;
logDir = logDir.replaceAll("\r", " ").replaceAll("\n", " ").replaceAll("\t", " ");
collectiondbbase.addKPI(KBP_ID, "CM-00-03-001-06", logDir);*/
collectiondbbase.addKPI(KBP_ID, "CM-00-03-001-06", logDir);
collectiondbbase
.addKPI(KBP_ID,
"CM-00-03-001-06",
collectiondbbase
.getSQLKPIInfo("select value from v$parameter where name = 'db_recovery_file_dest'"));
collectiondbbase
.addKPI(
... ...
package com.sitech.ismp.coll;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import java.util.HashMap;
import java.util.Vector;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
public abstract interface CollOracleMBean {
public Vector<TblATO_KPIDETAIL> getDataFile(HashMap<String,String> params);
... ... @@ -23,6 +23,11 @@ public abstract interface CollOracleMBean {
public Vector<TblATO_KPIDETAIL> getExtendKPI(HashMap<String,String> params);
/**
* 数据库jdbc连接状态
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getStatus(HashMap<String,String> params);
public Vector<TblATO_KPIDETAIL> getTotalData(HashMap<String,String> params);
... ... @@ -35,4 +40,11 @@ public abstract interface CollOracleMBean {
public Vector<TblATO_KPIDETAIL> getSessionWait(HashMap<String, String> params);
/**
* 获取数据库所在主机的ping状态
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getPingStatus(HashMap<String, String> params);
}
... ...
package com.sitech.ismp.coll;
import org.apache.log4j.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
... ... @@ -10,8 +12,6 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.apache.log4j.Logger;
public class SQLTarget extends CollBase {
Logger logger = Logger.getLogger(SQLTarget.class);
String ObjectIP = null;
... ... @@ -189,19 +189,31 @@ public class SQLTarget extends CollBase {
Vector recordSet = new Vector();
PreparedStatement pstmt = null;
ResultSet result = null;
try {
if (!getState()) {
return recordSet;
}
if (!getState()) {
return recordSet;
}
try {
pstmt = dbConnection.prepareStatement(sql);
boolean hasResult = pstmt.execute();
} catch (SQLException e) {
throw new RuntimeException("Exception while exec sql :" + sql, e);
}
boolean hasResult = false;
try {
hasResult = pstmt.execute();
} catch (SQLException e) {
logger.error("pstmt.execute() has error!",e);
e.printStackTrace();
}
try {
if (hasResult) {
result = pstmt.getResultSet();
ResultSetMetaData rsmd = result.getMetaData();
int iColumnCount = rsmd.getColumnCount();
while (result.next()) {
java.util.Vector vTemp = new Vector();
Vector vTemp = new Vector();
for (int i = 0; i < iColumnCount; i++) {
Object oTemp = result.getObject(i + 1);
String sTemp = oTemp == null ? "" : oTemp.toString();
... ... @@ -212,14 +224,9 @@ public class SQLTarget extends CollBase {
result.close();
}
pstmt.close();
// if (!"MySQL".equals(DBType)) {
// dbConnection.commit();
// }
} catch (Exception e) {
throw new RuntimeException("Exception while exec sql :" + sql, e);
} finally {
// releaseResources();
try {
if(pstmt!=null){
pstmt.close();
... ... @@ -239,11 +246,11 @@ public class SQLTarget extends CollBase {
getConnection();
try {
if (!state) {
java.lang.Thread.sleep(5000);// 间隔5s重试第二次连接
Thread.sleep(5000);// 间隔5s重试第二次连接
System.err.println("--second--conn error----");
getConnection();
if (!state) {
java.lang.Thread.sleep(5000);// 再间隔5s重试第三次连接
Thread.sleep(5000);// 再间隔5s重试第三次连接
System.err.println("--third--conn error----");
getConnection();
}
... ... @@ -326,8 +333,11 @@ public class SQLTarget extends CollBase {
return kpiinfo;
}
/**
* 释放数据库连接
*/
public void release() {
// releaseResources();
releaseResources();
}
}
... ...
package com.sitech.ismp.coll.centercoll;
import com.sitech.ismp.check.downtime.CheckConnectionState;
import com.sitech.ismp.check.downtime.ParamterBean;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.util.DES3;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Vector;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.util.DES3;
public class CollLinuxHost implements CollLinuxHostMBean {
private static Logger log= Logger.getLogger(CollLinuxHost.class);
CheckConnectionState server = null;
String kbpClass="10-10-24-10"; // linux 主机的标识
public CollLinuxHost() {
log.info("create CollLinuxHost ");
server = new CheckConnectionState();
}
public Vector collLinux(HashMap params) {
CollLinuxWithCMD cmd = new CollLinuxWithCMD();
... ... @@ -85,9 +100,94 @@ public class CollLinuxHost implements CollLinuxHostMBean {
CollLinuxWithCMD cmd = new CollLinuxWithCMD();
return cmd.getSyslogBylogPathUseGrep(params);
}
/**
* 获取linux集中式采集的 ping 连接状态
* @param params
* @return
*/
public Vector getPing(HashMap params) {
CollLinuxWithCMD cmd = new CollLinuxWithCMD();
return cmd.getPing(params);
Vector<TblATO_KPIDETAIL> v=new Vector<TblATO_KPIDETAIL>();
String ip=params.get("IP_ADDR")+"";
if(!StringUtils.isEmpty(ip)){
String connectStatCode="FM-00-10-001-999"; // linux 主机连接状态
String hostName=params.get("HOSTNAME")+""; // 资源标识
String unitId = kbpClass+":" + hostName + "-total";
ParamterBean bean =new ParamterBean();
bean.setDEVICE_IP(ip);
bean.setType("linux");
log.info("*** execute linux getPing ** ip=["+ip+"]** unitId=["+unitId+"]*********");
/**
* getPingState 方法执行后会将状态插入到表中,然后取当前时间
* 根基IP查询失败的次数,如果失败次数为3次,则确定为宕机,发送告警。
*/
CheckConnectionState server=new CheckConnectionState();
server.getPingState(bean);
// 根据IP获取ping的错误次数。如果是 DOWN 的话,发送告警信息。
String state=server.getPingErrorState(ip);
TblATO_KPIDETAIL kpidetail= new TblATO_KPIDETAIL();
log.info("***** unitId**"+unitId+"** state **"+state+"*******");
try {
kpidetail.setKPI_ID(connectStatCode);
kpidetail.setUNIT_ID(unitId);
kpidetail.setKPI_VALUE(state);
kpidetail.setCLL_TIME(new Date());
} catch (ParseException e) {
e.printStackTrace();
}
v.add(kpidetail);
}
return v;
}
/**
* 获取linux集中式采集的ssh连接状态
* @param params
* @return
*/
@Override
public Vector getSSH(HashMap params) {
Vector<TblATO_KPIDETAIL> v=new Vector<TblATO_KPIDETAIL>();
String ip=params.get("IP_ADDR")+"";
if(!StringUtils.isEmpty(ip)){
String loginStatCode="FM-00-10-001-998"; // linux 主机登录状态
ParamterBean bean =new ParamterBean();
String tempPort=params.get("PROTOCOL_PORT")+"";
int port=0;
if(!StringUtils.isEmpty(tempPort)){
port=Integer.parseInt(tempPort);
}
String hostName=params.get("HOSTNAME")+"";
String username=params.get("USERNAME")+"";
String password=params.get("PASSWORD")+"";
password=DES3.decrypt(password);
String unitId = kbpClass+":" + hostName + "-total";
log.info("*** execute linux getPing ** ip=["+ip+"]** unitId=["+unitId+"]**port="+port+"***hostName="+hostName+"****");
bean.setDEVICE_IP(ip);
bean.setPROTOCOL_PORT(port);
bean.setUSER_NAME(username);
bean.setPASSWORD(password);
String state=server.getConnectionState4SshOrTelnet(bean);
TblATO_KPIDETAIL kpidetail=new TblATO_KPIDETAIL();
try {
kpidetail.setKPI_ID(loginStatCode);
kpidetail.setUNIT_ID(unitId);
kpidetail.setKPI_VALUE(state);
kpidetail.setCLL_TIME(new Date());
} catch (ParseException e) {
e.printStackTrace();
}
v.add(kpidetail);
}
return v;
}
public Vector getDemsg(HashMap params) {
... ... @@ -100,6 +200,8 @@ public class CollLinuxHost implements CollLinuxHostMBean {
return cmd.getNet(params);
}
public static void main(String[] args) {
System.out
.println("***************Linux Center Collect Test Begin*********************");
... ...
package com.sitech.ismp.coll.centercoll;
import com.xen.api.Types;
import java.util.HashMap;
import java.util.Vector;
... ... @@ -82,9 +80,10 @@ public interface CollLinuxHostMBean {
public Vector getProcessTop5Mem(HashMap params);
public Vector getPing(HashMap params);
public Vector getDemsg(HashMap params);
public Vector getNet(HashMap params);
public Vector getSSH(HashMap params);
}
... ...
package com.sitech.ismp.coll.centercoll;
import java.util.HashMap;
import java.util.Vector;
import com.sitech.ismp.coll.CollBase;
import com.sitech.ismp.check.downtime.CheckConnectionState;
import com.sitech.ismp.check.downtime.ParamterBean;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.util.DES3;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;
public class CollWindows implements CollWindowsMBean {
private static Logger log= Logger.getLogger(CollWindows.class);
String kbpClass="10-10-23-10"; // Windows 主机的标识
CheckConnectionState server=new CheckConnectionState();
/**
* 获取主机ping状态。
* 当3个ping周期都ping不通的时候,才能视不能ping通。
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getPingState(HashMap<String, String> params){
Vector<TblATO_KPIDETAIL> v=new Vector<TblATO_KPIDETAIL>();
String ip=params.get("IP");
if(!StringUtils.isEmpty(ip)){
String kpiId="FM-00-10-001-999"; // Windows 主机连接状态
String hostName=params.get("HOST_NAME");
String unitId = kbpClass+":" + hostName + "-total";
ParamterBean bean =new ParamterBean();
bean.setDEVICE_IP(ip);
bean.setType("windows");
log.info("*** execute getPingState ** ip=["+ip+"]** unitId=["+unitId+"]*********");
/**
* getPingState 方法执行后会将状态插入到表中,然后取当前时间
* 根基IP查询失败的次数,如果失败次数为3次,则确定为宕机,发送告警。
*/
CheckConnectionState server=new CheckConnectionState();
server.getPingState(bean);
// 根据IP获取ping的错误次数。如果是 DOWN 的话,发送告警信息。
String state=server.getPingErrorState(ip);
TblATO_KPIDETAIL kpidetail= new TblATO_KPIDETAIL();
log.info("***** unitId**"+unitId+"** state **"+state+"*******");
try {
kpidetail.setKPI_ID(kpiId);
kpidetail.setUNIT_ID(unitId);
kpidetail.setKPI_VALUE(state);
kpidetail.setCLL_TIME(new Date());
} catch (ParseException e) {
e.printStackTrace();
}
v.add(kpidetail);
}
return v;
}
/**
* 获取连接状态
* @param params
* @return
*/
@Override
public Vector<TblATO_KPIDETAIL> getSnmpState(HashMap<String, String> params){
Vector<TblATO_KPIDETAIL> v=new Vector<TblATO_KPIDETAIL>();
String ip=params.get("IP");
if(!StringUtils.isEmpty(ip)){
String kpiId="FM-00-10-001-998"; // Windows 设备登录状态
ParamterBean bean =new ParamterBean();
String tempPort=params.get("PORT");
String community=params.get("COMMUNITY");
int port=Integer.parseInt(tempPort);
String hostName=params.get("HOST_NAME");
log.info("******ip "+ip+"**port "+tempPort+"****hostName "+hostName+"*****");
bean.setDEVICE_IP(ip);
bean.setPROTOCOL_PORT(port);
bean.setCOMMUNITY(community);
String state=server.getConnectionState4Snmp(bean);
String unitId = kbpClass+":" + hostName + "-total";
TblATO_KPIDETAIL kpidetail=new TblATO_KPIDETAIL();
try {
kpidetail.setKPI_ID(kpiId);
kpidetail.setUNIT_ID(unitId);
kpidetail.setKPI_VALUE(state);
kpidetail.setCLL_TIME(new Date());
} catch (ParseException e) {
e.printStackTrace();
}
v.add(kpidetail);
}
return v;
}
public Vector<TblATO_KPIDETAIL> coll(HashMap params) {
CollWindowsWithSNMP windows = new CollWindowsWithSNMP(params);
return windows.coll(params);
// Vector kpi = new Vector();
// // 保存采集结果,并返回值
// CollBase collResult = new CollBase();
// if (windows.getSNMPState()) {
// Vector memoryKpi = windows.getMemory();
// if (memoryKpi.size() <= 0) {
// System.out.println("the memory size is 0 , the coll process will be colled!");
// memoryKpi = windows.getMemory();
// }
// collResult.addKPISet(memoryKpi);
//
// Vector fileKpi = windows.getFileSystem();
// collResult.addKPISet(fileKpi);
//
// Vector stateKpi = windows.getStates();
// collResult.addKPISet(stateKpi);
//
// Vector configKpi = windows.getConfig();
// collResult.addKPISet(configKpi);
//
// Vector cpuKpi = windows.getCPU();
// collResult.addKPISet(cpuKpi);
// } else {
// Vector stateKpi = windows.getStates();
// collResult.addKPISet(stateKpi);
// }
// return collResult.getKPISet();
}
public Vector<TblATO_KPIDETAIL> collSpecProcess(HashMap params) {
... ... @@ -76,6 +155,9 @@ public class CollWindows implements CollWindowsMBean {
CollWindowsWithHyperv windows = new CollWindowsWithHyperv(params);
return windows.getMemory(params);};
/**
* 采集Hyper-v的磁盘相关指标
* @param params
... ...
package com.sitech.ismp.coll.centercoll;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import java.util.HashMap;
import java.util.Vector;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
public interface CollWindowsMBean {
public Vector<TblATO_KPIDETAIL> coll(HashMap<String, String> params);
... ... @@ -25,4 +25,8 @@ public interface CollWindowsMBean {
public Vector<TblATO_KPIDETAIL> getFileSystem(HashMap<String, String> params);
public Vector<TblATO_KPIDETAIL> getConfig(HashMap<String, String> params);
public Vector<TblATO_KPIDETAIL> getPingState(HashMap<String, String> params);
public Vector<TblATO_KPIDETAIL> getSnmpState(HashMap<String, String> params);
}
\ No newline at end of file
... ...
package com.sitech.ismp.coll.middleware.tomcat;
import java.util.HashMap;
import java.util.Vector;
import com.sitech.ismp.check.downtime.CheckConnectionState;
import com.sitech.ismp.check.downtime.ParamterBean;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.ismp.coll.middleware.tomcat.impl.ICollTomcat;
import com.sitech.ismp.coll.middleware.tomcat.impl.TomcatCollFactory;
import com.sitech.util.Formater;
import org.apache.log4j.Logger;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;
public class CollTomcat implements CollTomcatMBean {
private static Logger log= Logger.getLogger(CollTomcat.class);
public Vector<TblATO_KPIDETAIL> getMemory(HashMap<String, String> params) {
TomcatCollFactory factory = new TomcatCollFactory();
... ... @@ -56,6 +63,44 @@ public class CollTomcat implements CollTomcatMBean {
return null;
}
/**
* 获取中间件所在主机的ping状态。
* @param params
* @return
*/
@Override
public Vector<TblATO_KPIDETAIL> getPingStatus(HashMap<String, String> params) {
/**
* 该 kbp_class kpiId 如果不存在,需要在页面添加。
*/
String kbp_class="10-12-13-20";
String kpiId="FM-00-12-001-999";
Vector<TblATO_KPIDETAIL> vector=new Vector<TblATO_KPIDETAIL>();
String jmx_url=params.get("JMX_URL");
int start=jmx_url.indexOf("/rmi://");
int end=jmx_url.lastIndexOf(":");
String ip=jmx_url.substring(start+7,end);
/**
* domain_name 实际就是 资源标识。
*/
String domain_name = params.get("DOMAIN_NAME");
String unitId = kbp_class +":"+ Formater.neatenunitid(domain_name) + "-RUNTIME";
CheckConnectionState server=new CheckConnectionState();
TblATO_KPIDETAIL kpidetail=new TblATO_KPIDETAIL();
try {
kpidetail.setUNIT_ID(unitId);
kpidetail.setKPI_ID(kpiId);
kpidetail.setKPI_VALUE(server.getPingState(new ParamterBean(ip)));
kpidetail.setCLL_TIME(new Date());
vector.add(kpidetail);
} catch (ParseException e){
e.printStackTrace();
}
return vector;
}
@Override
public Vector<TblATO_KPIDETAIL> getThreading(HashMap<String, String> params) {
TomcatCollFactory factory = new TomcatCollFactory();
... ...
package com.sitech.ismp.coll.middleware.tomcat;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import java.util.HashMap;
import java.util.Vector;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
public interface CollTomcatMBean {
public Vector<TblATO_KPIDETAIL> getMemory(HashMap<String, String> params);
... ... @@ -18,4 +18,11 @@ public interface CollTomcatMBean {
public Vector<TblATO_KPIDETAIL> getSession(HashMap<String, String> params);
public Vector<TblATO_KPIDETAIL> getClassLoading(HashMap<String, String> params);
/**
* 获取数据库所在主机的ping状态
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getPingStatus(HashMap<String, String> params);
}
... ...
package com.sitech.ismp.coll.middleware.tomcat.impl;
import java.io.IOException;
import java.lang.management.MemoryUsage;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
... ... @@ -22,9 +12,22 @@ import javax.management.openmbean.CompositeDataSupport;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.lang.management.MemoryUsage;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CollTomcat {
private static Logger log= Logger.getLogger(CollTomcat.class);
HashMap<String, String[]> environmentMap = null;
private MBeanServerConnection mbeanServerConn = null;
JMXConnector JMXConn = null;
... ... @@ -35,6 +38,11 @@ public class CollTomcat {
public void init(HashMap<String, String> params) {
String jmxurl = params.get("JMX_URL");
// frank 添加 IP参数,用于获取Tomcat所在主机的ping状态。
int start=jmxurl.indexOf("://");
int end=jmxurl.lastIndexOf(":");
String ip=jmxurl.substring(start+15,end);
params.put("ip",ip);
try {
JMXServiceURL serverURL = new JMXServiceURL(jmxurl);
try {
... ... @@ -116,7 +124,9 @@ public class CollTomcat {
protected void release() {
try {
this.JMXConn.close();
if(null != JMXConn){
this.JMXConn.close();
}
} catch (IOException e) {
e.printStackTrace();
}
... ...