initial commit

This commit is contained in:
chenjinsong
2018-09-27 16:17:06 +08:00
commit 9b3c3ac5d7
215 changed files with 50034 additions and 0 deletions

View File

@@ -0,0 +1,132 @@
package com.nms.server;
import java.sql.Connection;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import com.fang.lang.Db;
import com.nms.server.common.Common;
import com.nms.server.common.Config;
import com.nms.server.common.Constants;
import com.nms.server.thread.InitServerThread;
import com.nms.server.thread.WritePidThread;
import com.nms.server.thread.netty.NettyServer;
import com.nms.server.thread.socket.SSLServerManager;
import com.nms.server.util.DbPool;
/**
* DataController 程序启动主方法类
* @date Aug 10, 2011 1:55:25 PM
* @author ZhangGang
*
*/
public class DataController {
private static Logger logger = Logger.getLogger(DataController.class);
public static void doShutDownWork() {
logger.info("注册程序退出事件");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
// Thread.currentThread().setName("退出DC缓存数据清理线程");
Thread.currentThread().setName("Exit DC, Caching Data Cleaning Thread");
Common.stop();//程序停止运行
logger.info("停止DataController处理缓存数据。。。");
Common.clearDataInMem();
logger.info("停止DataController处理缓存数据 完成");
} catch (Exception ex) {
logger.error("Stop DataController, cache data entry anomalies, cache data to disk", ex);//1.全部入库,入库异常时存盘 或 2.全部存盘,下次启动时入库
Common.saveDataInMemToDisk();
logger.error("Stop DataController, cache data entry anomalies, cache data stored in hard disk to complete", ex);//1.全部入库,入库异常时存盘 或 2.全部存盘,下次启动时入库
}
}
});
}
/**
* DataController程序启动入口
* @time Jan 5, 2012-11:37:59 AM
* @param args
*/
public static void main(String [] args) {
// Thread.currentThread().setName("主程序");
Thread.currentThread().setName("Main Program");
logger.info("------- DataController 启动开始------------");
doShutDownWork();//注册shutdown事件
//书写PID
Common.service.submit(new WritePidThread());
// WritePidThread pidth = new WritePidThread();
// pidth.run();
//- 初始化数据库连接池(在优化方向:将数据库连接池创建及维护通过 其专有维护线程实现独立管理)
try {
Thread.sleep(3000);
DbPool.initPool();
//初始化Common.Db
Common.initDb(new Db(new Db.DataSource() {
@Override
public Connection getConnection() {
try {
return DbPool.getConnection();
} catch (Exception e) {
logger.error("",e);
}
return null;
}
}));
Thread.sleep(3000);
String sequenceTable=Config.getString("sequence.table", "detection_info");
if(!sequenceTable.equals("0")){
String[] split=sequenceTable.split(",");
Common.initSequence(Common.getDb().getConnection(),split);
}
} catch (ClassNotFoundException e) {
logger.error("Load database driver failure");
} catch (Exception e) {
logger.error("Initialization of connection pool exception"+e.getMessage());
}
//- 启动加密通讯端口监听
try {
Common.service.submit(new SSLServerManager(Constants.SSL_SERVER_PORT,true)); //与web和Agent端通讯线程启动
if(Constants.NETTY_SERVER_FLAG == 1){
//启动netty server
Common.service.submit(new NettyServer(Constants.NETTY_SERVER_PORT, Constants.NETTY_SERVER_SSL));
}
} catch (Exception e) {
// String info = "通讯服务启动失败!\n请确定程序是否未启动或检查服务端口["+Constants.SSL_SERVER_PORT+"]未被占用!\n"+e.getMessage();
String info = "The communication service failed to start! \n please confirm whether the program has not started or checked the service port["+Constants.SSL_SERVER_PORT+"]is not occupied!\n"+e.getMessage();
// String info = "i18n_server.DataController.showMsg_n81i["+Constants.SSL_SERVER_PORT+"]i18n_server.DataController.isExists_n81i\n"+e.getMessage();
logger.error(info);//i18nlog
// JOptionPane.showMessageDialog(null, info, "错误", JOptionPane.ERROR_MESSAGE);
// JOptionPane.showMessageDialog(null, info, "Error", JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, info, "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
//- 获取本机IP
/*try {
String localIp = Common.getLocalIp();
if(StringUtils.isBlank(localIp)){
String info = "读取本地IP失败 程序无法启动 请检查配置文件";
logger.error(info);
JOptionPane.showMessageDialog(null, info, "错误", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
} catch (Exception e) {
String info = "主线程执行异常,被迫中止\n"+e.getMessage();
logger.error(info);
JOptionPane.showMessageDialog(null, info, "错误", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}*/
//- 执行加载启动操作
Common.service.submit(new InitServerThread());
}
}

View File

@@ -0,0 +1,197 @@
package com.nms.server.bean;
/**
* 告警信息对象
*
*/
public class AlarmInfo {
/**
* 告警设置id
*/
private Long id;
/**
* 监测设置ID
*/
private Long setInfoId;
/**
* 监测类型名称cpu...
*/
private String checkType;
/**
* 进程标识
*/
private String processIden;
/**
* 字段表字段Id
*/
private Long metadataId;
/**
* 字段序号
*/
private Integer showNum;
/**
* 字段描述
*/
private String filedCommonts;
/**
* 报警状态
*/
private String policeState;
/**
* 报警值
*/
private String policeValue;
/**
* 报警单位
*/
private String policeUnit;
/**
* 报警比较符针对number型数据>、<、>=、<=、= 针对字符串类型数据equal、 include、exclude
*/
private String policeSysmbols;
/**
* 报警等级
*/
private Integer policeLevel;
/**
* 报警紧急标示告警 (是否紧急 0紧急 1非紧急 默认为1
*/
private Integer policeEmergent;
/**
* 设置告警时指定多个标识符如多个盘符、多个CPU、多个网卡如硬盘使用率所有盘存在一个盘使用率超过告警值则告警all所有盘总的使用率超过告警值则告警指定多个盘符指定盘存在一个盘使用率超过告警值则告警
*/
private String marker;
/**
* 标识符对应字段在metadata表中的id
*/
private Integer markerFiledId;;
/**
* 标识符对应字段在metadata表中的showNum
*/
private Integer markerFiledShowNum;
public Long getSetInfoId() {
return setInfoId;
}
public void setSetInfoId(Long setInfoId) {
this.setInfoId = setInfoId;
}
public Long getMetadataId() {
return metadataId;
}
public void setMetadataId(Long metadataId) {
this.metadataId = metadataId;
}
public Integer getShowNum() {
return showNum;
}
public void setShowNum(Integer showNum) {
this.showNum = showNum;
}
public String getPoliceState() {
return policeState;
}
public void setPoliceState(String policeState) {
this.policeState = policeState;
}
public String getPoliceValue() {
return policeValue;
}
public void setPoliceValue(String policeValue) {
this.policeValue = policeValue;
}
public String getPoliceUnit() {
return policeUnit;
}
public void setPoliceUnit(String policeUnit) {
this.policeUnit = policeUnit;
}
public String getPoliceSysmbols() {
return policeSysmbols;
}
public void setPoliceSysmbols(String policeSysmbols) {
this.policeSysmbols = policeSysmbols;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getPoliceLevel() {
return policeLevel;
}
public void setPoliceLevel(Integer policeLevel) {
this.policeLevel = policeLevel;
}
public String getCheckType() {
return checkType;
}
public void setCheckType(String checkType) {
this.checkType = checkType;
}
public String getProcessIden() {
return processIden;
}
public void setProcessIden(String processIden) {
this.processIden = processIden;
}
public String getFiledCommonts() {
return filedCommonts;
}
public void setFiledCommonts(String filedCommonts) {
this.filedCommonts = filedCommonts;
}
public Integer getPoliceEmergent() {
return policeEmergent;
}
public void setPoliceEmergent(Integer policeEmergent) {
if(policeEmergent==null){policeEmergent = 1;}
this.policeEmergent = policeEmergent;
}
public String toString() {
return "showNum=" + showNum + ",policeSysmbols=" + policeSysmbols
+ ",policeValue=" + policeValue + ",policeLevel=" + policeLevel;
}
public String toStringVal(){
return showNum + "|" + policeSysmbols + "|" + policeValue + "|"
+ policeLevel + "|" + filedCommonts;
}
public String getMarker()
{
return marker;
}
public void setMarker(String marker)
{
this.marker = marker;
}
public Integer getMarkerFiledId()
{
return markerFiledId;
}
public void setMarkerFiledId(Integer markerFiledId)
{
this.markerFiledId = markerFiledId;
}
public Integer getMarkerFiledShowNum()
{
return markerFiledShowNum;
}
public void setMarkerFiledShowNum(Integer markerFiledShowNum)
{
this.markerFiledShowNum = markerFiledShowNum;
}
}

View File

@@ -0,0 +1,127 @@
package com.nms.server.bean;
import java.util.Date;
/**
* 客户端用到的监测设置信息实体
*
*/
public class ContactSetInfo {
/**
* 监测设置信息ID
*/
private Long missionId;
private String missionName;
private String nodeGroupName;
private String nodeGroupsId;
private String nodeIpsId;
private String nodeIpsName;
private Long missionType;
private Long missionState;
private Long isLoop;
private Date startTime;
private Date endTime;
private Long viewLevel;
private Long createUserId;
private Long createUserGroupId;
private Long systemId;
private String contactUserIds;
public Long getViewLevel() {
return viewLevel;
}
public void setViewLevel(Long viewLevel) {
this.viewLevel = viewLevel;
}
public Long getCreateUserId() {
return createUserId;
}
public void setCreateUserId(Long createUserId) {
this.createUserId = createUserId;
}
public Long getCreateUserGroupId() {
return createUserGroupId;
}
public void setCreateUserGroupId(Long createUserGroupId) {
this.createUserGroupId = createUserGroupId;
}
public Long getSystemId() {
return systemId;
}
public void setSystemId(Long systemId) {
this.systemId = systemId;
}
public String getContactUserIds() {
return contactUserIds;
}
public void setContactUserIds(String contactUserIds) {
this.contactUserIds = contactUserIds;
}
public Long getMissionId() {
return missionId;
}
public void setMissionId(Long missionId) {
this.missionId = missionId;
}
public String getMissionName() {
return missionName;
}
public void setMissionName(String missionName) {
this.missionName = missionName;
}
public String getNodeGroupName() {
return nodeGroupName;
}
public void setNodeGroupName(String nodeGroupName) {
this.nodeGroupName = nodeGroupName;
}
public Long getMissionType() {
return missionType;
}
public void setMissionType(Long missionType) {
this.missionType = missionType;
}
public Long getMissionState() {
return missionState;
}
public void setMissionState(Long missionState) {
this.missionState = missionState;
}
public Long getIsLoop() {
return isLoop;
}
public void setIsLoop(Long isLoop) {
this.isLoop = isLoop;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public String getNodeGroupsId() {
return nodeGroupsId;
}
public void setNodeGroupsId(String nodeGroupsId) {
this.nodeGroupsId = nodeGroupsId;
}
public String getNodeIpsId() {
return nodeIpsId;
}
public void setNodeIpsId(String nodeIpsId) {
this.nodeIpsId = nodeIpsId;
}
public String getNodeIpsName() {
return nodeIpsName;
}
public void setNodeIpsName(String nodeIpsName) {
this.nodeIpsName = nodeIpsName;
}
}

View File

@@ -0,0 +1,328 @@
package com.nms.server.bean;
import java.util.List;
import java.util.Map;
/**
* 监测信息
* @author Nan,Fang
* 2016-2-29
*/
public class DetecAllInfo {
/* 基本信息解析格式变量 */
private String seqId = null; //seqId
private String setInfoId = null; //监测设置ID
private String checkType = null; //监测类别
private String process = null; //进程名称(监测类别设置名称)
private Long startTime = null; //监测服务启动时间
private Integer delayTime = null; //检测时延(秒)
private Long checkTime = null; //本次检测时间
private Integer currentTimes = null; //尝试次数
private Long nextCheckTime = null; //下次计划监测时间
private Long arriveTime;
private Integer state = -1; //执行状态是否成功是否正常
private String showNums = null; //告警序列(数据)
private Integer pLevel = 99; //告警级别(数据)
//private int pl = 99; //告警级别(入库)
private String pValue = null; //告 警 值(数据)
private String dsinfo = null; //状态信息(描述信息)
private String pdata = null; //性能数据
private List<Map<String,String>> details;//详细参数
private boolean delyFlag; //是否解析详细参数标志
private int urgentLevel ; //紧急级别
private String alarmInfo;//告警信息
private boolean sendEmailFlag;//邮件发送标志
private boolean stateChangeFlag;//状态变更标志
private long statusChangTime = -1L;//状态变更时间
private EmailInfo emailInfo;//邮件信息
private List<String[]> diskInfoList; // net 特殊格式追加详细信息
private List<String[]> netInfoList; // net 特殊格式追加详细信息
private DetecAllInfo appendWarningInfo ;//延迟数据,追加告警信息
private byte[] dsb;//存放字节数字格式的监测数据,用于解析异常时,存监测数据到硬盘的时候用
/**
* 以下属性用于记录原监测数据
*/
private String valid;
private String detectionInfoId;
private String waitTime;
/**
* 无参构造方法
*/
public DetecAllInfo(){
}
public String getSeqId() {
return seqId;
}
public void setSeqId(String seqId) {
this.seqId = seqId;
}
public String getSetInfoId() {
return setInfoId;
}
public void setSetInfoId(String setInfoId) {
this.setInfoId = setInfoId;
}
public String getCheckType() {
return checkType;
}
public void setCheckType(String checkType) {
this.checkType = checkType;
}
public String getProcess() {
return process;
}
public void setProcess(String process) {
this.process = process;
}
public Long getStartTime() {
return startTime;
}
public void setStartTime(Long startTime) {
this.startTime = startTime;
}
public Integer getDelayTime() {
return delayTime;
}
public void setDelayTime(Integer delayTime) {
this.delayTime = delayTime;
}
public Long getCheckTime() {
return checkTime;
}
public void setCheckTime(Long checkTime) {
this.checkTime = checkTime;
}
public Integer getCurrentTimes() {
return currentTimes;
}
public void setCurrentTimes(Integer currentTimes) {
this.currentTimes = currentTimes;
}
public Long getNextCheckTime() {
return nextCheckTime;
}
public void setNextCheckTime(Long nextCheckTime) {
this.nextCheckTime = nextCheckTime;
}
public String getShowNums() {
return showNums;
}
public void setShowNums(String showNums) {
this.showNums = showNums;
}
public String getpValue() {
return pValue;
}
public void setpValue(String pValue) {
this.pValue = pValue;
}
public String getDsinfo() {
return dsinfo;
}
public void setDsinfo(String dsinfo) {
this.dsinfo = dsinfo;
}
public String getPdata() {
return pdata;
}
public void setPdata(String pdata) {
this.pdata = pdata;
}
public List<Map<String, String>> getDetails() {
return details;
}
public void setDetails(List<Map<String, String>> details) {
this.details = details;
}
public Long getArriveTime() {
return arriveTime;
}
public void setArriveTime(Long arriveTime) {
this.arriveTime = arriveTime;
}
public boolean isDelyFlag() {
return delyFlag;
}
public void setDelyFlag(boolean delyFlag) {
this.delyFlag = delyFlag;
}
public int getUrgentLevel() {
return urgentLevel;
}
public void setUrgentLevel(int urgentLevel) {
this.urgentLevel = urgentLevel;
}
public String getAlarmInfo() {
return alarmInfo;
}
public void setAlarmInfo(String alarmInfo) {
this.alarmInfo = alarmInfo;
}
public boolean isStateChangeFlag() {
return stateChangeFlag;
}
public void setStateChangeFlag(boolean stateChangeFlag) {
this.stateChangeFlag = stateChangeFlag;
}
public boolean isSendEmailFlag() {
return sendEmailFlag;
}
public void setSendEmailFlag(boolean sendEmailFlag) {
this.sendEmailFlag = sendEmailFlag;
}
public void setState(Integer state) {
this.state = state;
}
public Integer getState() {
return state;
}
public Integer getpLevel() {
return pLevel;
}
public void setpLevel(Integer pLevel) {
this.pLevel = pLevel;
}
public EmailInfo getEmailInfo() {
return emailInfo;
}
public void setEmailInfo(EmailInfo emailInfo) {
this.emailInfo = emailInfo;
}
public long getStatusChangTime() {
return statusChangTime;
}
public void setStatusChangTime(long statusChangTime) {
this.statusChangTime = statusChangTime;
}
public List<String[]> getDiskInfoList() {
return diskInfoList;
}
public void setDiskInfoList(List<String[]> diskInfoList) {
this.diskInfoList = diskInfoList;
}
public List<String[]> getNetInfoList() {
return netInfoList;
}
public void setNetInfoList(List<String[]> netInfoList) {
this.netInfoList = netInfoList;
}
public DetecAllInfo getAppendWarningInfo() {
return appendWarningInfo;
}
public void setAppendWarningInfo(DetecAllInfo appendWarningInfo) {
this.appendWarningInfo = appendWarningInfo;
}
public String getValid() {
return valid;
}
public void setValid(String valid) {
this.valid = valid;
}
public String getDetectionInfoId() {
return detectionInfoId;
}
public void setDetectionInfoId(String detectionInfoId) {
this.detectionInfoId = detectionInfoId;
}
public String getWaitTime() {
return waitTime;
}
public void setWaitTime(String waitTime) {
this.waitTime = waitTime;
}
public byte[] getDsb()
{
return dsb;
}
public void setDsb(byte[] dsb)
{
this.dsb = dsb;
}
}

View File

@@ -0,0 +1,403 @@
package com.nms.server.bean;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import com.fang.U;
import com.nms.server.common.Common;
import com.nms.server.common.Config;
import com.nms.server.dao.OracleToMysql;
public class DetectInfo {
public static final int SEQID = 0; //seqId
public static final int SETINFOID = 1; //监测设置ID
public static final int CHECKTYPE = 2; //监测类别
public static final int PROCESS = 3; //进程名称(监测类别设置名称)
public static final int STARTTIME = 4; //监测服务启动时间
public static final int DELAYTIME = 5; //检测时延(秒)
public static final int CHECKTIME = 6; //本次检测时间
public static final int CURRENTTIMES = 7; //尝试次数
public static final int NEXTCHECKTIME = 8; //下次计划监测时间
public static final int ARRIVETIME = 9;
public static final int STATE = 10; //执行状态是否成功是否正常
public static final int SHOWNUMS = 11; //告警序列(数据)
public static final int PLEVEL = 12; //告警级别(数据)
public static final int PVALUE = 13; //告 警 值(数据)
public static final int DSINFO = 14; //状态信息(描述信息)
public static final int PDATA = 15; //性能数据
public static final int DETAILS = 16;//详细参数
public static final int DELYFLAG = 17; //是否解析详细参数标志
public static final int URGENTLEVEL =18 ; //紧急级别
public static final int ALARMINFO =19 ;//告警信息
public static final int SENDEMAILFLAG =20;//邮件发送标志
public static final int STATECHANGEFLAG =21;//状态变更标志
public static final int STATUSCHANGTIME = 22;//状态变更时间
public static final int EMAILINFO = 23;//邮件信息
public static final int DISKINFOLIST = 24; // net 特殊格式追加详细信息
public static final int NETINFOLIST =25; // net 特殊格式追加详细信息
public static final int APPENDWARNINGINFO = 26;//延迟数据,追加告警信息
//public static final int DSB = 27;//存放字节数字格式的监测数据,用于解析异常时,存监测数据到硬盘的时候用
/**
* 以下属性用于记录原监测数据
*/
public static final int VALID = 27;
public static final int DETECTIONINFOID = 28;
public static final int WAITTIME = 29;
/**
* 从解析之后数据恢复成原数据时使用
*/
public static final int SHOWNUMLIST = 30;
public static final int PLEVELLIST = 31;
public static final int ALARMLIST = 32;
/**
* detect_queue 的 key
*/
public static final String INFO_KEY = "INFO";
public static final String DISK_STR_KEY = "DISK_STR";
public static final String NET_STR_KEY = "NET_STR";
/**
* 详细表中的外键字段名
*/
public static final String DETECTION_INFO_ID = "DETECTION_INFO_ID";
public static final String DETECTION_INFO="detection_info";
/*
* 该字段是针对,同一时间点多条具体数据(写多个文件),比如:网卡监测(多个网卡问题)
*/
private List<String> detailDatas = new LinkedList<String>();
/*
* 针对公共数据的描述信息
*/
private String descInfo;
/**
* 尝试次数 (小于最大尝试次数)
*/
private int testTimes;
/**
* 监测时间
*/
private long checkTime;
/*
* 该字段是针对一条数据,关联的其他表的数据;写入到一个文件的: String 是解析标识, List<String[]>是多条数据String[]存入表中的数据)
* 如系统信息监测数据中有网卡数量网卡数量关联着其他表表中又有多个字段如网卡名称IP子网掩码等等
*/
private Map<String, List<String[]>> relatedDatas;
public List<String> getDetailDatas() {
return detailDatas;
}
public void setDetailDatas(List<String> detailDatas) {
this.detailDatas = detailDatas;
}
public String getDescInfo() {
return descInfo;
}
public void setDescInfo(String descInfo) {
this.descInfo = descInfo;
}
public Map<String, List<String[]>> getRelatedDatas() {
return relatedDatas;
}
public void setRelatedDatas(Map<String, List<String[]>> relatedDatas) {
this.relatedDatas = relatedDatas;
}
public int getTestTimes() {
return testTimes;
}
public void setTestTimes(int testTimes) {
this.testTimes = testTimes;
}
public long getCheckTime() {
return checkTime;
}
public void setCheckTime(long checkTime) {
this.checkTime = checkTime;
}
/**
* DETECTION_INFO insert sql
* @return
*/
public static String getInsertInfoSql(){
String insertInfoSql = "";
if(Common.SEQUENCE.get(DetectInfo.DETECTION_INFO)!=null){
insertInfoSql = "INSERT INTO DETECTION_INFO (ID, DETECTION_SET_INFO_ID, DETECTION_STATE_INFO, " +
"PERFORMACE_DATA, CURRENT_TIMES, START_TIME, DELAY_TIME, NEXT_CHECK_TIME, " +
"POLICE_LEVEL, DATA_CHECK_TIME, DATA_ARRIVE_TIME, DETECTIONED_STATE, " +
"DATA_CHECK_TIME_DIGITAL, DATA_ARRIVE_TIME_DIGITAL, SEQ_ID, POLICE_EMERGENT,STATUS_CHANGE_TIME,SEQUENCE)"
+" VALUES (?, ?, ?, ?, ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, ?, ?, ?, ?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),?)";
}else{
insertInfoSql = "INSERT INTO DETECTION_INFO (ID, DETECTION_SET_INFO_ID, DETECTION_STATE_INFO, " +
"PERFORMACE_DATA, CURRENT_TIMES, START_TIME, DELAY_TIME, NEXT_CHECK_TIME, " +
"POLICE_LEVEL, DATA_CHECK_TIME, DATA_ARRIVE_TIME, DETECTIONED_STATE, " +
"DATA_CHECK_TIME_DIGITAL, DATA_ARRIVE_TIME_DIGITAL, SEQ_ID, POLICE_EMERGENT,STATUS_CHANGE_TIME)"
+" VALUES (?, ?, ?, ?, ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, ?, ?, ?, ?,to_date(?,'yyyy-mm-dd hh24:mi:ss'))";
}
return OracleToMysql.trans(insertInfoSql);
}
/**
* 组织detail表的insert语句
* @param fieldNames
* @param detailTableName
* @param tempMap
* @return
*/
public static String createDetailSql(List<String> fieldNames,
String detailTableName, Map<String, String> tempMap) {
String insertDetailSql;
StringBuffer preSql = new StringBuffer();
StringBuffer sufSql = new StringBuffer();
preSql.append(",DETECTION_INFO_ID");
sufSql.append(",?");
fieldNames.add("DETECTION_INFO_ID");
for(String tempField : tempMap.keySet()){
fieldNames.add(tempField);
preSql.append("," + tempField);
sufSql.append(",?");
}
insertDetailSql = "insert into "+detailTableName +" ( "+ preSql.substring(1) +" ) values (" + sufSql.substring(1) +" )";
return insertDetailSql;
}
/**
* 计算 detection_info 及详细表的关联主键
* @param checkTime 监测时间
* @param seqId 节点id
* @param setId 监测设置id
* @return 10位时间戳 + 5位 seqId + 3位 setId
*/
public static String computeId(String checkTime,String seqId,String setId){
if(U.Strs.isAllNotBlank(checkTime,seqId,setId)){
StringBuilder sb = new StringBuilder();
checkTime = checkTime.substring(checkTime.length() -10);//截取时间戳 后10位
sb.append("00000");
sb.append(seqId);
seqId = sb.substring(sb.length()-5);// seqId 占 5位
sb.delete(0, sb.length());//清空sb
sb.append("000");
sb.append(setId);
setId = sb.substring(sb.length() - 3); // set info id 占 3位
sb.setLength(0);
sb.append(checkTime);
sb.append(seqId);
sb.append(setId);
return sb.toString();
}
return null;
}
/**
* 监测设置查询权限 为 1 2 3 的邮件列表 sql
* @return
*/
public static String getDetecEmailListOf123Sql(){
StringBuilder sb = new StringBuilder();
sb.append(" select distinct c.id, xyj1.email ");
sb.append(" from xt_yh_jbxx xyj1, ");
sb.append(" (select dsi.id, ',' || dsi.contact_user_ids || ',' as ids ");
sb.append(" from detection_set_info dsi ");
sb.append(" where dsi.contact_user_ids is not null) c ");
sb.append(" where c.ids like ('%,' || xyj1.yhid || ',%') ");
sb.append(" and xyj1.email is not null ");
sb.append(" union ");
sb.append(" (select distinct dsi.id,xyj.email ");
sb.append(" from detection_set_info dsi ");
sb.append(" left join xt_js_jbxx xjj ");
sb.append(" on dsi.create_usergroup_id = xjj.jsbh ");
sb.append(" left join xt_yh_js_index xyji ");
sb.append(" on xjj.jsbh = xyji.jsbh ");
sb.append(" left join xt_yh_jbxx xyj ");
sb.append(" on xyj.yhid = xyji.yhid ");
sb.append(" where xyj.is_receiveemail = '0' ");
sb.append(" and xjj.zxbz = 0 ");
sb.append(" and xjj.type = 1 ");
sb.append(" and xyj.zxbz = 0 ");
sb.append(" and dsi.view_level = 2 ");
sb.append(" and xyj.email is not null ");
sb.append(" and dsi.create_usergroup_id is not null ");
sb.append(" and dsi.contact_user_ids is null) ");
sb.append(" union ");
sb.append(" ( ");
sb.append(" select distinct dsi.id,xyj.email from detection_set_info dsi ");
sb.append(" left join gorup_system_table gst ");
sb.append(" on gst.system_id = dsi.system_id ");
sb.append(" left join xt_js_jbxx xjj ");
sb.append(" on gst.user_group_id = xjj.jsbh ");
sb.append(" left join xt_yh_js_index xyji ");
sb.append(" on xjj.jsbh = xyji.jsbh ");
sb.append(" left join xt_yh_jbxx xyj ");
sb.append(" on xyji.yhid = xyj.yhid ");
sb.append(" where xyj.is_receiveemail = '0' ");
sb.append(" and xjj.zxbz = 0 ");
sb.append(" and xjj.type = 1 ");
sb.append(" and xyj.zxbz = 0 ");
sb.append(" and dsi.view_level = 3 ");
sb.append(" and xyj.email is not null ");
sb.append(" and dsi.contact_user_ids is null ");
sb.append(" ) ");
return OracleToMysql.trans(sb.toString());
}
/**
* 监测设置查看权限为 4 的 邮件列表 sql
* @return
*/
public static String getDetecEmailListOf4Sql(){
StringBuilder sb = new StringBuilder();
sb.append(" select distinct nt.seq_id ,xyj.email");
sb.append(" from xt_yh_jbxx xyj ");
sb.append(" left join xt_yh_js_index xyji ");
sb.append(" on xyji.yhid = xyj.yhid ");
sb.append(" left join xt_js_jbxx xjj ");
sb.append(" on xjj.jsbh = xyji.jsbh ");
sb.append(" left join gorup_system_table gst ");
sb.append(" on gst.user_group_id = xjj.jsbh ");
sb.append(" left join system_table st ");
sb.append(" on st.system_id = gst.system_id ");
sb.append(" left join node_table nt ");
sb.append(" on nt.system_id = gst.system_id ");
sb.append(" left join nodegroup_table ngt ");
sb.append(" on ngt.group_id = nt.node_group_id ");
sb.append(" where xyj.is_receiveemail = '0' ");
sb.append(" and nt.node_state = 0 ");
sb.append(" and ngt.is_valid = 1 ");
sb.append(" and st.system_state = 0 ");
sb.append(" and xjj.zxbz = 0 ");
sb.append(" and xjj.type = 1 ");
sb.append(" and xyj.zxbz = 0 ");
return sb.toString();
}
/**
* detection_info 表的 insert 语句
* @return
*/
public static String getInsertDetectInfoSql(){
String insertInfoSql="";
if(Common.SEQUENCE.get(DetectInfo.DETECTION_INFO)==null){
insertInfoSql = "INSERT INTO DETECTION_INFO (ID, DETECTION_SET_INFO_ID, DETECTION_STATE_INFO, " +
"PERFORMACE_DATA, CURRENT_TIMES, START_TIME, DELAY_TIME, NEXT_CHECK_TIME, " +
"POLICE_LEVEL, DATA_CHECK_TIME, DATA_ARRIVE_TIME, DETECTIONED_STATE, " +
"DATA_CHECK_TIME_DIGITAL, DATA_ARRIVE_TIME_DIGITAL, SEQ_ID, POLICE_EMERGENT)"
+" VALUES (?, ?, ?, ?, ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, ?, ?, ?, ?)";
}else{
insertInfoSql = "INSERT INTO DETECTION_INFO (ID, DETECTION_SET_INFO_ID, DETECTION_STATE_INFO, " +
"PERFORMACE_DATA, CURRENT_TIMES, START_TIME, DELAY_TIME, NEXT_CHECK_TIME, " +
"POLICE_LEVEL, DATA_CHECK_TIME, DATA_ARRIVE_TIME, DETECTIONED_STATE, " +
"DATA_CHECK_TIME_DIGITAL, DATA_ARRIVE_TIME_DIGITAL, SEQ_ID, POLICE_EMERGENT,SEQUENCE)"
+" VALUES (?, ?, ?, ?, ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, ?, ?, ?, ?,?)";
}
return OracleToMysql.trans(insertInfoSql);
}
/**
* detection_warning 表的insert 语句
* @return
*/
public static String getInsertWarningSql(){
//插入warning表
String insertWaringSql = "INSERT INTO DETECTION_INFO_WARNING (ID, DETECTION_SET_INFO_ID, DETECTION_STATE_INFO, " +
"PERFORMACE_DATA, CURRENT_TIMES, START_TIME, DELAY_TIME, NEXT_CHECK_TIME, " +
"POLICE_LEVEL, DATA_CHECK_TIME, DATA_ARRIVE_TIME, DETECTIONED_STATE, " +
"DATA_CHECK_TIME_DIGITAL, DATA_ARRIVE_TIME_DIGITAL, SEQ_ID, POLICE_EMERGENT)"
+" VALUES (?, ?, ?, ?, ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, to_date(?,'yyyy-mm-dd hh24:mi:ss'), to_date(?,'yyyy-mm-dd hh24:mi:ss'), ?, ?, ?, ?, ?)";
return OracleToMysql.trans(insertWaringSql);
}
/**
* email_info 表的insert语句
* @return
*/
public static String getInsertEmailSql(){
//插入email_table表
String insertEmailSql = " insert into email_table (to_address,action_type,content,send_flag,action_ip,action_date,action_desc,send_level,CREATE_TIME)" +
" values(?,?,?,?,?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),?,?,to_date(?,'yyyy-mm-dd hh24:mi:ss'))";
return OracleToMysql.trans(insertEmailSql);
}
/**
* 更新状态变更时间
* @return
*/
public static String getUpdateStatusSql(){
String sql = "update detection_info_new din set din.status_change_time =to_date(?,'yyyy-mm-dd hh24:mi:ss') where din.seq_id=?";
return OracleToMysql.trans(sql);
}
public static String getSaveToNewSql(){
String sql=" insert into detection_info_new(detection_set_info_id ,detection_state_info ,"
+ "performace_data ,current_times ,start_time ,wait_time ,delay_time ,next_check_time ,"
+ "police_level ,data_check_time ,data_arrive_time ,detectioned_state ,"
+ "status_change_time ,seq_id ,detection_info_id,data_check_time_digital,data_arrive_time_digital ,"
+ "POLICE_EMERGENT ) VALUES"
+"(?,?,"
+ "?,?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),?,?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),"
+ "?,to_date(?,'yyyy-mm-dd hh24:mi:ss'),to_date(?,'yyyy-mm-dd hh24:mi:ss'),?,"
+ "to_date(?,'yyyy-mm-dd hh24:mi:ss'),?,?,?,?,?)";
return OracleToMysql.trans(sql);
}
public static String getUpdateToNewSql(){
String sql=" update detection_info_new din set "
+"din.detection_state_info = ?"
+", din.performace_data = ?"
+", din.current_times = ?"
+", din.start_time = to_date(?,'yyyy-mm-dd hh24:mi:ss')"
+", din.wait_time = ?"
+" , din.delay_time = ?"
+" , din.next_check_time = to_date(?,'yyyy-mm-dd hh24:mi:ss')"
+" , din.police_level = ?"
+" , din.data_check_time = to_date(?,'yyyy-mm-dd hh24:mi:ss')"
+" , din.data_arrive_time = to_date(?,'yyyy-mm-dd hh24:mi:ss')"
+", din.detectioned_state = ?"
+" , din.status_change_time = to_date(?,'yyyy-mm-dd hh24:mi:ss')"
+" , detection_info_id = ?"
+" ,data_check_time_digital = ?"
+" ,data_arrive_time_digital = ?"
+" ,POLICE_EMERGENT = ?"
+" where din.detection_set_info_id = ?"
+" and din.seq_id = ?";
return OracleToMysql.trans(sql);
}
public static String getChangeWarningInfoSql(){
String sql="update detection_info_warning set valid =0 where SEQ_ID=? and DETECTION_SET_INFO_ID=? and valid=1";
return OracleToMysql.trans(sql);
}
}

View File

@@ -0,0 +1,43 @@
package com.nms.server.bean;
import java.util.concurrent.Future;
/**
* 断点下载文件 数据模板
* @date Mar 8, 2012 4:33:41 PM
* @author ZhangGang
*
*/
public class DownloadFileModel {
private String fileName;
private String MD5Val;
private Future<Object> bpDownFuture;
public DownloadFileModel(){
}
public DownloadFileModel(String fileName,String MD5Val,Future<Object> bpDownFuture){
this.fileName = fileName;
this.MD5Val = MD5Val;
this.bpDownFuture = bpDownFuture;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMD5Val() {
return MD5Val;
}
public void setMD5Val(String val) {
MD5Val = val;
}
public Future<Object> getBpDownFuture() {
return bpDownFuture;
}
public void setBpDownFuture(Future<Object> bpDownFuture) {
this.bpDownFuture = bpDownFuture;
}
}

View File

@@ -0,0 +1,148 @@
package com.nms.server.bean;
public class EmailInfo {
/**
* 邮件ID
*/
private Long id;
/**
* 目标地址
*/
private String toAddress; //接收地址
/**
* 事件类型
* 10监测恢复11监测信息异常12:监测结果超时,
* 20主动告警恢复21主动告警异常
* 31结果失败32任务状态变更
* 40系统运行异常恢复41系统运行异常
*/
private Integer actionType; //
/**
* 事件标题(具体的监测、任务等名称标题)
*/
private String actionDesc; //
/**
* 事件摘要(监测或任务下的,典型描述)
private String actionDesc2; //
*/
/**
* 事件地点
*/
private String actionIp; //
/**
* 事件时间
*/
private String actionDate; //
/**
* 事件内容及结果
*/
private String content; //
/**
* 发送标示
* 0未发送 1已发送
*/
private Integer sendFlag; //
/**
* 发送标示
* 0紧急发送 1 非紧急
*/
private Integer sendLevel; //
public EmailInfo (){
}
public EmailInfo (EmailInfo info){
this.toAddress = info.getToAddress();
this.actionType = info.getActionType();
this.actionDesc = info.getActionDesc();
// this.actionDesc2 = info.getActionDesc2();
this.actionIp = info.getActionIp();
this.actionDate = info.getActionDate();
this.content = info.getContent();
this.sendFlag = info.getSendFlag();
this.sendLevel = info.getSendLevel();
}
public EmailInfo (Integer actionType,String actionDesc,/*String actionDesc2,*/String actionIp,String actionDate,String content,Integer sendFlag,Integer sendLevel){
this.actionType = actionType;
this.actionDesc = actionDesc;
// this.actionDesc2 = actionDesc2;
this.actionIp = actionIp;
this.actionDate = actionDate;
this.content = content;
this.sendFlag = sendFlag;
this.sendLevel = sendLevel;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public Integer getActionType() {
return actionType;
}
public void setActionType(Integer actionType) {
this.actionType = actionType;
}
public String getActionIp() {
return actionIp;
}
public void setActionIp(String actionIp) {
this.actionIp = actionIp;
}
public String getActionDate() {
return actionDate;
}
public void setActionDate(String actionDate) {
this.actionDate = actionDate;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getSendFlag() {
return sendFlag;
}
public void setSendFlag(Integer sendFlag) {
this.sendFlag = sendFlag;
}
public String getActionDesc() {
return actionDesc;
}
public void setActionDesc(String actionDesc) {
this.actionDesc = actionDesc;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/*public String getActionDesc2() {
return actionDesc2;
}
public void setActionDesc2(String actionDesc2) {
this.actionDesc2 = actionDesc2;
}
*/
public Integer getSendLevel() {
return sendLevel;
}
public void setSendLevel(Integer sendLevel) {
this.sendLevel = sendLevel;
}
}

View File

@@ -0,0 +1,36 @@
package com.nms.server.bean;
public class EmailModel {
private String toAddress; //接收地址
private String subjectDesc; //主题
private String content; //邮件内容
private Integer sendFlag; //0未发送 1已发送 2即时发送
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getSubjectDesc() {
return subjectDesc;
}
public void setSubjectDesc(String subjectDesc) {
this.subjectDesc = subjectDesc;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getSendFlag() {
return sendFlag;
}
public void setSendFlag(Integer sendFlag) {
this.sendFlag = sendFlag;
}
}

View File

@@ -0,0 +1,128 @@
package com.nms.server.bean;
import java.util.Date;
/**
* EventRecordLibrary entity.
*
* @author MyEclipse Persistence Tools
*/
public class EventRecordLibrary implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String recordType;
private String recordContent;
private Long seqId;
private Long state;
private String recordCommand;
private Date createTime; // 创建时间
// private String tableName; // 操作表
// private Long tableId; //表主键
// Constructors
/** default constructor */
public EventRecordLibrary() {
}
/** full constructor */
public EventRecordLibrary(String recordType, String recordContent,
Long seqId, Long state, String recordCommand) {
this.recordType = recordType;
this.recordContent = recordContent;
this.seqId = seqId;
this.state = state;
this.recordCommand = recordCommand;
}
// Property accessors
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getRecordType() {
return this.recordType;
}
public void setRecordType(String recordType) {
this.recordType = recordType;
}
public String getRecordContent() {
return this.recordContent;
}
public void setRecordContent(String recordContent) {
this.recordContent = recordContent;
}
public Long getSeqId() {
return seqId;
}
public void setSeqId(Long seqId) {
this.seqId = seqId;
}
public Long getState() {
return this.state;
}
public void setState(Long state) {
this.state = state;
}
public String getRecordCommand() {
return this.recordCommand;
}
public void setRecordCommand(String recordCommand) {
this.recordCommand = recordCommand;
}
// public Long getPid() {
// return pid;
// }
//
// public void setPid(Long pid) {
// this.pid = pid;
// }
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
// public String getTableName() {
// return tableName;
// }
//
// public void setTableName(String tableName) {
// this.tableName = tableName;
// }
//
// public Long getTableId() {
// return tableId;
// }
//
// public void setTableId(Long tableId) {
// this.tableId = tableId;
// }
}

View File

@@ -0,0 +1,53 @@
package com.nms.server.bean;
import java.util.Date;
/**
* MissionStateTable entity.
*
* @author MyEclipse Persistence Tools
*/
public class LoopMissionRoundInfo implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 8184110460944634042L;
private Long missionId;
private Long curMissionId;
private Long missionState;
private Date startTime;
private Date endTime;
public Long getMissionId() {
return missionId;
}
public void setMissionId(Long missionId) {
this.missionId = missionId;
}
public Long getCurMissionId() {
return curMissionId;
}
public void setCurMissionId(Long curMissionId) {
this.curMissionId = curMissionId;
}
public Long getMissionState() {
return missionState;
}
public void setMissionState(Long missionSate) {
this.missionState = missionSate;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
}

View File

@@ -0,0 +1,41 @@
package com.nms.server.bean;
public class MissionResult {
private Long missionId;// 任务ID
private String nodeIp;// 节点IP
private Long uuid;// 节点IP
private Long result;// 结果
private String description;// 结果描述
public Long getMissionId() {
return missionId;
}
public void setMissionId(Long missionId) {
this.missionId = missionId;
}
public String getNodeIp() {
return nodeIp;
}
public void setNodeIp(String nodeIp) {
this.nodeIp = nodeIp;
}
public Long getResult() {
return result;
}
public void setResult(Long result) {
this.result = result;
}
public Long getUuid() {
return uuid;
}
public void setUuid(Long uuid) {
this.uuid = uuid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@@ -0,0 +1,118 @@
package com.nms.server.bean;
import java.io.Serializable;
public class MissionResult2 implements Serializable{
/**
*
*/
private static final long serialVersionUID = -2036264131238309952L;
private Long missionId;// 任务ID
private Long missionType;// 节点IP
private Long uuid;// 节点IP
private Long startTime;// 配置截取文本
private Long EndTime;// 配置截取文本
private String text;// 配置截取文本
private Long result;// 结果
private String description;// 结果描述
private String fileInfo;// 回传文件
private Long loopFlag;// 周期标识 0 非周期1 周期
private Long resultDetail;//执行结果失败的具体原因目前只有下发失败41
public MissionResult2() {
}
public MissionResult2(Long missionId) {
this.missionId = missionId;
}
public MissionResult2(Long missionId,Long missionType,Long uuid,Long startTime,Long EndTime,String text,Long result,String description,String fileInfo,Long loopFlag) {
this.missionId = missionId;// 任务ID
this.missionType = missionType;;// 节点IP
this.uuid = uuid;;// 节点IP
this.startTime = startTime;;// 配置截取文本
this.EndTime = EndTime;;// 配置截取文本
this.text = text;;// 配置截取文本
this.result = result;;// 结果
this.description = description;;// 结果描述
this.fileInfo = fileInfo;;// 结果描述
this.loopFlag = loopFlag;;// 周期标识 0 非周期1 周期
}
public Long getMissionId() {
return missionId;
}
public void setMissionId(Long missionId) {
this.missionId = missionId;
}
public Long getResult() {
return result;
}
public void setResult(Long result) {
this.result = result;
}
public Long getUuid() {
return uuid;
}
public void setUuid(Long uuid) {
this.uuid = uuid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getMissionType() {
return missionType;
}
public void setMissionType(Long missionType) {
this.missionType = missionType;
}
public Long getStartTime() {
return startTime;
}
public void setStartTime(Long startTime) {
this.startTime = startTime;
}
public Long getEndTime() {
return EndTime;
}
public void setEndTime(Long endTime) {
EndTime = endTime;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getFileInfo() {
return fileInfo;
}
public void setFileInfo(String fileInfo) {
this.fileInfo = fileInfo;
}
public Long getLoopFlag() {
return loopFlag;
}
public void setLoopFlag(Long loopFlag) {
this.loopFlag = loopFlag;
}
public Long getResultDetail()
{
return resultDetail;
}
public void setResultDetail(Long resultDetail)
{
this.resultDetail = resultDetail;
}
}

View File

@@ -0,0 +1,152 @@
package com.nms.server.bean;
import java.util.Date;
/**
* MissionStateTable entity.
*
* @author MyEclipse Persistence Tools
*/
public class MissionStateTable implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = -1342600696641355325L;
private Long missionId;
// private String missionName;
private Long missionType;
// private String missionTypeName;
private Long missionState;
// private Long viewLevel;
// private Long userId;
// private String userIdName;
private Long groupId;
private Long nodeListId;
private String nodeIpsId;
// private Long nodeListId1;
private String nodeGroupsId;
// private String groupIdName;
// private Date createTime;
private Date startTime;
private Date endTime;
// private String failDesc;
private Long systemId;
// private String systemIdName;
private Long loopFlag = 0L;
private Long loopDelay;
// Constructors
/** default constructor */
public MissionStateTable() {
}
public Long getMissionId() {
return missionId;
}
public void setMissionId(Long missionId) {
this.missionId = missionId;
}
public Long getMissionType() {
return missionType;
}
public void setMissionType(Long missionType) {
this.missionType = missionType;
}
public Long getMissionState() {
return missionState;
}
public void setMissionState(Long missionState) {
this.missionState = missionState;
}
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Long getSystemId() {
return systemId;
}
public void setSystemId(Long systemId) {
this.systemId = systemId;
}
public Long getLoopFlag() {
return loopFlag;
}
public void setLoopFlag(Long loopFlag) {
this.loopFlag = loopFlag;
}
public Long getLoopDelay() {
return loopDelay;
}
public void setLoopDelay(Long loopDelay) {
this.loopDelay = loopDelay;
}
public Long getNodeListId() {
return nodeListId;
}
public void setNodeListId(Long nodeListId) {
this.nodeListId = nodeListId;
}
// public Long getNodeListId1() {
// return nodeListId1;
// }
//
// public void setNodeListId1(Long nodeListId1) {
// this.nodeListId1 = nodeListId1;
// }
public String getNodeGroupsId() {
return nodeGroupsId;
}
public void setNodeGroupsId(String groupsId) {
this.nodeGroupsId = groupsId;
}
public String getNodeIpsId() {
return nodeIpsId;
}
public void setNodeIpsId(String nodeIpsId) {
this.nodeIpsId = nodeIpsId;
}
}

View File

@@ -0,0 +1,86 @@
package com.nms.server.bean;
/**
* NmsErrorCode entity.
*
* @author MyEclipse Persistence Tools
*/
public class NmsErrorCode implements java.io.Serializable {
// Fields
private Long id;
private String errorCode;
private String errorName;
private String errorDes;
private Long errorLevel;
// Constructors
/** default constructor */
public NmsErrorCode() {
}
/** minimal constructor */
public NmsErrorCode(Long id, String errorCode, String errorName,
Long errorLevel) {
this.id = id;
this.errorCode = errorCode;
this.errorName = errorName;
this.errorLevel = errorLevel;
}
/** full constructor */
public NmsErrorCode(Long id, String errorCode, String errorName,
String errorDes, Long errorLevel) {
this.id = id;
this.errorCode = errorCode;
this.errorName = errorName;
this.errorDes = errorDes;
this.errorLevel = errorLevel;
}
// Property accessors
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getErrorCode() {
return this.errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorName() {
return this.errorName;
}
public void setErrorName(String errorName) {
this.errorName = errorName;
}
public String getErrorDes() {
return this.errorDes;
}
public void setErrorDes(String errorDes) {
this.errorDes = errorDes;
}
public Long getErrorLevel() {
return this.errorLevel;
}
public void setErrorLevel(Long errorLevel) {
this.errorLevel = errorLevel;
}
}

View File

@@ -0,0 +1,135 @@
package com.nms.server.bean;
import java.util.Date;
/**
* NmsErrorInfo entity.
*
* @author MyEclipse Persistence Tools
*/
public class NmsErrorInfo implements java.io.Serializable {
// Fields
private Long id;
private String errorCode;
private Date errorTime;
private String errortGetip;
private String errortIp;
private String errortDesc;
private Long errorState;
private Date stateUpdateTime;
private Long stateUpdateUserid;
// Constructors
/** default constructor */
public NmsErrorInfo() {
}
/** minimal constructor */
public NmsErrorInfo(Long id) {
this.id = id;
}
/** full constructor */
// public NmsErrorInfo(Long id, String errorCode, Date errorTime,
// String errortGetip, String errortIp, Long errorState,
// Date stateUpdateTime, Long stateUpdateUserid,String errortDesc) {
// this.id = id;
// this.errorCode = errorCode;
// this.errorTime = errorTime;
// this.errortGetip = errortGetip;
// this.errortIp = errortIp;
// this.errorState = errorState;
// this.errortDesc = errortDesc;
// this.stateUpdateTime = stateUpdateTime;
// this.stateUpdateUserid = stateUpdateUserid;
// }
public NmsErrorInfo(String errorCode, Date errorTime,
String errortGetip, String errortIp, Long errorState,String errortDesc) {
this.errorCode = errorCode;
this.errorTime = errorTime;
this.errortGetip = errortGetip;
this.errortIp = errortIp;
this.errorState = errorState;
this.errortDesc = errortDesc;
}
// Property accessors
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getErrorCode() {
return this.errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public Date getErrorTime() {
return this.errorTime;
}
public void setErrorTime(Date errorTime) {
this.errorTime = errorTime;
}
public String getErrortGetip() {
return this.errortGetip;
}
public void setErrortGetip(String errortGetip) {
this.errortGetip = errortGetip;
}
public String getErrortIp() {
return this.errortIp;
}
public void setErrortIp(String errortIp) {
this.errortIp = errortIp;
}
public Long getErrorState() {
return this.errorState;
}
public void setErrorState(Long errorState) {
this.errorState = errorState;
}
public Date getStateUpdateTime() {
return this.stateUpdateTime;
}
public void setStateUpdateTime(Date stateUpdateTime) {
this.stateUpdateTime = stateUpdateTime;
}
public Long getStateUpdateUserid() {
return this.stateUpdateUserid;
}
public void setStateUpdateUserid(Long stateUpdateUserid) {
this.stateUpdateUserid = stateUpdateUserid;
}
public String getErrortDesc() {
return errortDesc;
}
public void setErrortDesc(String errortDesc) {
this.errortDesc = errortDesc;
}
}

View File

@@ -0,0 +1,131 @@
package com.nms.server.bean;
/**
* NodeTable entity.
*
* @author MyEclipse Persistence Tools
*/
public class NodeModel implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = 1984053252904108229L;
private Long nodeId;
private String nodeIp;
/* 节点类型 0服务器 1交换机 */
private Long nodeType;
// private String nodeName;
/* 节点状态 0有效 1无效*/
private Long nodeState;
private Long systemId;
private Long seqId;
private Long groupId;
private String nodeUserName;
private String nodePassword;
// Constructors
/** default constructor */
public NodeModel() {
}
public NodeModel(String nodeIp,Long nodeType) {
this.nodeIp = nodeIp;
this.nodeType = nodeType;
}
/** minimal constructor */
public NodeModel(Long nodeId, Long nodeState,
Long systemId) {
this.nodeId = nodeId;
// this.nodeName = nodeName;
this.nodeState = nodeState;
this.systemId = systemId;
//this.nodeLatticeId=nodeLatticeId;
}
// Property accessors
public Long getNodeId() {
return this.nodeId;
}
public void setNodeId(Long nodeId) {
this.nodeId = nodeId;
}
public Long getNodeState() {
return this.nodeState;
}
public void setNodeState(Long nodeState) {
this.nodeState = nodeState;
}
public Long getSystemId() {
return this.systemId;
}
public void setSystemId(Long systemId) {
this.systemId = systemId;
}
public String getNodeIp() {
return nodeIp;
}
public void setNodeIp(String nodeIp) {
this.nodeIp = nodeIp;
}
public Long getNodeType() {
return nodeType;
}
public void setNodeType(Long nodeType) {
this.nodeType = nodeType;
}
public Long getSeqId() {
return seqId;
}
public void setSeqId(Long seqId) {
this.seqId = seqId;
}
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public String getNodeUserName() {
return nodeUserName;
}
public void setNodeUserName(String nodeUserName) {
this.nodeUserName = nodeUserName;
}
public String getNodePassword() {
return nodePassword;
}
public void setNodePassword(String nodePassword) {
this.nodePassword = nodePassword;
}
}

View File

@@ -0,0 +1,66 @@
package com.nms.server.bean;
/**
* NodegroupTable entity.
*
* @author MyEclipse Persistence Tools
*/
public class NodegroupModel implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = -5562024412959332727L;
private Long groupId;
private String groupName;
private Long groupType;
private Long systemId;
private Long isValid;//0是失效1是生效
// Property accessors
public Long getGroupId() {
return this.groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return this.groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public Long getGroupType() {
return this.groupType;
}
public void setGroupType(Long groupType) {
this.groupType = groupType;
}
public void setSystemId(Long systemId) {
this.systemId = systemId;
}
public Long getIsValid() {
return this.isValid;
}
public void setIsValid(Long isValid) {
this.isValid = isValid;
}
public Long getSystemId() {
return systemId;
}
}

View File

@@ -0,0 +1,106 @@
package com.nms.server.bean;
import java.util.Date;
public class ReturnFilePO {
/**
* ID
*/
private Long taskId;
/**
* 类型4 命令执行6 升级
*/
private long taskType;
/**
* 唯一标志一台物理机类似于IP
*/
private long uuid;
/**
* 回传路径集: key 文件实际路径 value 文件别名
*/
// private Map<String, String> filePathMap;
/**
* 当前要回传的文件
*/
// private File curRetrunFile;
/**
* 回传文件名(统一处理后一个任务只有一个回传文件)
*/
private String returnFileName;
/**
* 回传状态0 成功1 失败
*/
private long state;
/**
* 开始时间
*/
private Date startTime;
/**
* 结束时间
*/
private Date endTime;
/**
* 是否循环任务
*/
private long isLoop;
/**
* 回传文件的结果描述
*/
private String resDesc;
public Long getTaskId() {
return taskId;
}
public void setTaskId(Long taskId) {
this.taskId = taskId;
}
public long getTaskType() {
return taskType;
}
public void setTaskType(long taskType) {
this.taskType = taskType;
}
public long getState() {
return state;
}
public void setState(long state) {
this.state = state;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public long getIsLoop() {
return isLoop;
}
public void setIsLoop(long isLoop) {
this.isLoop = isLoop;
}
public String getResDesc() {
return resDesc;
}
public void setResDesc(String resDesc) {
this.resDesc = resDesc;
}
public String getReturnFileName() {
return returnFileName;
}
public void setReturnFileName(String returnFileName) {
this.returnFileName = returnFileName;
}
public long getUuid() {
return uuid;
}
public void setUuid(long uuid) {
this.uuid = uuid;
}
}

View File

@@ -0,0 +1,32 @@
package com.nms.server.bean;
public class ServerIpSegment {
public String startIp;
public Long startIpn;
public String endIp;
public Long endIpn;
public String getStartIp() {
return startIp;
}
public void setStartIp(String startIp) {
this.startIp = startIp;
}
public Long getStartIpn() {
return startIpn;
}
public void setStartIpn(Long startIpn) {
this.startIpn = startIpn;
}
public String getEndIp() {
return endIp;
}
public void setEndIp(String endIp) {
this.endIp = endIp;
}
public Long getEndIpn() {
return endIpn;
}
public void setEndIpn(Long endIpn) {
this.endIpn = endIpn;
}
}

View File

@@ -0,0 +1,121 @@
package com.nms.server.bean;
import java.util.LinkedList;
import java.util.List;
/**
* ServerTable entity.
*
* @author MyEclipse Persistence Tools
*/
public class ServerTable implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id; //数据库DC 注册ID
private String serverName; //当前DC名称
private Long serverState; //当前DC状态
private String serverIp; //当前DC IP
private Long serverIpn; //当前DC IPN
private int index; //当前dc 在数据库的排序
private int conut; //当前dc 总数
//- 当前DC 的IP管理范围空时 过滤条件为空,即为管理全部 注意)
private List<ServerIpSegment> ipSegList = new LinkedList<ServerIpSegment>();
// Constructors
/** default constructor */
public ServerTable() {
}
/** full constructor */
public ServerTable(String serverName, Long serverState, String serverIp,
Long serverIpn) {
this.serverName = serverName;
this.serverState = serverState;
this.serverIp = serverIp;
this.serverIpn = serverIpn;
}
/** All constructor */
public ServerTable(Long id,String serverName, Long serverState, String serverIp,
Long serverIpn) {
this.id = id;
this.serverName = serverName;
this.serverState = serverState;
this.serverIp = serverIp;
this.serverIpn = serverIpn;
}
// Property accessors
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getServerName() {
return this.serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public Long getServerState() {
return this.serverState;
}
public void setServerState(Long serverState) {
this.serverState = serverState;
}
public String getServerIp() {
return this.serverIp;
}
public void setServerIp(String serverIp) {
this.serverIp = serverIp;
}
public Long getServerIpn() {
return this.serverIpn;
}
public void setServerIpn(Long serverIpn) {
this.serverIpn = serverIpn;
}
public List<ServerIpSegment> getIpSegList() {
return ipSegList;
}
public void setIpSegList(List<ServerIpSegment> ipSegList) {
this.ipSegList = ipSegList;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getConut() {
return conut;
}
public void setConut(int conut) {
this.conut = conut;
}
}

View File

@@ -0,0 +1,277 @@
package com.nms.server.bean;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
/**
* 客户端用到的监测设置信息实体
*
*/
/**
* @author chuan
*
*/
public class SetInfo {
/**
* 监测设置信息ID
*/
private Long id;
/**
* 检测类型
*/
private String checkTypeName;//如CPU、DISK等
private Long checkTypeId;//检测类型的ID预留
/**
* 目标IP
*/
// private String nodeIp;//
/**
* 最大测试次数
*/
private Long checkMaxTimes;
/**
* 节点组ID
*/
// private Long groupId;
/**
*
*/
private String nodeGroupsId;
/**
* 最大测试次数
*/
private String nodeIpsId;
/**
* 时间间隔(单位:分钟)
*/
private Long checkGap;
/**
* 超时时间(单位:秒)
*/
private Long checkOutTime;
/**
* 监测状态0无效1有效
*/
private String checkState;
/**
* 监测方式0主动1被动
*/
private String checkWay;
/**
* 进程标志
*/
private String processIden;
/**
* 进程执行文件
*/
private String processFile;
/**
* 进程执行文件路径
*/
private String processPath;
/**
* 是否系统启动NMSAgent启动/第三方自己启动默认0自启动1NMSAgent启动
*/
private String IsControlStart;
/* *//**
* 是否需下发文件0需要1不需要 默认1
*//*
private String isIssueFile;
*//**
* 文件下发是否成功;0成功1不成功 默认1
*//*
private String isIssued;
*//**
* 是否下发设置0下发1未下发 默认值为1如新添加或者修改一项设置之后设置为未下发需要完成其他配置信息后才执行一次下发
*//*
private String isIssue;*/
/**
* 控制启动时间
*/
private Long controlStartTime;
/**
*上传数据时间间隔单位分钟不能为空默认15分钟。监测数据上传到NMSServer周期。
*/
private Long uploadGap;
/**
* 计划检测时间:针对当前配置信息首次执行时间
*/
private Long planCheckTime;
/**
* 是否预置监测
*/
private String isSchedule;
/**
* 监测级别
*/
private Long viewLevel;
/**
* 指定IP操作
*/
private String nodeIp2; //指定单个IP
/**
* 进程搜索关键字
*/
private String processSearchKeyCode; //指定单个IP
/**
* 是否SNMP检测 0objectSNMP 1SNMP4j
*/
private Long isSNMP;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCheckTypeName() {
return checkTypeName;
}
public void setCheckTypeName(String checkTypeName) {
this.checkTypeName = checkTypeName;
}
public Long getCheckTypeId() {
return checkTypeId;
}
public Long getCheckMaxTimes() {
return checkMaxTimes;
}
public void setCheckMaxTimes(Long checkMaxTimes) {
this.checkMaxTimes = checkMaxTimes;
}
public Long getCheckGap() {
return checkGap;
}
public void setCheckGap(Long checkGap) {
this.checkGap = checkGap;
}
public Long getCheckOutTime() {
return checkOutTime;
}
public void setCheckOutTime(Long checkOutTime) {
this.checkOutTime = checkOutTime;
}
public String getCheckState() {
return checkState;
}
public void setCheckState(String checkState) {
this.checkState = checkState;
}
public String getProcessIden() {
return processIden;
}
public void setProcessIden(String processIden) {
this.processIden = processIden;
}
public String getProcessFile() {
return processFile;
}
public void setProcessFile(String processFile) {
this.processFile = processFile;
}
public String getProcessPath() {
return processPath;
}
public void setProcessPath(String processPath) {
this.processPath = processPath;
}
public void setCheckTypeId(Long checkTypeId) {
this.checkTypeId = checkTypeId;
}
public String getCheckWay() {
return checkWay;
}
public void setCheckWay(String checkWay) {
this.checkWay = checkWay;
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
// public String getNodeIp() {
// return nodeIp;
// }
// public void setNodeIp(String nodeIp) {
// this.nodeIp = nodeIp;
// }
public String getIsControlStart() {
return IsControlStart;
}
public void setIsControlStart(String isControlStart) {
IsControlStart = isControlStart;
}
public Long getControlStartTime() {
return controlStartTime;
}
public void setControlStartTime(Long controlStartTime) {
this.controlStartTime = controlStartTime;
}
public Long getPlanCheckTime() {
return planCheckTime;
}
public void setPlanCheckTime(Long planCheckTime) {
this.planCheckTime = planCheckTime;
}
public Long getUploadGap() {
return uploadGap;
}
public void setUploadGap(Long uploadGap) {
this.uploadGap = uploadGap;
}
public String getIsSchedule() {
return isSchedule;
}
public void setIsSchedule(String isSchedule) {
this.isSchedule = isSchedule;
}
// public Long getGroupId() {
// return groupId;
// }
// public void setGroupId(Long groupId) {
// this.groupId = groupId;
// }
public Long getIsSNMP() {
return isSNMP;
}
public void setIsSNMP(Long isSNMP) {
this.isSNMP = isSNMP;
}
public String getNodeGroupsId() {
return nodeGroupsId;
}
public void setNodeGroupsId(String nodeGroupsId) {
this.nodeGroupsId = nodeGroupsId;
}
public String getNodeIpsId() {
return nodeIpsId;
}
public void setNodeIpsId(String nodeIpsId) {
this.nodeIpsId = nodeIpsId;
}
public String getNodeIp2() {
return nodeIp2;
}
public void setNodeIp2(String nodeIp2) {
this.nodeIp2 = nodeIp2;
}
public Long getViewLevel() {
return viewLevel;
}
public void setViewLevel(Long viewLevel) {
this.viewLevel = viewLevel;
}
public String getProcessSearchKeyCode() {
return processSearchKeyCode;
}
public void setProcessSearchKeyCode(String processSearchKeyCode) {
this.processSearchKeyCode = processSearchKeyCode;
}
}

View File

@@ -0,0 +1,29 @@
package com.nms.server.bean;
/**
*
* 简单节点对象
* @date Jun 18, 2013 3:51:28 PM
* @author ZhangGang
*
*/
public class SimpleNode {
private String nodeIp; //节点IP
private Integer snmpVersion; // 节点SNMP版本 version1 version2c version3
public SimpleNode(String nodeIp,Integer snmpVersion){
this.nodeIp = nodeIp;
this.snmpVersion = snmpVersion;
}
public String getNodeIp() {
return nodeIp;
}
public void setNodeIp(String nodeIp) {
this.nodeIp = nodeIp;
}
public Integer getSnmpVersion() {
return snmpVersion;
}
public void setSnmpVersion(Integer snmpVersion) {
this.snmpVersion = snmpVersion;
}
}

View File

@@ -0,0 +1,57 @@
package com.nms.server.bean;
/**
* 表字段详细信息
* @date Jun 18, 2013 4:02:44 PM
* @author ZhangGang
*
*/
public class TableColumnsModel {
private String filedName; //字段名称 表字段名称
private String filedComments; //字段描述 中文名称
private String filedType; //字段类型
private String oid; //字段OID 用于snmp
// private Integer showNum;
public TableColumnsModel() {
}
public TableColumnsModel(String filedName,String filedComments,String filedType,String oid) {
this.filedName = filedName;
this.filedComments = filedComments;
this.filedType = filedType;
this.oid = oid;
// this.showNum = showNum;
}
public String getFiledName() {
return filedName;
}
public void setFiledName(String filedName) {
this.filedName = filedName;
}
public String getFiledComments() {
return filedComments;
}
public void setFiledComments(String filedComments) {
this.filedComments = filedComments;
}
public String getFiledType() {
return filedType;
}
public void setFiledType(String filedType) {
this.filedType = filedType;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
// public Integer getShowNum() {
// return showNum;
// }
// public void setShowNum(Integer showNum) {
// this.showNum = showNum;
// }
}

View File

@@ -0,0 +1,39 @@
package com.nms.server.bean;
/**
* 监测类别信息
* @date Jun 18, 2013 4:04:15 PM
* @author ZhangGang
*
*/
public class TableModel {
private String tableName ; //表名称 库表名称
private String oid ; // 监测类别对应的OID
private Long isSnmp; // 监测类别是否是snmp
public TableModel (){
}
public TableModel (String tableName,String oid,Long isSnmp){
this.tableName = tableName;
this.oid = oid;
this.isSnmp = isSnmp;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public Long getIsSnmp() {
return isSnmp;
}
public void setIsSnmp(Long isSnmp) {
this.isSnmp = isSnmp;
}
}

View File

@@ -0,0 +1,70 @@
package com.nms.server.bean;
/**
* 任务实体类1 文件推送
*
*/
public class Task1 {
/**
* 任务ID
*/
private Long taskId;
/**
* 任务类型1 文件推送2 非流文本数据获取3 流文本数据获取4 命令执行5 shell注册
*/
private long taskType;
/**
* 节点组Id
*/
private Long nodeListId;
private String nodeIpsId;
// private Long nodeListId1;
private String nodeGroupsId;
/**
* 节点组Id
*/
private String taskParam;
public Long getTaskId() {
return taskId;
}
public void setTaskId(Long taskId) {
this.taskId = taskId;
}
public long getTaskType() {
return taskType;
}
public void setTaskType(long taskType) {
this.taskType = taskType;
}
public Long getNodeListId() {
return nodeListId;
}
public void setNodeListId(Long nodeListId) {
this.nodeListId = nodeListId;
}
public String getTaskParam() {
return taskParam;
}
public void setTaskParam(String taskParam) {
this.taskParam = taskParam;
}
public String getNodeGroupsId() {
return nodeGroupsId;
}
public void setNodeGroupsId(String groupsId) {
this.nodeGroupsId = groupsId;
}
// public Long getNodeListId1() {
// return nodeListId1;
// }
// public void setNodeListId1(Long nodeListId1) {
// this.nodeListId1 = nodeListId1;
// }
public String getNodeIpsId() {
return nodeIpsId;
}
public void setNodeIpsId(String nodeIpsId) {
this.nodeIpsId = nodeIpsId;
}
}

View File

@@ -0,0 +1,165 @@
package com.nms.server.bean;
/**
* 任务实体类4 命令执行
*
*/
public class Task4 {
/**
* 任务ID
*/
private Long taskId;
/**
* 任务类型1 文件推送2 非流文本数据获取3 流文本数据获取4 命令执行5 shell注册
*/
private long taskType;
/**
* 命令类型1 Agent原生支持命令2 脚本3 shell命令
*/
private long commandType;
/**
* 命令名称
*/
private String commandName;
/**
* 命令参数
*/
private String commandParam;
/**
* 脚本路径
*/
private String scriptPath;
/**
* 执行状态4下发任务40 下发成功41下发失败5杀进程50成功51失败、6备份、7更新覆盖 、8启动进程
*/
private long state;
/**
* 执行状态0 周期执行5撤销执行
*/
private Long missionState;
/**
* 如果是升级,旧的版本
*/
private Long version;
/**
* 节点组Id
*/
private Long nodeListId;
private String nodeIpsId;
private String nodeGroupsId;
/**
* 执行时间
*/
private Long startTime;
/**
* 结束时间
*/
private Long endTime;
/**
* 是否循环任务
*/
private Long isLoop;
/**
* 如果是循环任务,循环周期
*/
private Long loopDelay;
public Long getTaskId() {
return taskId;
}
public void setTaskId(Long taskId) {
this.taskId = taskId;
}
public long getTaskType() {
return taskType;
}
public void setTaskType(long taskType) {
this.taskType = taskType;
}
public long getCommandType() {
return commandType;
}
public void setCommandType(long commandType) {
this.commandType = commandType;
}
public String getCommandName() {
return commandName;
}
public void setCommandName(String commandName) {
this.commandName = commandName;
}
public String getCommandParam() {
return commandParam;
}
public void setCommandParam(String commandParam) {
this.commandParam = commandParam;
}
public String getScriptPath() {
return scriptPath;
}
public void setScriptPath(String scriptPath) {
this.scriptPath = scriptPath;
}
public long getState() {
return state;
}
public void setState(long state) {
this.state = state;
}
public Long getMissionState() {
return missionState;
}
public void setMissionState(Long missionState) {
this.missionState = missionState;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public Long getNodeListId() {
return nodeListId;
}
public void setNodeListId(Long nodeListId) {
this.nodeListId = nodeListId;
}
public String getNodeIpsId() {
return nodeIpsId;
}
public void setNodeIpsId(String nodeIpsId) {
this.nodeIpsId = nodeIpsId;
}
public String getNodeGroupsId() {
return nodeGroupsId;
}
public void setNodeGroupsId(String nodeGroupsId) {
this.nodeGroupsId = nodeGroupsId;
}
public Long getStartTime() {
return startTime;
}
public void setStartTime(Long startTime) {
this.startTime = startTime;
}
public Long getEndTime() {
return endTime;
}
public void setEndTime(Long endTime) {
this.endTime = endTime;
}
public Long getIsLoop() {
return isLoop;
}
public void setIsLoop(Long isLoop) {
this.isLoop = isLoop;
}
public Long getLoopDelay() {
return loopDelay;
}
public void setLoopDelay(Long loopDelay) {
this.loopDelay = loopDelay;
}
}

View File

@@ -0,0 +1,181 @@
package com.nms.server.bean;
/**
* 任务实体类6 升级
*
*/
public class Task6 {
/**
* 任务ID
*/
private Long taskId;
/**
* 任务类型1 文件推送4 命令执行5 shell注册6 升级
*/
private long taskType;
/**
* 命令类型4 Agent原生支持命令
*/
private long commandType;
/**
* 命令名称
*/
private String commandName;
/**
* 命令参数
*/
private String commandParam;
/**
* 执行状态4下发任务40 下发成功41下发失败5杀进程50成功51失败、6备份、7更新覆盖 、8启动进程
*/
private Long state;
/**
* 当前版本
*/
private Long version;
/**
* 节点组Id(Agent无用)
*/
private Long nodeListId;
private String nodeIpsId;
// private Long nodeListId1;
private String nodeGroupsId;
/**
* 升级时间
*/
private Long upgradeTime;
/**
* 推送文件名
*/
private String fileName;
/**
* 推送目的地
*/
private String destPath;
/**
* 推送文件的MD5值
*/
private String md5Value;
/**
* 全局权限用户名(未来)
*/
private String username;
/**
* 全局权限密码(未来 约定加密方式)
*/
private String userpwd;
/**
* 重新执行原任务ID
*/
private Long oldTaskId;
public Long getTaskId() {
return taskId;
}
public void setTaskId(Long taskId) {
this.taskId = taskId;
}
public long getTaskType() {
return taskType;
}
public void setTaskType(long taskType) {
this.taskType = taskType;
}
public long getCommandType() {
return commandType;
}
public void setCommandType(long commandType) {
this.commandType = commandType;
}
public String getCommandName() {
return commandName;
}
public void setCommandName(String commandName) {
this.commandName = commandName;
}
public String getCommandParam() {
return commandParam;
}
public void setCommandParam(String commandParam) {
this.commandParam = commandParam;
}
public Long getState() {
return state;
}
public void setState(Long state) {
this.state = state;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public Long getNodeListId() {
return nodeListId;
}
public void setNodeListId(Long nodeListId) {
this.nodeListId = nodeListId;
}
public Long getUpgradeTime() {
return upgradeTime;
}
public void setUpgradeTime(Long upgradeTime) {
this.upgradeTime = upgradeTime;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getDestPath() {
return destPath;
}
public void setDestPath(String destPath) {
this.destPath = destPath;
}
public String getMd5Value() {
return md5Value;
}
public void setMd5Value(String md5Value) {
this.md5Value = md5Value;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
public Long getOldTaskId() {
return oldTaskId;
}
public void setOldTaskId(Long oldTaskId) {
this.oldTaskId = oldTaskId;
}
public String getNodeGroupsId() {
return nodeGroupsId;
}
public void setNodeGroupsId(String groupsId) {
this.nodeGroupsId = groupsId;
}
// public Long getNodeListId1() {
// return nodeListId1;
// }
// public void setNodeListId1(Long nodeListId1) {
// this.nodeListId1 = nodeListId1;
// }
//
public String getNodeIpsId() {
return nodeIpsId;
}
public void setNodeIpsId(String nodeIpsId) {
this.nodeIpsId = nodeIpsId;
}
}

View File

@@ -0,0 +1,162 @@
package com.nms.server.bean;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import org.snmp4j.PDU;
import org.snmp4j.smi.Variable;
public class TrapMessageInfo
{
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 TrapMessageInfo()
{
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;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,68 @@
package com.nms.server.common;
import java.util.ListResourceBundle;
public class CommonResources extends ListResourceBundle{
static final Object[][] contents = new String[][]{
// { "ms_1", "已创建" },
// { "ms_2", "进行中" },
// { "ms_3", "已完成" },
// { "ms_30", "全部成功" },
// { "ms_31", "全部失败" },
// { "ms_32", "部分成功" },
// { "ms_4", "未能执行" },
// { "ms_5", "撤销准备" },
// { "ms_6", "撤销开始" },
// { "ms_7", "撤销完成" },
// { "mt_1", "推送文件" },
// { "mt_4", "命令执行" },
// { "mt_6", "升级部署" },
// { "loop_0", "非周期任务" },
// { "loop_1", "周期任务" },
// { "ec_1", "任务开始下发" },
// { "ec_4", "任务开始下发" },
// { "ec_6", "任务开始下发"}};
// { "ms_1", "Created" },
// { "ms_2", "In progress" },
// { "ms_3", "Completed" },
// { "ms_30", "All succeeded" },
// { "ms_31", "All failed" },
// { "ms_32", "Partially successful" },
// { "ms_4", "Failed to execute" },
// { "ms_5", "Undo preparation" },
// { "ms_6", "Revocation starts" },
// { "ms_7", "Undo completed" },
// { "mt_1", "Push File" },
// { "mt_4", "Command execution" },
// { "mt_6", "Upgrade deployment" },
// { "loop_0", "Acyclic tasks" },
// { "loop_1", "Period tasks" },
// { "ec_1", "Mission started" },
// { "ec_4", "Mission started" },
// { "ec_6", "Mission started"}};
{ "ms_1", "i18n_server.CommonResources.ms_1_n81i" },
{ "ms_2", "i18n_server.CommonResources.ms_2_n81i" },
{ "ms_3", "i18n_server.CommonResources.ms_3_n81i" },
{ "ms_30", "i18n_server.CommonResources.ms_30_n81i" },
{ "ms_31", "i18n_server.CommonResources.ms_31_n81i" },
{ "ms_32", "i18n_server.CommonResources.ms_32_n81i" },
{ "ms_4", "i18n_server.CommonResources.ms_4_n81i" },
{ "ms_5", "i18n_server.CommonResources.ms_5_n81i" },
{ "ms_6", "i18n_server.CommonResources.ms_6_n81i" },
{ "ms_7", "i18n_server.CommonResources.ms_7_n81i" },
{ "mt_1", "i18n_server.CommonResources.mt_1_n81i" },
{ "mt_4", "i18n_server.CommonResources.mt_4_n81i" },
{ "mt_6", "Upgrade deployment" },
{ "loop_0", "i18n_server.CommonResources.loop_0_n81i" },
{ "loop_1", "i18n_server.CommonResources.loop_1_n81i" },
{ "ec_1", "i18n_server.CommonResources.ec_1_n81i" },
{ "ec_4", "i18n_server.CommonResources.ec_1_n81i" },
{ "ec_6", "i18n_server.CommonResources.ec_1_n81i"}};
public Object[][] getContents() {
return contents;
}
}

View File

@@ -0,0 +1,159 @@
package com.nms.server.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import javax.swing.JOptionPane;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* 获取和保存myconfig信息的类
*
* @author ZGGG3
*
*/
public class Config {
private static Logger logger = Logger.getLogger(Config.class);
private static Properties properties;
private static String url = null;
public static Config config = Config.getInstance();
// private static ResourceBundle resource;
public static String getSystemDir() {
return System.getProperty("user.dir");
}
/**
* 单例 初始化获取实例
*
* @return
*/
public static Config getInstance() {
if (config == null)
return new Config();
return config;
}
/**
* 单例 重新读取文件已获取参数
*
* @return
*/
public static Config reinitialize() {
config = null;
return new Config();
}
/**
* 构造函数私有,用于单例实例
*/
private Config() {
//执行参数更新及检查
ConfigUpdate.getInstance();
//加载配置文件
URL urlObj = Config.class.getClassLoader().getResource("myconfig.properties");
// resource = ResourceBundle.getBundle(DefaultConfig.class.getName());
if(urlObj==null){
// JOptionPane.showMessageDialog(null, "未找到参数配文件!\n请运行"+Constants.COMMON_CONFIG_EXE_NAME+"初始化参数配置", "错误", JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog(null, "Parameter configuration file not found! \nPlease run "+Constants.COMMON_CONFIG_EXE_NAME+"initialization parameter configuration", "Error", JOptionPane.ERROR_MESSAGE);
// JOptionPane.showMessageDialog(null, "i18n_server.Config.initConfig_n81i"+Constants.COMMON_CONFIG_EXE_NAME+"i18n_server.Config.initConfig.init_n81i", "i18n_server.Config.error_n81i", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}else{
url = urlObj.getPath().replaceAll("%20", " ");
}
properties = new Properties();
try {
properties.load(new FileInputStream(url));
} catch (IOException e) {
logger.error("Reading properties file error"+"",e);
}
}
/**
* 根据name获取value
*
* @param name
* @return
*/
public static Boolean getBoolan(String name,Boolean defaultValue) {
try {
String val = getString(name,defaultValue==null?null:defaultValue.toString());
return StringUtils.isEmpty(val)? null : Boolean.valueOf(val);
} catch (Exception e) {
logger.error("Digital formatting error", e);
}
return null;
}
/**
* 根据name获取value
*
* @param name
* @return
*/
public static Integer getInteger(String name,Integer defaultValue) {
try {
String val = getString(name,defaultValue==null?null:defaultValue.toString());
return StringUtils.isEmpty(val)? null : Integer.parseInt(val);
} catch (Exception e) {
logger.error("Digital formatting error", e);
}
return null;
}
/**
* 根据name获取value
*
* @param name
* @return
*/
public static String getString(String name,String defaultValue) {
String str = null;
/* 获取参数值:先从资源文件取值,如果为空,则从默认参数配置中取值 */
str = properties.getProperty(name,defaultValue);
if(StringUtils.isNotEmpty(str)){
str = str.trim();
}else{
logger.warn("Resource configuration file abnormality >> "+name+" Value is empty");
}
return str;
}
/**
* 向资源配置文件中添加或更新一个键值对
*
* @time Jul 7, 2011-3:52:45 PM
* @param key
* @param value
*/
public static void setValueByName(String key, String value) {
// 添加或更新键值对
properties.setProperty(key, value);
try {
// 保存到文件
if (url != null && !"".equals(url)) {
String fileName = url.substring(
url.lastIndexOf(File.separator), url.length());
properties.store(new FileOutputStream(url), fileName);
}
} catch (FileNotFoundException e) {
logger.error("The properties file Set Value file does not find ERROR "+"",e);
} catch (IOException e) {
logger.error("Properties file Set Value set value ERROR"+"",e);
}
}
/*
// 测试主函数
public static void main(String[] args) {
Config cfg=new Config();
String oid="mission.file.download.dir";
System.out.println("---------"+cfg.getString(oid));
}
*/
}

View File

@@ -0,0 +1,264 @@
package com.nms.server.common;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* 获取和保存myconfig信息的类
*
* @author ZGGG3
*
*/
public class ConfigUpdate {
private static Logger logger = Logger.getLogger(ConfigUpdate.class);
private static Properties properties;
private static String url = null;
public static List<String> proList = new LinkedList<String>();
public static ConfigUpdate config = ConfigUpdate.getInstance();
private static ResourceBundle resource;
/**
* 单例 初始化获取实例
*
* @return
*/
public static ConfigUpdate getInstance() {
if (config == null)
return new ConfigUpdate();
return config;
}
/**
* 单例 重新读取文件已获取参数
*
* @return
*/
public static ConfigUpdate reinitialize() {
config = null;
return new ConfigUpdate();
}
/**
* 构造函数私有,用于单例实例
*/
private ConfigUpdate() {
// Thread.currentThread().setName("更新参数");
resource = ResourceBundle.getBundle(UpdateParams.class.getName());
URL urlObj = ConfigUpdate.class.getClassLoader().getResource("myconfig.properties");
if(urlObj!= null){
url = urlObj.getPath().replaceAll("%20", " ");
}else{
url = new File(System.getProperty("user.dir")).getParentFile().getAbsolutePath()+"/conf/myconfig.properties";
}
logger.info("参数文件:"+url);
BufferedReader reader = null;
FileInputStream fis = null;
properties = new Properties();
try {
File file = new File(url).getAbsoluteFile();
/*外部资源文件是否已存在*/
if(file.exists()){ // 存在 则读取已存在的文件信息 ,将内部资源文件参数更新到外部资源文件中
fis = new FileInputStream(file);
properties.load(fis);
//判断是否更新properties
String updateFlag = properties.getProperty(UpdateParams.CONFIG_UPDATE_FLAG,"-1");
if(updateFlag.equals(resource.getString(UpdateParams.CONFIG_UPDATE_FLAG))){ //配置文件已经更新,退出操作
return;
}
}else{ // 不存在无操作
return ;
}
//更新参数
/*Enumeration<String> en = resource.getKeys();
while (en.hasMoreElements()) {
String elem = (String) en.nextElement();
String value = properties.getProperty(elem);
if(StringUtils.isBlank(value)){
properties.setProperty(elem, configRb.getString(elem));
}
}
*/
fis.close();
fis = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(fis,Charset.forName("utf-8")));
String str =null;
while((str = reader.readLine() )!=null){
proList.add(str);
}
save();
} catch (Exception e) {
logger.error("Reading properties file error"+"",e);
}finally{
try {
if(reader!= null)reader.close();
if(fis!= null)fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 根据name获取value
*
* @param name
* @return
*/
public static Integer getInteger(String name) {
try {
return Integer.parseInt(getString(name));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据name获取value
*
* @param name
* @return
*/
public static String getString(String name) {
String str = null;
try {
str = properties.getProperty(name);
if(StringUtils.isNotEmpty(str)){
str = str.trim();
}else{
logger.warn("Resource configuration file abnormality >> "+name+" Value is empty");
}
} catch (Exception e) {
logger.error("Resource configuration file abnormality", e);
}
return str;
}
/**
* 向资源配置文件中添加或更新一个键值对
*
* @time Jul 7, 2011-3:52:45 PM
* @param key
* @param value
*/
public static void setValueByName(String key, String value) {
// 添加或更新键值对
String oldValue = properties.getProperty(key);
properties.setProperty(key, value);
}
/**
* 保存到文件
* @time Jan 6, 2013-1:24:07 PM
*/
public static void save() {
BufferedWriter writer = null;
try {
//将properties中的值更新到proList中
Enumeration<String> en = resource.getKeys();
while (en.hasMoreElements()) {
String elem = (String) en.nextElement();
String value = resource.getString(elem);
boolean addFlag = true;
try {
for (int i = 0; i < proList.size(); i++) {
String str = proList.get(i);
if(StringUtils.isEmpty(str)){continue;}
if(str.split("=", 2)[0].trim().equals(elem)){
// str = elem+" = "+value;
// proList.set(i, str);
addFlag = false;
// logger.info("参数更新:"+elem+" = "+(StringUtils.isBlank(value)?"":value));
break ;
}
}
if(addFlag){
proList.add(elem+" = "+value);
logger.info("参数新增:"+elem+" = "+(StringUtils.isBlank(value)?"":value));
}
} catch (Exception e) {
logger.error("Properties file Set Value set value ERROR "+elem,e);
}
}
File file = new File(url).getAbsoluteFile();
if(!file.exists()){
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
file.createNewFile();
}
//将文件信息写入到文件中
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),Charset.forName("utf-8")));
Iterator<String> it = proList.iterator();
while (it.hasNext()) {
String elem = (String) it.next();
writer.write((elem==null?"":elem)+"\r\n");
}
writer.flush();
} catch (Exception e) {
System.err.println("资源配置文件取值异常");
e.printStackTrace();
}finally{
try {
if(writer!= null ){
writer.close();
writer = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 向资源配置文件host_uuid.properties中更新UUID键值
*/
/*public static void saveResource(String value) {
try {
Properties properties = new Properties();
if (uuidUrl != null && !"".equals(uuidUrl)) {
properties.load(new FileInputStream(uuidUrl));
// 添加或更新键值对
properties.setProperty(AGENT_HOST_UUID_KEY, value);
// 保存到文件
properties.store(new FileOutputStream(uuidUrl), "");
}
properties.clear();
if(value != null && !"".equals(value)){
Contants.AGENT_HOST_UUID = Long.parseLong(value);
}
} catch (Exception e) {
logger.error(e);
}
}*/
/* public static void pl(Object obj){
System.out.println(obj==null?null:obj.toString());
}*/
/* public static void main(String [] args){
// pl(log4jRb.getString("log4j.appender.logfile.File"));
// pl(configRb.getString("email.flag"));
}*/
}

View File

@@ -0,0 +1,844 @@
package com.nms.server.common;
import java.io.File;
import java.net.SocketException;
import javax.net.ssl.SSLServerSocket;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.util.LocalAddress;
import com.zhtelecom.common.snmp.SNMPTarget;
/**
* DataController 公共常量和配置文件参数信息类
* @date Jan 5, 2012 11:38:45 AM
* @author ZhangGang
*
*/
public class Constants {
private static final Logger logger = Logger.getLogger(Constants.class);
// private static ResourceBundle resource = ResourceBundle.getBundle(DefaultConfig.class.getName());
// #---Common-------
/**
* DC初始化标识
*/
public static boolean flag_init = false;
/**
* 全局 邮件信息保存参数
* 1保存 0 不保存 DC端默认为0 缺省配置为1
* PS:当同步web端邮件功能配置时可以创建发送通讯变更该变量信息
*/
public static int flag_email = 0; //Email 信息创建标示 1创建 0 不创建 DC端默认为0
public static final String ERROR_INFO_RESOVE_MANAGER = "errorInfoResoveManager"; //错误信息解析入库管理线程 标识, futureMap 中的Key值
public static final String ERROR_INFO_RESOVE = "errorInfoResove"; //错误信息解析入库操作线程 标识, futureMap 中的Key值
public static final Integer ERROR_INFO_RESOVE_PERIOD; //监测数据解析周期(秒)
public static final String MAILING_MANAGER = "errorInfoResoveManager"; //错误信息解析入库管理线程 标识, futureMap 中的Key值
public static final String MAILING_THREAD = "errorInfoResove"; //错误信息解析入库操作线程 标识, futureMap 中的Key值
// public static final Integer MAILING_PERIOD; //监测数据解析周期(秒)
public static final String DETEC_DATA_RESOVE_MANAGER = "detecDataResoveManager";
// public static final String DETEC_DATA_COLLECT_MANAGER = "detecDataCollectManager";//DC端主动收集监测数据
public static final String DATA_COLLECT_MANAGER = "dataCollectManager";//DC端主动收集数据监测数据、任务结果、回传文件
public static final String ERROR_NODE_DATA_COLLECT_MANAGER = "errorNodeDataCollectManager";//异常节点管理线程
public static final String NO_DETECT_DATA_NODE_DATA_COLLECT_MANAGER = "noDetectDataNodeDataCollectManager";//无监测数据节点管理线程
public static final String EMAIL_START_THREAD = "emailStartThread";//DC端刷新邮件启动标识线程
public static final String NONRLTTASK_RESULT_COLLECT_MANAGER = "nonRltTaskResultCollectManager";//DC端主动收集数据执行完成但无任务结果的任务的结果信息
public static final String DETEC_DATA_RESOVE = "detecDataResove"; //监测数据解析线程 标识, futureMap 中的Key值
public static final String OVERRUN_DATA_RESOVE_MANAGER = "overrunDataResove"; //硬盘数据解析入库管理线程 标识, futureMap 中的Key值
public static final String OVRERUN_DETEC_DATA_RESOVE = "overrunDetecDataResove"; //硬盘监测数据解析线程 标识, futureMap 中的Key值
public static final String OVRERUN_WARNING_DATA_RESOVE = "overrunWarningDataResove"; //硬盘告警数据解析线程 标识, futureMap 中的Key值
public static final String OVRERUN_RESULT_DATA_RESOVE = "overrunResultDataResove"; //硬盘任务结果数据解析线程 标识, futureMap 中的Key值
public static final String DELETE_TMP_FILES_MANAGER = "deteleTmpFilesManager";//删除log等临时文件
public static final String DETEC_DATA_COLLECT = "detecDataCollect"; //监测数据主动收集线程 标识, futureMap 中的Key值-暂未使用
public static final String DATA_COLLECT = "dataCollect"; //监测数据主动收集线程 标识, futureMap 中的Key值
public static final String NO_DETECT_DATA_COLLECT = "noDetectDataCollect"; //异常监测数据主动收集线程 标识, futureMap 中的Key值
public static final String NONRLTTASK_RESULT_COLLECT = "nonRltTaskResultCollect"; //无任务结果的任务的结果数据的主动收集线程 标识, futureMap 中的Key值
public static final String ALARM_DATA_RESOVE_MANAGER = "alarmDataResoveManager";
public static final String ALARM_DATA_RESOVE = "alarmDataResove"; //告警数据解析线程 标识, futureMap 中的Key值
public static final String MISSION_THREAD = "missionThread";
public static final String DELETE_TMP_FILES = "deleteTmpFiles"; //删除log等文件线程 标识, futureMap 中的Key值
public static final String UNZIP_FILE_MANAGER = "unZipFileManager";
public static final String UNZIP_FILE = "unZipFile";
public static final String SUCCESS = "success";
public static final String MISSION_RESULT_RESOVE_MANAGER = "missionResultResoveManager";
public static final String MISSION_RESULT_RESOVE = "missionResultResove";
public static final String MISSION_FILE_UPLOAD = "missionFileUpload";
public static final String CHANGE_OPERATIONS_MANAGER = "changeOperationsManager";
public static final String CHANGE_OPERATIONS = "changeOperations";
public static final String DETECTION_INFO_TABLE_NAME = "detection_info_new";//监测数据表名
public static final String DETECTION_WARNING_TABLE_NAME = "detection_info_warning";//告警数据表名
public static final Boolean DETECSELFTHREAD_FLAG ;//DetecSelfThread 开关
public static final String DETECTI_SELF_THREAD_NAME = "DetecSelfThread";//监测数据表名
public static final Long DETECSELFTHREAD_PERIOD;//监测间隔,单位:秒
public static final Long DETECSELFTHREAD_INITIALDELAY;//监测延迟启动时间,单位:秒
public static final String DETECTI_DATA_COLLECT_THREAD_NAME = "DetecDataCollectThread";//监测数据收集线程是否正常运行
public static final String RESET_SERVER_THREAD_NAME = "ResetServerThread";//告警数据表名
public static final String DB_CONNECTION_THREAD_NAME = "DbConnectionThreadName";//数据库连接线程名
public static final String EMAIL_TYPE_IDENTITY = "emailflag";//是否发送邮件的参数配置标识
// public static final String NO_DETECTDATA_STATUS_INFO = "数据收集超时,未获取监测数据";//DC收集数据无监测数据时默认的提示信息
// public static final String NO_DETECTDATA_STATUS_INFO = "Data collection is out of time and no monitoring data is obtained";//DC收集数据无监测数据时默认的提示信息
public static final String NO_DETECTDATA_STATUS_INFO = "i18n_server.Constants.NO_DETECTDATA_STATUS_INFO_n81i";//DC收集数据无监测数据时默认的提示信息
// #---Common-------
public static final String COMMON_CONFIG_EXE_NAME ; //参数配置程序名称
public static final String COMMON_TEXT_CODING ; //公用字符流编码格式
public static final String COMMON_DATE_FORMAT; //公用日期格式化标准格式DEFAULT_DATE_FORMAT
public static final String COMMON_DATAS_DIR;
public static final Integer COMMON_SNMP_VERSION = SNMPTarget.VERSION2C ; //公用字符流编码格式
public static final String COMMON_DATA_SPLIT = "\\$@\\$"; //主动告警信息解析标识串-用于分隔字符
public static final String COMMON_DATA_POINT = "$@$"; //主动告警信息解析标识串-用于连接字符
public static final String COMMON_TEMP_DIR ; //安装程序下临时目录
public static final String COMMON_RUNTIME_PID_FILE ; //程序运行时PID文件
public static final String SYSTEM_PATH; //DataController应用启动主目录
public static final String SYSTEM_INET_ADDRESS;
public static final Integer SYSTEM_CLEAR_PERIOD = 24; // [1,99999999]hours 每SYSTEM_CLEAR_PERIOD系统清理一次
public static final Integer SYSTEM_CLEAR_TIME = 20; // [00:00:00,24:00:00] 每天某时间(精确到小时),执行系统数据清理
public static final Integer MAX_NETWORK_BANDWIDTH; //证书有效期(天)
// #---Executor /ThreadPool-------
public static final Integer EXECUTOR_SOCKET_THREAD_SIZE ; //线程池 通讯线程最大数
public static final Integer EXECUTOR_DATA_RESOVE_THREAD_SIZE ;
public static final Integer EXECUTOR_SCHEDULED_THREAD_SIZE ; //线程池 周期性线程最大数
// #---Change Operations-------
public static final Integer CHANGE_OPERATIONS_PERIOD ;
public static final Integer CHANGE_RELEASE_SEMAPHORE_MAX ;
// #---Detection Resolve-------
// public static final Integer DETEC_TIMEOUT_ALARM_PERIOD_TIMES; //监测数据告警周期数
public static final Integer DETEC_DATA_RESOLVE_PERIOD; //缓存监测数据解析周期(秒)
public static final Integer DISK_DATA_RESOLVE_PERIOD; //硬盘监测数据解析周期(秒)
public static final int CHECK_DETEC_DATA_OVERRUN = 5; //检查 监测数据量是否过大(导致无法及时、完整的入库) 的次数即5*DETEC_DATA_RESOLVE_PERIOD
public static final int CHECK_WARNING_DATA_OVERRUN = 5; //检查 告警数据量是否过大(导致无法及时、完整的入库) 的次数即5*告警数据解析周期
public static final int CHECK_RESULT_DATA_OVERRUN = 5; //检查 任务结果数据量是否过大(导致无法及时、完整的入库) 的次数即5*任务结果解析周期
public static final int REFRESH_EMAIL_FLAG_PEROID = 300; //刷新邮件功能启用标示周期:5分钟
// public static final Integer DETEC_DATA_COLLECT_PERIOD; //监测数据主动收集周期
public static final Integer DATA_COLLECT_PERIOD; //DC端主动收集数据监测数据、任务结果、回传文件周期
public static final Integer ERROR_NODE_DATA_COLLECT_PERIOD; //DC端主动收集数据监测数据、任务结果、回传文件周期(针对异常节点)
public static final Integer DATA_COLLECT_DAILY; //DC端主动收集数据等待时间
public static final Integer ERROR_NODE_DATA_COLLECT_DAILY; //DC端主动收集数据等待时间(针对问题节点)
public static final Integer SINGLE_NODE_DETECT_TIMEOUT; //DC端主动监测单节点超时时间
public static final Integer DETEC_RELEASE_SEMAPHORE_MAX;
public static final String DETEC_PING_STR; //ping配置名称 与数据库监测类别表 ping对应 谨慎一致修改
public static final String DETEC_NMSC_STR; //NMSClient端通信握手配置名称 与数据库监测类别表 NMSClient对 应谨慎一致修改
public static final String DETEC_SNMP_STR;
public static final String DETEC_SWITCH_STR;
public static final String DETEC_SYSTEMINFO_STR;
public static final String DETEC_SYSTEM_STR;
public static final String DETEC_SYSTEMDATE_STR;
public static final String DETEC_IFXTABLE_STR;
public static final String ALARM_SNMP_TRAP_STR;
public static final Integer DELETE_TMP_FILES_PERIOD; //删除log等临时文件的线程执行间隔时间
public static final Integer KEEP_FILE_DAYS; //保留log等临时文件的天数
// #---Alarm Resolve-------
public static final Integer ALARM_DATA_RESOLVE_PERIOD; //告警数据解析周期
public static final Integer NONRLTTASK_RESULT_COLLECT_PERIOD; //DC端主动收集数据执行完成但无任务结果的任务的结果信息周期
// #---Web-------
// public static final String WEB_DOWNLOAD_URL; //NMSWeb 文件下载路径
public static final String WEB_SOCKET_IP; //指定非加密通讯通信IP
public static final Integer WEB_SOCKET_PORT; //指定非加密通讯通信端口
// #---Mission Control-------
public static final Integer MISSION_FIRST_START = 0;//10; //任务下发线程启动时间 计算式agent任务结果上传周期+MISSION_RESULTS_SAVE_PERIOD/MISSION_RESULTS_SAVE_PERIOD 取其进1整数*MISSION_RESULTS_SAVE_PERIOD+MISSION_RESULTS_SAVE_START+1
public static final Integer MISSION_RESULTS_SAVE_START = 60; //任务结果入库线程启动时间 秒
public static final Integer MISSION_RESULTS_SAVE_PERIOD = 120; //任务结果入库线程循环周期 秒
public static final Integer MISSION_CHECK_NEW_START = 10;//10; //新任务检查线程启动在first_start之后
public static final Integer MISSION_CHECK_NEW_PERIOD = 300; //周期间隔可以稍长
public static final Integer TASK_RLT_COLLECT_RESERVED_PERIOD = 600; //任务结果收集估计预留时间,单位秒
public static final Integer MISSION_LOOP_PRESET_NUMBER; //周期预置数
// public static final String MISSION_LOOP_FINISHING_DAILY; //周期任务 完成状态变更时间(未使用)
public static final Integer MISSION_UPGRADE_DAILY; //DataController应用启动主目录
// #---Mission release-------
public static final Integer MISSION_RELEASE_SEMAPHORE_MAX; ////信号计数,每申请一个信号,创建两个线程,一个任务执行线程,一个结果接收线程
public static final Integer MISSION_RELEASE_TIMES; //下发任务尝试次数
public static final Integer MISSION_RELEASE_PERIOD; //下发任务间隔周期
// #---Mission File-------
public static final String MISSION_FILE_DOWNLOAD_DIR ; //下发任务文件目录(推送文件用)
public static final Integer MISSION_FILE_DOWNLOAD_DELAY; //上传最大等待时间(秒)
public static final String MISSION_FILE_UPLOAD_DIR ; //上传回传文件目录(推送文件用)
public static final Integer MISSION_FILE_UPLOAD_PERIOD; //上传周期(分)
// #---Email-------
// public static final String EMAIL_ADDRESS ;
// public static final String EMAIL_USERNAME ;
// public static final String EMAIL_PASSWORD;
// public static final String EMAIL_HOST ;
// #---DataBase-------
public static final String DB_POOL_TYPE;//连接池类型
public static final String DB_DRIVER; //数据库链接驱动
public static final String DB_USER_NAME; //数据库链接用户名
public static final String DB_PASSWORD; //数据库链接密码
public static final String DB_URL; //数据库链接地址
public static final String DB_DATE_FORMAT; //数据库日期格式化格式
public static final Integer DB_EXECUTE_BATCH; //数据库批处理更新操作单次最大处理量
public static final Integer DB_STATEMENT_EXECUTE_TIMEOUT ;
public static final Integer DB_POOL_PARTITION_COUNT ; //连接池 设置分区 缺省值 3
public static final Integer DB_POOL_CONNECTIONS_PER_PARTITION_MAX; //设置每个分区中的最大连接数 缺省值 30
public static final Integer DB_POOL_CONNECTIONS_PER_PARTITION_MIN ; //设置每个分区中的最小连接数 缺省值 10
public static final Integer DB_POOL_ACQUIRE_INCREMENT; //当连接池中的连接耗尽的时候 BoneCP一次同时获取的连接数 缺省值3
public static final Integer DB_POOL_IDLE_CONNECTION_TEST_PERIOD ; //设置每60秒检查数据库中的空闲连接数 单位 秒 缺省值 60
public static final Integer DB_POOL_IDLE_MAX_AGE ; //设置连接空闲时间 单位 分钟 缺省值 240
public static final Integer DB_GET_CONNECTION_TIMEOUT ; //设置获取连接超时时间默认30秒
public static final Integer DB_POOL_MAX_CONNECTION_AGE;
public static final Integer DB_POOL_RELEASE_HELPER_THREADS ; //连接释放处理 缺省值3
public static final Integer DB_POOL_STATEMENT_RELEASE_HELPER_THREADS;
public static final Integer DB_POOL_QUERY_EXECUTE_TIME_LIMIT ; //sql执行超时时间
public static final boolean DB_POOL_LOG_STATEMENT_ENABLE;
// #---DATA-------
/*
public static final String DATA_DIR; //DataController端未解析数据文件存放目录
public static final String DATA_BACKUP_RIGHT_DIR; //DataController端解析正确的数据文件备份目录
public static final String DATA_BACKUP_WRONG_DIR; //DataController端解析错误的数据文件备份目录
*/
// #---ZIP File-------
public static final String ZIP_FILE_DETECT_DATA_DIR;
public static final String ZIP_FILE_TASK_RESULT_DIR;
public static final String ZIP_FILE_TASK_RETURN_DIR;
// #---ZIP File Resove-------
public static final String ZIP_RESOVE_DETECT_DATA_DIR;
public static final String ZIP_RESOVE_TASK_RESULT_DIR;
public static final String ZIP_RESOVE_TASK_RETURN_DIR;
public static final String ERROR_DETEC_FILE_DIR;
public static final int ERROR_DETEC_FILE_DIR_FILE_SIZES = 500;
public static final String DEFAULT_NODE_GROUP_NAME;
//20160909 单个节点默认收集后加入监测数据列表的最大监测数据条数如果一次收集超过设置的条数则存入dc_overrun/detect/zip_resove中避免解析时数据过多导致内存溢出
public static final int MAX_COLLECT_RESOVE_DETECT_DATA_NUM;
//20160912 内存中监测数据的条数超过MAX_DETECT_DATA_RESOVE_LIMIT_NUM则不再向内存中添加监测数据而是暂存硬盘待之后解析入库避免内存溢出,默认10万
public static final int MAX_DETECT_DATA_RESOVE_LIMIT_NUM;
// #---overrun detect data file path-------
public static final String OVERRUN_DETEC_FILE_DIR;//超出处理能力的监测数据文件存放路径
// #---overrun warning data file path-------
public static final String OVERRUN_WARNING_FILE_DIR;//超出处理能力的告警数据文件存放路径
// #---overrun result data file path-------
public static final String OVERRUN_RESULT_FILE_DIR;//超出处理能力的任务结果数据文件存放路径
// 第三方监测脚本
public static final String PLUGIN_SCRIPT_FILE_DIR; // 第三方检测脚本存储路径
// #---SNMP-------
public static final Integer SNMP_TRAP_THREAD_POOL_SIZE; //指定SNMP 共同体名称
public static final Integer SNMP_CLIENT_PORT; //指定SNMP client get端口
public static final Integer SNMP_TRAP_PORT; //指定SNMP trap get端口
public static final String SNMP_COMMUNITY; //指定SNMP 共同体名称
/* public static final String SNMP_MIB_DIR ; //
public static final String SNMP_CLASS_PATH ;
public static final String SNMP_CLASS_DIR ;
*/
public static final String SNMP_CLASS_PACKAGE ;
public static final Integer SNMP_V3_SECURITY_LEVEL ; // ##--SNMP 加密认证等级
public static final String SNMP_V3_SECURITY_NAME ; // ##--SNMP 加密认证用户 用户名
public static final String SNMP_V3_AUTH_PROTOCOL ; // ##--SNMP 认证协议方式
public static final String SNMP_V3_PRIV_PROTOCOL ; // ##--SNMP 加密协议方式
public static final String SNMP_V3_AUTH_PASSPHRASE ; // ##--SNMP 认证密码明文
public static final String SNMP_V3_PRIV_PASSPHRASE ; // ##--SNMP 加密密码明文
// #---SSL Init-------
public static final Integer SSL_SO_TIMEOUT; //SSL加密通信类型
public static final String SSL_TYPE; //SSL加密通信类型
public static final String SSL_KEYSTORE_TYPE; //SSL加密通信加密密匙库类型
public static final Integer SSL_SERVER_PORT; //SSL加密通信接收端口
public static final Integer SSL_CLIENT_PORT; //SSL加密通信请求端口
public static final String SSL_DIR ; //证书存放目录
public static final String SSL_SERVER_EXPORT ; //程序初始化服务端证书导出名称
public static final String SSL_CLIENT_EXPORT ; //程序初始化客户端通用证书导出名称
// public static final String SSL_INIT_SERVER_KEY; //程序初始化服务端证书 (安装时用)
// public static final String SSL_INIT_SERVER_KEY_PSW ; //程序初始化服务端证书密码
// public static final String SSL_INIT_CLIENT_KEY ; //程序初始化客户端通用证书 (安装时用)
// public static final String SSL_INIT_CLIENT_KEY_PSW ; //程序初始化客户端证书密码
// #---SSL Server-------
public static final String SSL_SERVER_STORE ; //通讯接收端证书密匙库
public static final String SSL_CLIENT_STORE ; //通讯请求端证书密匙库
public static final String SSL_SERVER_STORE_PSW ; //通讯接收端证书密匙库密码
public static final String SSL_SERVER_TRUST; //通讯接收端证书公钥库
public static final String SSL_CLIENT_TRUST; //通讯请求端证书公钥库
public static final String SSL_SERVER_TRUST_PSW; //通讯接收端证书公钥库密码
public static final String SSL_SERVER_KEY_NEW; //通讯接收端新密匙
public static final String SSL_SERVER_KEY_NEW_PSW;
public static final String SSL_SERVER_KEY_OLD ; //通讯接收端旧密匙
public static final String SSL_SERVER_KEY_OLD_PSW; //通讯接收端旧密匙密码
public static final String SSL_CLIENT_KEY ; //通讯请求端密匙
public static final String SSL_CLIENT_KEY_PSW ; //通讯请求端密匙密码
public static final Integer SSL_KEY_VALIDITY; //证书有效期(天)
// #---SSL Bat-------
// public static final String SSL_BAT_IMPORT ;
// public static final String SSL_BAT_GENKEY_EXPORT ;
// public static final String SSL_BAT_SERVER_INIT ;
//监测执行失败时,握手监测-默认的告警级别:0
public static final int DETECT_FAIL_NMSC_POLICE_LEVEL;//0
//监测执行失败时,握手监测-默认的紧急状态:0紧急
public static final int DETECT_FAIL_NMSC_POLICE_EMERGENT;//0
//监测执行失败时,非握手监测-默认的告警级别1级
public static final int DETECT_FAIL_NON_NMSC_POLICE_LEVEL;//1
//监测执行失败时,非握手监测-默认的紧急状态:非紧急
public static final int DETECT_FAIL_NON_NMSC_POLICE_EMERGENT;//1
//NC主动告警默认为紧急state=-2时默认的告警级别:0级
public static final String NC_ALARM_POLICE_LEVEL;//1
/**监测信息状态集合
* [0] -2 监测线程异常
* [1] -1 监测任务失败
* [2] 0 监测信息异常
* [3] 1 监测信息正常
* [4] 2 监测线程正常
* */
private static final Integer [] DETECTION_INFO_STATE = new Integer[]{-2,-1,0,1,2};
/**监测线程异常 -2*/
public static final Integer DETECTION_INFO_ALARM_WRONG = DETECTION_INFO_STATE[1];
/**监测线程正常 2*/
public static final Integer DETECTION_INFO_ALARM_RIGHT = DETECTION_INFO_STATE[3];
/**监测任务失败 -1*/
public static final Integer DETECTION_INFO_DETEC_ERROR = DETECTION_INFO_STATE[1];
/**监测信息异常 0*/
public static final Integer DETECTION_INFO_DETEC_WRONG = DETECTION_INFO_STATE[2];
/**监测信息正常 1*/
public static final Integer DETECTION_INFO_DETEC_RIGHT = DETECTION_INFO_STATE[3];
// public static final String ERROR_CODE_CREATE_SOCKET_ERROR= "CreateSocketError";
// public static final String ERROR_CODE_CREATE_SOCKET_ERROR= "CreateSocketError";
// public static final String ERROR_CODE_CREATE_SOCKET_ERROR= "CreateSocketError";
// public static final String ERROR_CODE_CREATE_SOCKET_ERROR= "CreateSocketError";
// public static final String ERROR_CODE_CREATE_SOCKET_ERROR= "CreateSocketError";
// public static final String ERROR_CODE_CREATE_SOCKET_ERROR= "CreateSocketError";
public static final String ERROR_CODE_CREATE_SOCKET= "CreateSocketError";
public static final String ERROR_CODE_SOCKET_RUNTIME= "DCSocketRuntimeError";
public static final String ERROR_CODE_SOCKET_SERVER_START = "DCSocketServerStartError";
public static final String ERROR_CODE_SOCKET_SERVER_RUNTIME = "DCSocketServerRuntimeError";
public static final String ERROR_CODE_DB_CONNECT= "DBConnectError";
public static final String ERROR_CODE_DATA_COLLECT= "DataCollectError";
// public static final String ERROR_DESC_DATA_COLLECT= "数据收集管理线程停止运行";
// public static final String ERROR_DESC_DATA_COLLECT= "The data collection management thread stopped running";
public static final String ERROR_DESC_DATA_COLLECT= "i18n_server.Constants.ERROR_DESC_DATA_COLLECT_n81i";
// public static final String ERROR_DESC_DATA_COLLECT_NO_RUN= "数据收集管理线程未启动";
// public static final String ERROR_DESC_DATA_COLLECT_NO_RUN= "Data Collection Management thread did not start";
public static final String ERROR_DESC_DATA_COLLECT_NO_RUN= "i18n_server.Constants.ERROR_DESC_DATA_COLLECT_NO_RUN_n81i";
public static final long ERROR_INFO_SATAE_ERROR = 1;//异常
public static final long ERROR_INFO_SATAE_RIGHT = 0;//已解决,手动置为已解决的
public static final long ERROR_INFO_SATAE_RIGHT_AUTO = 2;//已恢复,自己恢复的
public static final int PORT_ALARM_LEVEL;//端口异常默认的告警级别5
public static final int PORT_ALARM_EMERGENT;//端口异常默认的紧急状态1非紧急
// #---Test Flag-------
public static final Integer FLAG_ZIP;
// public static final Integer FLAG_DETEC_TIMEOUT;
public static final Integer FLAG_DETEC_RESOVE;
public static final Integer FLAG_ERROR_INFO;
public static final Integer FLAG_FILES_READER_RESOVE;
public static final Integer FLAG_DATA_COLLECT;//数据收集标志(是否启动数据收集管理线程)
public static final Integer FLAG_HANDWALK_SSH;//握手时是否进行ssh判断
public static final Integer FLAG_DATA_COLLECT_ONLY_HANDSHAKE;//数据收集线程里只握手,不收集数据
public static final Integer FLAG_NONRLTTASK_RESULT_COLLECT;//执行完成,但无任务结果的任务的结果信息的收集标志
public static final Integer FLAG_DELETE_TMP_FILES;//删除日志等文件标识
public static final Integer FLAG_FILE_UPLOAD;
public static final Integer FLAG_CHANGE_OPERATIONS;
public static final Integer FLAG_PING;
public static final Integer FLAG_NMSC;
public static final Integer FLAG_SNMP;
public static final Integer FLAG_SWITCH;
public static final Integer FLAG_SYSTEMDATE;
public static final Integer FLAG_MISSION;
public static final Integer FLAG_MISSION_RESULT;
/*public static final Integer FLAG_RESOVE_READ_FILE;
public static final Integer FLAG_RESOVE_RESOVE_FILE;
public static final Integer FLAG_MOVE_FILE;*/
public static final Integer FLAG_RESOVE_COMMIT_DB;
public static final Integer FLAG_ALARM_RESOVE;
public static final Integer FLAG_TRAP;
public static final Integer FLAG_EMAIL_START;//是否启用邮件发送功能
//20151229 hyx
public static final Integer FLAG_DETECT_DATA_SAVE_DISK_RESOVE;//监测数据过多时是否保存硬盘:1保存
public static final Integer FLAG_WARN_DATA_SAVE_DISK_RESOVE;//告警数据过多时是否保存硬盘:1保存
public static final Integer FLAG_ERROR_DATA_SAVE_DISK_RESOVE;//错误数据过多时是否保存硬盘:1保存
public static final Integer FLAG_TASK_RLT_SAVE_DISK_RESOVE;//任务结果过多时是否保存硬盘:1保存
public static final String OS_WIN = "win";
public static final String OS_LINUX = "linux";
public static SSLServerSocket sslServer = null;
public static int LEVEL_OF_EMERGENCY = 0;//紧急级别对应的level0紧急1-5非紧急
public static int VARCHAR_MAX_LENGTH = 4000-1;//oracle中varchar2类型的最大长度为4000个字节
public static Integer DETECTION_INFO_DATA_MAX_ROWS;//监测数据每多少条数据入库一次
public static int FETCH_SIZE;//如果不设置自动取的是10当网络情况不好的时候一次查询的数据较多的时候批量监测数据入库就会一次查出new表和端口表等的数据多达几万条就会多次从数据库取数据在网络上浪费时间因此这个值需要设置的大一些,但是这个值设置的越大占用的内存就越大所以一般设置50或者100是比较合适的
public static int SSH_CONNECT_TIMEOUT;
public static boolean IS_HANDEL_EXCEPTION_NODE = false;//正常收集线程是否处理异常节点的具体异常原因
//批量解析数据限制数量
public static final int BATCH_RESOVE_COUNT;
// public static final Integer FLAG_TEST;
// public static final Integer TEST_COMPUTER;
// public static final Integer TEST_SWITCH;
//static final 自变量的初始化
public static final String DB_TYPE;
public static final boolean IS_MYSQL;
//dc监测数据入库模式1由web 主控控制入库2自己主动入库3智能模式4数据上传
public static final Integer DETECT_INSERT_MODE;
public static final Integer WEB_NOTICE_INSERT_DETECT_OVER_TIMES ;// web通知监测入库超时次数只有 配置 DETECT_INSERT_MODE = 3 有效
/**
* 监测数据入库线程模式1单线程2双线程info,detail
*/
public static final int DETECT_INSERT_THREAD_MODE;
/**
* INFO入库线程运行模式1每隔 N秒 运行一次2间隔 N 秒运行一次
*/
public static final int DETECT_INFO_THREAD_MODE;
/**
* INFO入库线程 每隔 或间隔 时间 单位S
*/
public static final int DETECT_INFO_THREAD_TIME;
public static final int DETECT_INFO_THREAD_DELAY;
/**
* DETAIL入库线程运行模式1每隔 N秒 运行一次2间隔 N 秒运行一次
*/
public static final int DETECT_DETAIL_THREAD_MODE;
/**
* DETAIL入库线程 每隔 或间隔 时间 单位S
*/
public static final int DETECT_DETAIL_THREAD_TIME;
public static final int DETECT_DETAIL_THREAD_DELAY;
/**
* future key
*/
public static final String DETECT_INFO_THREAD_KEY = "DETECT_INFO_THREAD_KEY" ;
public static final String DETECT_DETAIL_THREAD_KEY = "DETECT_DETAIL_THREAD_KEY" ;
/**
* 监测数据解析线程
*/
public static final String DETECT_RESOVE_THREAD_KEY = "DETECT_RESOVE_THREAD_KEY" ;
public static final int NETTY_SERVER_FLAG;
public static final int NETTY_SERVER_PORT;
public static final boolean NETTY_SERVER_SSL;//是否使用加密通信
public static final int NETTY_IDLE_TIME;
public static final int NETTY_SO_BACKLOG;
/**
* 服务器握手监测 周期时间
*/
public static final int SERVER_NMSC_THREAD_INTERVAL;
public static final String NEXTVAL_FUNCTION_NAME ;
public static final String CURRVAL_FUNCTION_NAME ;
public static final Long HANDSHANK_DELAY_TIME;
static {
// InetAddress inetAddress = null;
// try {
// inetAddress = InetAddress.getLocalHost();
// } catch (UnknownHostException e) {
// logger.error("LocalHost InetAddress 获取失败",e);
// }
BATCH_RESOVE_COUNT=Config.getInteger("batch.resove.count",500);
// #---Common-------
SYSTEM_PATH = formatPath(Config.getSystemDir());
COMMON_CONFIG_EXE_NAME = Config.getString("common.config.exe.name","DCConfig.exe");
COMMON_TEXT_CODING = Config.getString("common.text.coding","UTF-8");
COMMON_DATE_FORMAT = Config.getString("common.date.format","yyyy-MM-dd HH:mm:ss");
COMMON_DATAS_DIR = Config.getString("common.datas.dir",SYSTEM_PATH+"/nmsdata");
COMMON_TEMP_DIR = Config.getString("common.temp.dir","temp");
COMMON_RUNTIME_PID_FILE = Config.getString("common.Runtime.pid","DataControllerPid.temp");
// if(inetAddress!= null){
// SYSTEM_INET_ADDRESS = StringUtils.isEmpty(Config.getString("system.inet.address"))
// ?inetAddress.getHostAddress().toString()
// :Config.getString("system.inet.address");
// }else {
String localIP = Config.getString("system.inet.address",null);
try {
String localIP2 = LocalAddress.getRealIp();
// if(StringUtils.isEmpty(localIP)){
// localIP = localIP2;
// logger.warn("配置IP【"+localIP+"】为空 程序获取IP【"+localIP2+"】将使用程序获取IP");
// }
if(!localIP.equals(localIP2)){
logger.warn("Local IP exception configuration IP【"+localIP+"】 Program to get IP【"+localIP2+"】 will use the configuration IP");
}
} catch (SocketException e1) {
logger.error("Program gets IP failure", e1);
}
SYSTEM_INET_ADDRESS = localIP;
// }
MAX_NETWORK_BANDWIDTH = Config.getInteger("max.network.bandwidth",0);
// #---Executor /ThreadPool-------
EXECUTOR_SOCKET_THREAD_SIZE = Config.getInteger("executor.socket.thread.size",120);
EXECUTOR_SCHEDULED_THREAD_SIZE = Config.getInteger("executor.scheduled.thread.size",30);
EXECUTOR_DATA_RESOVE_THREAD_SIZE = Config.getInteger("executor.data.resove.thread.size",3);
// #---Change Operations-------
CHANGE_OPERATIONS_PERIOD = Config.getInteger("change.operations.period",120);
CHANGE_RELEASE_SEMAPHORE_MAX = Config.getInteger("change.release.semaphore.max",20);
// #---Detection Resolve-------
// String outTimes = Config.getString("detec.timeout.alarm.period.times");
//
// int outT = 1;
// if(outTimes != null ){
// try {
// outT = Integer.parseInt(outTimes);
// } catch (Exception e) {
// logger.error("detec.timeout.alarm.period.times 取值失败",e);
// }
// }
// DETEC_TIMEOUT_ALARM_PERIOD_TIMES = Config.getInteger("detec.timeout.alarm.period.times");;
DETEC_RELEASE_SEMAPHORE_MAX = Config.getInteger("detec.release.semaphore.max",(int)(EXECUTOR_SOCKET_THREAD_SIZE*0.8));
DETEC_DATA_RESOLVE_PERIOD = Config.getInteger("detec.data.resovle.period",60);
DISK_DATA_RESOLVE_PERIOD = Config.getInteger("disk.data.resovle.period",600);
ERROR_INFO_RESOVE_PERIOD = Config.getInteger("error.info.resovle.period",60);
// MAILING_PERIOD = Config.getInteger("mailing.period",120);
// DETEC_DATA_COLLECT_PERIOD = Config.getInteger("detec.data.collect.period");
DATA_COLLECT_PERIOD = Config.getInteger("data.collect.period",300);
ERROR_NODE_DATA_COLLECT_PERIOD = Config.getInteger("error.node.data.collect.period",600);
NONRLTTASK_RESULT_COLLECT_PERIOD = Config.getInteger("nonRltTask.result.collect.period",600);
DETEC_PING_STR = Config.getString("detec.ping.str","ping");
DETEC_NMSC_STR = Config.getString("detec.nmsc.str","nmsclient");
DETEC_SNMP_STR = Config.getString("detec.snmp.str","SNMP");
DETEC_SWITCH_STR = Config.getString("detec.switch.str","switchport");
DETEC_SYSTEMINFO_STR = Config.getString("detec.systeminfo.str","systeminfo");
DETEC_SYSTEM_STR = Config.getString("detec.system.str","system");
DETEC_SYSTEMDATE_STR = Config.getString("detec.systemdate.str","systemdate");
DETEC_IFXTABLE_STR = Config.getString("detec.ifxtable.str","ifXTable");
DELETE_TMP_FILES_PERIOD = Config.getInteger("delete.files.period",24);
KEEP_FILE_DAYS = Config.getInteger("keep.file.days",7);
ALARM_SNMP_TRAP_STR = Config.getString("alarm.snmp.trap.str","SNMP_TRAP");
// #---Alarm Resolve-------
ALARM_DATA_RESOLVE_PERIOD = Config.getInteger("alarm.data.resovle.period",60);
// #---Web-------
// WEB_DOWNLOAD_URL = formatPath(Config.getValue("web.download.url")); //指定IP通信
WEB_SOCKET_IP = Config.getString("web.socket.ip",null); //指定IP通信
WEB_SOCKET_PORT = Config.getInteger("web.socket.port",60703) ; //指定IP通信端口
// #---Mission Control-------
MISSION_LOOP_PRESET_NUMBER = Config.getInteger("mission.loop.preset.number",10);
// MISSION_LOOP_FINISHING_DAILY = Config.getString("mission.loop.finishing.daily");
// #---Mission release-------
MISSION_RELEASE_SEMAPHORE_MAX = Config.getInteger("mission.release.semaphore.max",(int)(EXECUTOR_SOCKET_THREAD_SIZE*0.3));
MISSION_RELEASE_TIMES = Config.getInteger("mission.release.times",3);
MISSION_RELEASE_PERIOD = Config.getInteger("mission.release.period",180);
// #---Mission File-------
MISSION_FILE_DOWNLOAD_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("mission.file.download.dir","dc_downLoad"));
// int downloadDelay = (int)Config.getInteger("mission.file.download.delay");
MISSION_FILE_DOWNLOAD_DELAY = Config.getInteger("mission.file.download.delay",60);
MISSION_FILE_UPLOAD_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("mission.file.upload.dir","dc_upload"));
MISSION_FILE_UPLOAD_PERIOD = Config.getInteger("mission.file.upload.period",120);
MISSION_UPGRADE_DAILY = Config.getInteger("mission.update.daily",300);
// #---Email-------
/*
FLAG_EMAIL = Config.getInteger("email.flag",0);
if(FLAG_EMAIL==1){
EMAIL_ADDRESS = Config.getString("email.address");
EMAIL_USERNAME = Config.getString("email.userName");
EMAIL_PASSWORD = Config.getString("email.password");
EMAIL_HOST = Config.getString("email.host");
}else{
EMAIL_ADDRESS = null;
EMAIL_USERNAME = null;
EMAIL_PASSWORD = null;
EMAIL_HOST = null;
}*/
// #---DataBase-------
DB_POOL_TYPE = Config.getString("db.pool.type", "bonecp");//默认 bonecp
DB_URL = Config.getString("db.url",null);
DB_USER_NAME = Config.getString("db.username",null);
DB_PASSWORD = Config.getString("db.password",null);
DB_DRIVER = Config.getString("db.driver","oracle.jdbc.driver.OracleDriver");
DB_DATE_FORMAT = Config.getString("db.date.format","yyyy-MM-dd HH24:mi:ss");
DB_EXECUTE_BATCH = Config.getInteger("db.execute.batch",1000);
// Integer partitionCount = (Integer) resource.getObject("db.pool.partitionCount");
DB_STATEMENT_EXECUTE_TIMEOUT = Config.getInteger("db.statement.execute.timeout",60);
DB_POOL_PARTITION_COUNT = Config.getInteger("db.pool.partitionCount",3);
DB_POOL_CONNECTIONS_PER_PARTITION_MAX = Config.getInteger("db.pool.maxConnectionsPerPartition",5);
DB_POOL_CONNECTIONS_PER_PARTITION_MIN = Config.getInteger("db.pool.minConnectionsPerPartition",3);
DB_POOL_ACQUIRE_INCREMENT = Config.getInteger("db.pool.acquireIncrement",3);
DB_POOL_IDLE_CONNECTION_TEST_PERIOD = Config.getInteger("db.pool.idleConnectionTestPeriod",15);
DB_POOL_IDLE_MAX_AGE = Config.getInteger("db.pool.idleMaxAge",30);
DB_GET_CONNECTION_TIMEOUT = Config.getInteger("db.get.connection.timeout",30);
DB_POOL_MAX_CONNECTION_AGE = Config.getInteger("db.pool.max.connection.age",DB_POOL_IDLE_MAX_AGE*2);
DB_POOL_RELEASE_HELPER_THREADS = Config.getInteger("db.pool.releaseHelperThreads",DB_POOL_PARTITION_COUNT);
DB_POOL_STATEMENT_RELEASE_HELPER_THREADS = Config.getInteger("db.pool.statement.releaseHelperThreads",DB_POOL_PARTITION_COUNT);
DB_POOL_QUERY_EXECUTE_TIME_LIMIT = Config.getInteger("db.pool.queryExecuteTimeLimit",60);
DB_POOL_LOG_STATEMENT_ENABLE = Config.getBoolan("db.pool.logStatementEnable",true);
// #---DATA-------
/*
DATA_DIR = formatPath(Config.getString("data.dir"));
DATA_BACKUP_RIGHT_DIR = formatPath(Config.getString("data.backup.right.dir"));
DATA_BACKUP_WRONG_DIR = formatPath(Config.getString("data.backup.wrong.dir"));
*/
// #---ZIP File-------
ZIP_FILE_DETECT_DATA_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("zip.file.detect.data.dir","dc_zip/detect"));
ZIP_FILE_TASK_RESULT_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("zip.file.task.result.dir","dc_zip/result"));
ZIP_FILE_TASK_RETURN_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("zip.file.task.return.dir","dc_zip/return"));
// #---ZIP File Resove-------
// ZIP_RESOVE_DETECT_DATA_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("zip.resove.detect.data.dir","dc_zip/resove/detect"));
ZIP_RESOVE_DETECT_DATA_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("zip.resove.detect.data.dir","dc_overrun/detect/zip_resove"));//为了避免因长时间未收集数据导致一次性收集大量的数据nc端默认1000csv打包zip所以如果监测数据打包发送表明数据较多如果全部进行解析入库会导致内存溢出所以存入dc_overrun等待之后慢慢解析
ZIP_RESOVE_TASK_RESULT_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("zip.resove.task.result.dir","dc_zip/resove/result"));
ZIP_RESOVE_TASK_RETURN_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("zip.resove.task.return.dir","dc_zip/resove/return"));
ERROR_DETEC_FILE_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("error.detect.file.dir","dc_error/detect"));
OVERRUN_DETEC_FILE_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("overrun.detect.file.dir","dc_overrun/detect"));
OVERRUN_WARNING_FILE_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("overrun.warning.file.dir","dc_overrun/warning"));
OVERRUN_RESULT_FILE_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("overrun.result.file.dir","dc_overrun/result"));
// TODO
PLUGIN_SCRIPT_FILE_DIR = formatPath(COMMON_DATAS_DIR+File.separator+Config.getString("detecScript","dc_detecScript"));
// DEFAULT_NODE_GROUP_NAME = Config.getString("default.node.group.name","默认节点组");
// DEFAULT_NODE_GROUP_NAME = Config.getString("default.node.group.name","Default Node Group");
DEFAULT_NODE_GROUP_NAME = Config.getString("default.node.group.name","i18n_server.Constants.defaultNodeGroup_n81i");
MAX_COLLECT_RESOVE_DETECT_DATA_NUM = Config.getInteger("max.collect.resove.detect.data.num",60);
MAX_DETECT_DATA_RESOVE_LIMIT_NUM = Config.getInteger("max.detect.data.resove.limit.num",60000);
// #---SNMP-------
SNMP_CLIENT_PORT = Config.getInteger("snmp.client.port",161);
SNMP_TRAP_THREAD_POOL_SIZE = Config.getInteger("snmp.trap.thread.pool.size",10);
SNMP_TRAP_PORT = Config.getInteger("snmp.trap.port",162);
SNMP_COMMUNITY = Config.getString("snmp.community","public");
/*SNMP_MIB_DIR = formatPath(Config.getString("snmp.mib.dir"));
SNMP_CLASS_PATH = formatPath(Config.getString("snmp.class.path"));
SNMP_CLASS_DIR = SNMP_CLASS_PATH+SNMP_CLASS_PACKAGE.replaceAll("\\.", "/")+"/";*/
SNMP_CLASS_PACKAGE = Config.getString("snmp.class.package","osDomains");
/*##--SNMP 加密认证级别 0 不认证 不加密'zg' 1 认证 不加密'hckings' ,2认证 且 加密'dxy'*/
SNMP_V3_SECURITY_LEVEL = Config.getInteger("snmp.v3.security.level",0);
SNMP_V3_SECURITY_NAME = Config.getString("snmp.v3.security.name","zg");
SNMP_V3_AUTH_PROTOCOL = Config.getString("snmp.v3.auth.protocol","MD5");
SNMP_V3_PRIV_PROTOCOL = Config.getString("snmp.v3.priv.protocol","DES");
SNMP_V3_AUTH_PASSPHRASE = Config.getString("snmp.v3.auth.passphrase","12345678");
SNMP_V3_PRIV_PASSPHRASE = Config.getString("snmp.v3.priv.passphrase","12345678");
// #---SSL Init-------
SSL_SO_TIMEOUT = Config.getInteger("ssl.so.timeout",600);
SSL_TYPE = Config.getString("ssl.type","TLS");
SSL_DIR = formatPath(Config.getString("ssl.dir","cer"));
SSL_SERVER_PORT = Config.getInteger("ssl.server.port",60702);
SSL_CLIENT_PORT = Config.getInteger("ssl.client.port",60701);
SSL_KEYSTORE_TYPE = Config.getString("ssl.keystore.type","jceks");
SSL_SERVER_STORE = Config.getString("ssl.server.store","server_ks");
SSL_SERVER_STORE_PSW = Config.getString("ssl.server.store.psw","client");
SSL_SERVER_TRUST = Config.getString("ssl.server.trust","server_ts");
SSL_SERVER_TRUST_PSW = Config.getString("ssl.server.trust.psw","client");
SSL_SERVER_EXPORT = Config.getString("ssl.server.export","server.cer");
SSL_CLIENT_EXPORT = Config.getString("ssl.client.export","client.cer");
SSL_SERVER_KEY_NEW = Config.getString("ssl.server.key.new","serverks20110828");
SSL_SERVER_KEY_OLD = Config.getString("ssl.server.key.old","serverks20110828");
SSL_SERVER_KEY_NEW_PSW = Config.getString("ssl.server.key.new.psw","123456");
SSL_SERVER_KEY_OLD_PSW = Config.getString("ssl.server.key.old.psw","123456");
SSL_CLIENT_KEY = Config.getString("ssl.client.key","serverks20110828");
SSL_CLIENT_KEY_PSW = Config.getString("ssl.client.key.psw","123456");
SSL_CLIENT_STORE = Config.getString("ssl.client.store","client_ks");
SSL_CLIENT_TRUST= Config.getString("ssl.client.trust","client_ts");
SSL_KEY_VALIDITY= Config.getInteger("ssl.key.validity",90);
// #---Test Flag-------
FLAG_ZIP = Config.getInteger("zip.flag",1);
// FLAG_DETEC_TIMEOUT = Config.getInteger("detec.timeout.flag");
FLAG_FILE_UPLOAD= Config.getInteger("file.upload.flag",1);
FLAG_DETEC_RESOVE= Config.getInteger("file.resove.flag",1);
FLAG_ERROR_INFO= Config.getInteger("error.info.flag",1);
FLAG_FILES_READER_RESOVE= Config.getInteger("data.files.reader.flag",1);
FLAG_DATA_COLLECT= Config.getInteger("data.collect.flag",1);
FLAG_HANDWALK_SSH= Config.getInteger("handwalk.ssh.flag",1);
FLAG_DATA_COLLECT_ONLY_HANDSHAKE= Config.getInteger("data.collect.flag.only.handshake",1);
FLAG_EMAIL_START= Config.getInteger("email.start.flag",1);
FLAG_NONRLTTASK_RESULT_COLLECT= Config.getInteger("nonRltTask.result.collect.flag",1);
FLAG_DELETE_TMP_FILES= Config.getInteger("delete.files.flag",1);
FLAG_CHANGE_OPERATIONS= Config.getInteger("change.operations.flag",1);
FLAG_PING= Config.getInteger("ping.flag",1);
FLAG_NMSC= Config.getInteger("nmsc.flag",1);
FLAG_SNMP= Config.getInteger("snmp.flag",1);
FLAG_SWITCH= Config.getInteger("switch.flag",1);
FLAG_SYSTEMDATE = Config.getInteger("systemdate.flag",1);
FLAG_MISSION= Config.getInteger("mission.flag",1);
FLAG_MISSION_RESULT= Config.getInteger("result.flag",1);
/*FLAG_RESOVE_READ_FILE= Config.getInteger("file.resove.readFile.flag");
FLAG_RESOVE_RESOVE_FILE= Config.getInteger("file.resove.resoveFile.flag");
FLAG_MOVE_FILE= Config.getInteger("file.moveFile.flag");*/
FLAG_RESOVE_COMMIT_DB= Config.getInteger("file.resove.commitDB.flag",1);
FLAG_ALARM_RESOVE = Config.getInteger("alarm.resove.flag",1);
FLAG_TRAP = Config.getInteger("trap.flag",1);
// FLAG_TEST = Config.getInteger("test.flag");
// TEST_COMPUTER = Config.getInteger("computer.size");
// TEST_SWITCH = Config.getInteger("switch.size");
// SSL_INIT_SERVER_KEY = Config.getValue("ssl.init.server.key");
// SSL_INIT_CLIENT_KEY = Config.getValue("ssl.init.client.key");
// SSL_INIT_SERVER_KEY_PSW = Config.getValue("ssl.init.server.key.psw");
// SSL_INIT_CLIENT_KEY_PSW = Config.getValue("ssl.init.client.key.psw");
// #---SSL Bat-------
// SSL_BAT_IMPORT = Config.getValue("ssl.bat.import");
// SSL_BAT_GENKEY_EXPORT = Config.getValue("ssl.bat.genkey.export");
// SSL_BAT_SERVER_INIT = Config.getValue("ssl.bat.server.init");
// SYSTEM_INET_ADDRESS = Common.getLocalIp();
PORT_ALARM_LEVEL = Config.getInteger("port.alarm.level",5);
PORT_ALARM_EMERGENT = Config.getInteger("port.alarm.level",1);
DETECT_FAIL_NMSC_POLICE_LEVEL = Config.getInteger("detect.fail.nmsc.police.level",0);
DETECT_FAIL_NMSC_POLICE_EMERGENT = Config.getInteger("detect.fail.nmsc.police.emergent",0);
DETECT_FAIL_NON_NMSC_POLICE_LEVEL = Config.getInteger("detect.fail.non.nmsc.police.level",1);
DETECT_FAIL_NON_NMSC_POLICE_EMERGENT = Config.getInteger("detect.fail.non.nmsc.police.emergent",1);
NC_ALARM_POLICE_LEVEL = Config.getString("nc.alarm.police.level","0");
SINGLE_NODE_DETECT_TIMEOUT = Config.getInteger("single.node.detect.timeout", 180);
VARCHAR_MAX_LENGTH = Config.getInteger("varchar.max.length",4000)-1;
FLAG_DETECT_DATA_SAVE_DISK_RESOVE = Config.getInteger("flag.detect.data.save.disk.resove",1);
FLAG_WARN_DATA_SAVE_DISK_RESOVE = Config.getInteger("flag.warn.data.save.disk.resove",1);
FLAG_ERROR_DATA_SAVE_DISK_RESOVE = Config.getInteger("flag.error.data.save.disk.resove",1);
FLAG_TASK_RLT_SAVE_DISK_RESOVE = Config.getInteger("flag.task.rlt.save.disk.resove",1);
DETECTION_INFO_DATA_MAX_ROWS = Config.getInteger("detection_info_data_max_rows", 500);
FETCH_SIZE = Config.getInteger("fetch.size", 100);
DATA_COLLECT_DAILY = Config.getInteger("data.collect.daily", 120);
ERROR_NODE_DATA_COLLECT_DAILY = Config.getInteger("error.node.data.collect.daily", 540);
SSH_CONNECT_TIMEOUT = Config.getInteger("ssh.connect.timeout", 2000);
IS_HANDEL_EXCEPTION_NODE = Config.getBoolan("is.handel.exception.node", false);
/**
* 数据库类型
*/
DB_TYPE = Config.getString("db.type", "oracle");
/**
* 是否是 mysql 数据库
*/
IS_MYSQL = "mysql".equalsIgnoreCase(DB_TYPE);
/**
* //dc监测数据入库模式1由web 主控控制入库2自己主动入库
*/
DETECT_INSERT_MODE = Config.getInteger("detect.insert.mode", 2);
WEB_NOTICE_INSERT_DETECT_OVER_TIMES = Config.getInteger("web.notice.insert.detect.over.times", 3);
DETECSELFTHREAD_FLAG = Config.getBoolan("DETECSELFTHREAD_FLAG", true);//DETECSELFTHREAD 开关
DETECSELFTHREAD_PERIOD = Long.valueOf(Config.getInteger("DETECSELFTHREAD_PERIOD", 30));//监测间隔,单位:秒
DETECSELFTHREAD_INITIALDELAY = Long.valueOf(Config.getInteger("DETECSELFTHREAD_PERIOD", 30));//监测延迟启动时间,单位:秒
/**
* 监测数据入库线程模式1单线程2双线程info,detail
*/
DETECT_INSERT_THREAD_MODE = Config.getInteger("detect.insert.thread.mode", 1);
/**
* INFO入库线程运行模式1每隔 N秒 运行一次2间隔 N 秒运行一次
*/
DETECT_INFO_THREAD_MODE = Config.getInteger("detect.info.thread.mode", 1);
/**
* INFO入库线程 每隔 或间隔 时间 单位S
*/
DETECT_INFO_THREAD_TIME = Config.getInteger("detect.info.thread.time", 60);
DETECT_INFO_THREAD_DELAY = Config.getInteger("detect.INFO.thread.delay", 5);
/**
* DETAIL入库线程运行模式1每隔 N秒 运行一次2间隔 N 秒运行一次
*/
DETECT_DETAIL_THREAD_MODE = Config.getInteger("detect.detail.thread.mode", 1);
/**
* DETAIL入库线程 每隔 或间隔 时间 单位S
*/
DETECT_DETAIL_THREAD_TIME = Config.getInteger("detect.detail.thread.time", 60);
DETECT_DETAIL_THREAD_DELAY = Config.getInteger("detect.detail.thread.delay", 5);
/**
* netty server
*
*/
//0启用
NETTY_SERVER_FLAG = Config.getInteger("netty.server.flag", 1);
NETTY_SERVER_PORT = Config.getInteger("netty.server.port", 9527);
NETTY_SERVER_SSL = Config.getBoolan("netty.server.ssl", true);
NETTY_IDLE_TIME = Config.getInteger("netty.idle.time", 15);
NETTY_SO_BACKLOG = Config.getInteger("netty.so.backlog", 6000);
SERVER_NMSC_THREAD_INTERVAL = Config.getInteger("server.nmsc.thread.interval", 300);
NEXTVAL_FUNCTION_NAME = Config.getString("nextval_function_name", "nextval");
CURRVAL_FUNCTION_NAME = Config.getString("currval_function_name", "currval");
HANDSHANK_DELAY_TIME = Long.parseLong(Config.getString("handshank.delay.time", 15000+""));
}
//文件传输 临时文件命名后缀
public static final String TEMP_SUFFIX = ".tp";
private static String formatPath(String path){
if(StringUtils.isNotEmpty(path)){
path = path.replaceAll("\\\\", "/");
if(!path.endsWith("/") && !path.endsWith("=")){
path = path+"/";
}
}
return path;
}
}

View File

@@ -0,0 +1,5 @@
package com.nms.server.common;
public class DetectionConstants {
}

View File

@@ -0,0 +1,74 @@
package com.nms.server.common;
public class EmailTypeConstants {
// private static final Object[][] type =new Object[][]{
// {10,"监测信息恢复"},
// {11,"监测信息异常"},
// {12,"监测信息超时"},
// {20,"主动告警异常"},
// {21,"主动告警恢复"},
// {31,"节点结果失败"},
// {32,"任务状态变更"},
// {40,"系统运行异常"},
// {41,"系统运行恢复"},
// };
public static final String ERROR_PROCESSS_NOT_EXIST = "ProcessNotExist"; //进程不存在
public static final String ERROR_HANDSHAKE = "HandShakeError"; //握手失败
public static final String ERROR_THREAD_RUNTIME = "ThreadRuntimeError"; //执行异常
public static final String ERROR_PROT_LISTENER = "ProtListenerError"; //端口监听失败
public static final String ERROR_DEAMON_NOT_EXIST = "DeamonNotExist"; //守护进程不存在
public static final String ERROR_DATA_RESOVE = "DataResoveError"; //数据解析错误
public static final String ERROR_SOCKET = "SocketError"; //通讯失败
// public static final int STATE_OK = 0; //已解决
// public static final int STATE_FAIL = 1; //未解决
// public static final int STATE_RECOVER = 2; //已恢复
public static final int FLAG_SEND_LATER = 0;
public static final int FLAG_SEND_ALLREADY = 1;
public static final int FLAG_SEND_IMMEDIATELY = 2;
public static final int URGENT_IMMEDIATELY = 0;
public static final int URGENT_LATER = 1;
public static final int TYPE_DETECTION_INFO_RECOVER = 10;
// public static final String DESC_DETECTION_INFO_RECOVER = "监测信息恢复";
// public static final String DESC_DETECTION_INFO_RECOVER = "Monitoring Information Recovery";
public static final String DESC_DETECTION_INFO_RECOVER = "i18n_server.EmailTypeConstants.DESC_DETECTION_INFO_RECOVER_n81i";
public static final int TYPE_DETECTION_INFO_EXCEPTION = 11;
// public static final String DESC_DETECTION_INFO_EXCEPTION = "监测信息异常";
// public static final String DESC_DETECTION_INFO_EXCEPTION = "Monitoring information is abnormal";
public static final String DESC_DETECTION_INFO_EXCEPTION = "i18n_server.EmailTypeConstants.DESC_DETECTION_INFO_EXCEPTION_n81i";
public static final int TYPE_DETECTION_INFO_TIMEOUT = 12;
// public static final String DESC_DETECTION_INFO_TIMEOUT = "监测信息超时";
// public static final String DESC_DETECTION_INFO_TIMEOUT = "Monitoring information timeout";
public static final String DESC_DETECTION_INFO_TIMEOUT = "i18n_server.EmailTypeConstants.DESC_DETECTION_INFO_TIMEOUT_n81i";
public static final int TYPE_ALARM_INFO_EXCEPTION = 20;
// public static final String DESC_ALARM_INFO_EXCEPTION = "主动告警异常";
// public static final String DESC_ALARM_INFO_EXCEPTION = "Active alarm exception";
public static final String DESC_ALARM_INFO_EXCEPTION = "i18n_server.EmailTypeConstants.DESC_ALARM_INFO_EXCEPTION_n81i";
public static final int TYPE_ALARM_INFO_RECOVER = 21;
// public static final String DESC_ALARM_INFO_RECOVER = "主动告警恢复";
// public static final String DESC_ALARM_INFO_RECOVER = "Active Alarm Recovery";
public static final String DESC_ALARM_INFO_RECOVER = "i18n_server.EmailTypeConstants.DESC_ALARM_INFO_RECOVER_n81i";
public static final int TYPE_TASK_NODE_RESULT_ERROR = 31;
// public static final String DESC_TASK_NODE_RESULT_ERROR = "节点结果失败";
// public static final String DESC_TASK_NODE_RESULT_ERROR = "Node result failed";
public static final String DESC_TASK_NODE_RESULT_ERROR = "i18n_server.EmailTypeConstants.DESC_TASK_NODE_RESULT_ERROR_n81i";
public static final int TYPE_TASK_STATE_CHANGE = 32;
// public static final String DESC_TASK_STATE_CHANGE = "任务状态变更";
// public static final String DESC_TASK_STATE_CHANGE = "Change of task status";
public static final String DESC_TASK_STATE_CHANGE = "i18n_server.EmailTypeConstants.DESC_TASK_STATE_CHANGE_n81i";
public static final int TYPE_SYSTEM_RUNNING_EXCEPTION = 40;
// public static final String DESC_SYSTEM_RUNNING_EXCEPTION = "系统运行异常";
// public static final String DESC_SYSTEM_RUNNING_EXCEPTION = "System operation is abnormal";
public static final String DESC_SYSTEM_RUNNING_EXCEPTION = "i18n_server.EmailTypeConstants.DESC_SYSTEM_RUNNING_EXCEPTION_n81i";
public static final int TYPE_SYSTEM_RUNNING_RECOVER = 41;
// public static final String DESC_SYSTEM_RUNNING_RECOVER = "系统运行恢复";
// public static final String DESC_SYSTEM_RUNNING_RECOVER = "System Operation Recovery";
public static final String DESC_SYSTEM_RUNNING_RECOVER = "i18n_server.EmailTypeConstants.DESC_SYSTEM_RUNNING_RECOVER_n81i";
}

View File

@@ -0,0 +1,33 @@
package com.nms.server.common;
public class MissionConstants {
public final static int MISSION_STATE_CREATE = 1;
public final static int MISSION_STATE_RUNNING_OK = 2;
public final static int MISSION_STATE_FINISHING = 3;
public final static int MISSION_STATE_RUNNING_FAIL = 4;
public final static int MISSION_STATE_CANCEL = 5;
public final static int MISSION_STATE_CANCEL_RUNNING_OK = 6;
public final static int MISSION_STATE_CANCEL_FINISHING = 7;
// public final static String ERROR_TASK_PARAMS = "参数错误,任务无法执行;";
// public final static String ERROR_TASK_NO_FILE = "无推送文件,任务无法执行;";
// public final static String ERROR_TASK_NO_USED_NODE = "无有效服务器节点,任务无法执行;";
// public final static String ERROR_TASK_RUND_NO_USED_NODE = "无有效服务器节点,当前周期无法执行;";
// public final static String WARN_TASK_UN_MANAGEMENT_NODE = "存在DC管理外节点";
// public final static String NOTICE_TASK_RUNNING = "任务开始执行";
// public final static String ERROR_RESULT_NOT_SERVER = "该节点不是服务器";
// public final static String ERROR_RESULT_UN_MANAGEMENT_NODE = "该节点不在DC管理范围内";
// public final static String ERROR_RESULT_FILE_DOWNLOAD_FAIL = "DC文件下载失败";
// public final static String ERROR_RESULT_EXEC_TIMEOUT = "周期任务执行超时,结果置为失败";//endTime<当前时间
public final static String ERROR_TASK_PARAMS = "i18n_server.MissionConstants.ERROR_TASK_PARAMS_n81i";
public final static String ERROR_TASK_NO_FILE = "i18n_server.MissionConstants.ERROR_TASK_NO_FILE_n81i";
public final static String ERROR_TASK_NO_USED_NODE = "i18n_server.MissionConstants.ERROR_TASK_NO_USED_NODE_n81i";
public final static String ERROR_TASK_RUND_NO_USED_NODE = "i18n_server.MissionConstants.ERROR_TASK_RUND_NO_USED_NODE_n81i";
public final static String WARN_TASK_UN_MANAGEMENT_NODE = "i18n_server.MissionConstants.WARN_TASK_UN_MANAGEMENT_NODE_n81i";
public final static String NOTICE_TASK_RUNNING = "i18n_server.MissionConstants.NOTICE_TASK_RUNNING_n81i";
public final static String ERROR_RESULT_NOT_SERVER = "i18n_server.MissionConstants.ERROR_RESULT_NOT_SERVER_n81i";
public final static String ERROR_RESULT_UN_MANAGEMENT_NODE = "i18n_server.MissionConstants.ERROR_RESULT_UN_MANAGEMENT_NODE_n81i";
public final static String ERROR_RESULT_FILE_DOWNLOAD_FAIL = "i18n_server.MissionConstants.ERROR_RESULT_FILE_DOWNLOAD_FAIL_n81i";
public final static String ERROR_RESULT_EXEC_TIMEOUT = "i18n_server.MissionConstants.ERROR_RESULT_EXEC_TIMEOUT_n81i";//endTime<当前时间
}

View File

@@ -0,0 +1,40 @@
package com.nms.server.common;
public class UpdateParams extends java.util.ListResourceBundle {
public static String CONFIG_UPDATE_FLAG = "config.update.flag"; //更新标示 固定 判断配置文件指定值更新 建议自增1操作
public static String CONFIG_UPDATE_FLAG_VALUE = "12"; //更新标示 该值 缺省值为0 每次修改都要
static final String[][] contents = new String[][]{
{CONFIG_UPDATE_FLAG,CONFIG_UPDATE_FLAG_VALUE}, //更新标示 固定 判断配置文件指定值更新 建议自增1操作
{"detec.switch.str","switchport"}, // 更新switch 监测类别
{"detec.systeminfo.str","systeminfo"}, // 更新systeminfo 监测类别
{"detec.systemdate.str","systemdate"}, // 更新systemdate 监测类别
{"detec.system.str","system"}, // 更新systeminfo 监测类别
{"detec.ifxtable.str","ifXTable"},// 更新ifXTable 监测类别
{"error.info.flag","1"}, // 更新systeminfo 监测类别
{"data.files.reader.flag","1"}, // 数据保存暂存硬盘标示
{"systemdate.flag","1"}, // systemdate主动监测监测标示
{"email.start.flag","1"}, // 邮件发送功能启用标识
{"delete.files.flag","1"}, // delete log/error/download files flag
{"keep.file.days","7"}, // keep log/error/download files days
{"delete.files.period","24"}, // 删除log等临时文件的时间间隔,unit:hour
{"mailing.period","120"}, // 邮件发送周期,unit:S
//2014-1-2 hyx add
{"detect.fail.nmsc.police.level","0"},//握手监测失败时state=-1默认的告警级别0级
{"detect.fail.nmsc.police.emergent","0"},//握手监测失败时state=-1默认的紧急状态0紧急1非紧急
{"detect.fail.non.nmsc.police.level","1"},//非握手监测失败时state=-1默认的告警级别1-5级
{"detect.fail.non.nmsc.police.emergent","1"},//非握手监测失败时state=-1默认的紧急状态0紧急1非紧急
{"port.alarm.level","5"},//端口异常流量为0设置状态和实际状态不符默认的告警级别:1-5级
{"port.alarm.emergent","1"},//端口异常流量为0设置状态和实际状态不符默认的紧急状态:0紧急1非紧急
{"nc.alarm.police.level","0"},//NC主动告警默认为紧急state=-2时默认的告警级别:0级
{"single.node.detect.timeout","180"}//DC端主动监测单节点超时时间
};
public Object[][] getContents() {
return contents;
}
}

View File

@@ -0,0 +1,254 @@
package com.nms.server.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.common.Constants;
import com.nms.server.util.ConnectionOracle;
import com.nms.server.util.DateUtil;
import com.nms.server.util.SQLExecuteTimeoutException;
public class CommonDao extends ConnectionOracle {
public CommonDao() throws SQLException {
super();
}
private Logger logger = Logger.getLogger(CommonDao.class);
/**
* 插入数据 封装方法
*
* @time Jul 27, 2011-4:00:44 PM
* @param tableName
* 插入表 表名
* @param info
* 字段和值集合
* @return
* @throws Exception
*/
public boolean insertObj(String tableName, Map<String, String> info)
throws SQLExecuteTimeoutException,SQLException {
StringBuffer values_0 =new StringBuffer();
StringBuffer infoSQL = new StringBuffer("insert into " + tableName
+ " ("); // SQL
StringBuffer values = new StringBuffer(); // values
// SQL拼写
Iterator<Entry<String, String>> ite = info.entrySet().iterator();
ArrayList<String> params = new ArrayList<String>();
while (ite.hasNext()) {
Entry<String, String> entry = ite.next();
//logger.debug(entry.getKey() +": \""+entry.getValue()+"\"" );
if (StringUtils.isBlank(entry.getValue()))
continue; // 跳过无效数据
infoSQL.append(entry.getKey() + ",");
params.add(entry.getValue());
if (DateUtil.isDate(entry.getValue(), Constants.COMMON_DATE_FORMAT)) { // 日期类型
values.append(" to_date(?,'" + Constants.DB_DATE_FORMAT
+ "'),");
} else { // 其他类型
values.append("?,");
}
//--
if (DateUtil.isDate(entry.getValue(), Constants.COMMON_DATE_FORMAT)) { // 日期类型
values_0.append(" to_date('"+entry.getValue()+"','" + Constants.DB_DATE_FORMAT
+ "'),");
} else { // 其他类型
values_0.append("'"+entry.getValue()+"',");
}
}
infoSQL = infoSQL.deleteCharAt(infoSQL.length() - 1);
values = values.deleteCharAt(values.length() - 1);
values_0 = values_0.deleteCharAt(values_0.length() - 1);
logger.debug(infoSQL+") values ("+values_0+")");
infoSQL.append(") values (" + values + ")");
return this.dbUpdate(infoSQL.toString(), params.toArray());
}
/**
* 插入数据 封装方法
*
* @time Jul 27, 2011-4:00:44 PM
* @param tableName
* 插入表 表名
* @param info
* 字段和值集合
* @return
* @throws Exception
*/
public boolean insertObjByBatch(String tableName, List<Map<String, String>> infoList)
throws SQLExecuteTimeoutException,SQLException {
if(infoList!=null && infoList.size()>0){
List<String> sqList = new LinkedList<String>();
for(Map<String, String> info : infoList){
StringBuffer values_0 =new StringBuffer();
StringBuffer infoSQL = new StringBuffer("insert into " + tableName
+ " ("); // SQL
// SQL拼写
Iterator<Entry<String, String>> ite = info.entrySet().iterator();
ArrayList<String> params = new ArrayList<String>();
while (ite.hasNext()) {
Entry<String, String> entry = ite.next();
//logger.debug(entry.getKey() +": \""+entry.getValue()+"\"" );
if (StringUtils.isBlank(entry.getValue()))
continue; // 跳过无效数据
infoSQL.append(entry.getKey() + ",");
params.add(entry.getValue());
//--
if (DateUtil.isDate(entry.getValue(), Constants.COMMON_DATE_FORMAT)) { // 日期类型
values_0
.append(" to_date('"+entry.getValue()+"','" + Constants.DB_DATE_FORMAT
+ "'),");
} else { // 其他类型
values_0.append("'"+entry.getValue()+"',");
}
}
infoSQL = infoSQL.deleteCharAt(infoSQL.length() - 1);
values_0 = values_0.deleteCharAt(values_0.length() - 1);
logger.debug(infoSQL+") values ("+values_0+")");
infoSQL.append(") values (" + values_0 + ")");
sqList.add(infoSQL.toString());
}
return this.dbUpdateByBatch(sqList);
}else{
return true;
}
}
/**
* 插入数据 封装方法
*
* @time Jul 27, 2011-4:00:44 PM
* @param tableName
* 插入表 表名
* @param info
* 字段和值集合
* @return
* @throws Exception
*/
/*public boolean insertSimpleObjByBatch(String tableName,List<Map<String, String>> infoList)
throws SQLExecuteTimeoutException,SQLException {
//固定 字段名
List<Object> columnList = null;
//固定 sql
StringBuffer infoSQL = new StringBuffer("insert into " + tableName
+ " ("); // SQL
StringBuffer values = new StringBuffer(); // values
if(infoList!=null && infoList.size()>0){
Map<String, String> map = infoList.get(0);
columnList = Arrays.asList(map.keySet().toArray());
for(Object obj : columnList){
if(obj == null){
continue;
}
String key = obj.toString();
String value = map.get(key);
logger.debug(key +": \""+value+"\"" );
infoSQL.append(key + ",");
if (DateUtil.isDate(value, Constants.COMMON_DATE_FORMAT)) { // 日期类型
values
.append(" to_date(?,'" + Constants.DB_DATE_FORMAT
+ "'),");
} else { // 其他类型
values.append("?,");
}
}
infoSQL = infoSQL.deleteCharAt(infoSQL.length() - 1);
values = values.deleteCharAt(values.length() - 1);
infoSQL.append(") values (" + values + ")");
}
//整理值
if(infoList!=null && infoList.size()>0){
List<String[]> paramsList = new LinkedList<String[]>();
for(Map<String, String> info : infoList){
for(Object obj : columnList){
if(obj == null){
continue;
}
ArrayList<String> params = new ArrayList<String>();
String value = info.get(obj);
if(StringUtils.isBlank(value)){
params.add("");
}else{
params.add(info.get(obj));
}
System.out.println(""+Arrays.toString(params.toArray(new String[0])));
paramsList.add(params.toArray(new String[0]));
}
}
return this.dbUpdateByBatch(infoSQL.toString(),paramsList);
}else{
return true;
}
}*/
/**
* 查询数据 封装方法
*
* @time Jul 27, 2011-4:08:38 PM
* @param attributes
* @param fields{
*
* @param tableName
* @param info
* @return
* @throws Exception
*/
/*private ArrayList<Map<String, String>> selectObjs(ArrayList<String> fields,
String tableName, Map<String, String> info) throws Exception {
StringBuffer seachInfoSQL = new StringBuffer(); // 查询SQL
if (fields == null || fields.size() == 0) { // 全部字段查询
seachInfoSQL.append("select * from " + tableName + " where 1=1 ");
} else { // 指定字段查询
seachInfoSQL.append("select ");
for (String attribute : fields) {
seachInfoSQL.append(attribute + ",");
}
seachInfoSQL.deleteCharAt(seachInfoSQL.length() - 1);
seachInfoSQL.append(" from " + tableName + " where 1=1 ");
}
// SQL拼写
Iterator<Entry<String, String>> ite = info.entrySet().iterator();
ArrayList<String> params = new ArrayList<String>();
while (ite.hasNext()) {
Entry<String, String> entry = ite.next();
if (StringUtils.isEmpty(entry.getValue()))
continue;
params.add(entry.getValue());
if (Common.isDate(entry.getValue(), Constants.COMMON_DATE_FORMAT)) {
seachInfoSQL.append(" and to_char(" + entry.getKey() + ",'"
+ Constants.DB_DATE_FORMAT + "') = ?");
} else {
seachInfoSQL.append(" and " + entry.getKey() + "=?");
}
}
return this.dbSelect(seachInfoSQL.toString(), fields, params.toArray());
}*/
}

View File

@@ -0,0 +1,473 @@
package com.nms.server.dao;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import com.nms.server.common.Constants;
/**
* oracle 特殊函数 适配 mysql 数据库 sql 转换工具
* @author fang
*
*/
public class OracleToMysql {
static final Logger logger = Logger.getLogger(OracleToMysql.class);
/**
* decode函数正则匹配不支持括号嵌套
*/
static final Pattern DECODE_PATTERN = Pattern.compile("([^\\w]+)decode\\s*\\(([^\\(\\)]*)\\)",Pattern.CASE_INSENSITIVE);
/**
* nvl函数正则匹配
*/
static final Pattern NVL_PATTERN = Pattern.compile("[^\\w]+(nvl)\\s*\\(",Pattern.CASE_INSENSITIVE);
/**
* sysdate
*/
static final Pattern SYSDATE_PATTERN = Pattern.compile("[^\\w]+(sysdate)[^\\w]+",Pattern.CASE_INSENSITIVE);
/**
* sysdate-1 oracle 日期加减
* ([^\\w]+)(sysdate\\s*([-+])\\s*(\\w+))([^\\w]+)
*/
static final Pattern DATE_CAL_PATTERN = Pattern.compile("([^\\w]+)(sysdate\\s*([-+])\\s*([0-9/]+))([^\\w]+|$)",Pattern.CASE_INSENSITIVE);
/**
* nextval
*/
static final Pattern NEXTVAL_PATTERN = Pattern.compile("([^\\w]+)([\\w]+)\\s*\\.\\s*nextval([^\\w]+)",Pattern.CASE_INSENSITIVE);
/**
* currval
*/
static final Pattern CURRVAL_PATTERN = Pattern.compile("([^\\w]+)([\\w]+)\\s*\\.\\s*currval([^\\w]+)",Pattern.CASE_INSENSITIVE);
/**
* to_date
*/
static final Pattern TO_DATE_PATTERN = Pattern.compile("([\\W])to_date\\s*\\(([^\\)]+),([^\\)]+)",Pattern.CASE_INSENSITIVE);
/**
* to_char
*/
static final Pattern TO_CHAR_PATTERN = Pattern.compile("([\\W])to_char\\s*\\(([^\\)]+),([^\\)]+)",Pattern.CASE_INSENSITIVE);
/**
* 数字 转字符
*/
static final Pattern TO_CHAR_CAST_PATTERN = Pattern.compile("([\\W])to_char\\s*\\(([^\\),]+)",Pattern.CASE_INSENSITIVE);
/**
* trunc 函数截取日期 只匹配 sysdate 转换成 date_add 的语句
*/
static final Pattern TRUNC_DATE_PATTERN = Pattern.compile("[^\\w]+(trunc)\\s*\\(\\s*date_add",Pattern.CASE_INSENSITIVE);
/**
* instr函数
*/
static final Pattern INSTR_PATTERN = Pattern.compile("([^\\w]+)(instr)\\s*\\(([^\\)]+)\\)",Pattern.CASE_INSENSITIVE);
/**
* where 条件中的rownum
*/
//static final Pattern WHERE_ROWNUM_PATTERN = Pattern.compile("([^\\w]+)where([^\\)]+)rownum\\s*(<?=?)\\s*(\\d+)([^\\)]*)",Pattern.CASE_INSENSITIVE);
/**
* 有些函数参数会出现如下情况 '1,' ,无法正常通过逗号分割
*/
static final Pattern DYH_PATTERN = Pattern.compile("('.+')",Pattern.CASE_INSENSITIVE);
static final LinkedHashMap<String, String> DATEFORMAT_MAPPING = new LinkedHashMap<String, String>();
static{
/*DATEFORMAT_MAPPING.put("","%a");//工作日的缩写名称  (Sun..Sat)
DATEFORMAT_MAPPING.put("","%b");//月份的缩写名称  (Jan..Dec)
DATEFORMAT_MAPPING.put("","%c");//月份,数字形式(0..12)
DATEFORMAT_MAPPING.put("","%D");//带有英语后缀的该月日期  (0th, 1st, 2nd, 3rd, ...)
DATEFORMAT_MAPPING.put("","%d");//该月日期, 数字形式 (00..31)
DATEFORMAT_MAPPING.put("","%e");//该月日期, 数字形式(0..31)
DATEFORMAT_MAPPING.put("","%f");//微秒 (000000..999999)
DATEFORMAT_MAPPING.put("","%H");//小时(00..23)
DATEFORMAT_MAPPING.put("","%h");//小时(01..12)
DATEFORMAT_MAPPING.put("","%I");//小时 (01..12)
DATEFORMAT_MAPPING.put("","%i");//分钟,数字形式 (00..59)
DATEFORMAT_MAPPING.put("","%j");//一年中的天数 (001..366)
DATEFORMAT_MAPPING.put("","%k");//小时 (0..23)
DATEFORMAT_MAPPING.put("","%l");//小时 (1..12)
DATEFORMAT_MAPPING.put("","%M");//月份名称 (January..December)
DATEFORMAT_MAPPING.put("","%m");//月份, 数字形式 (00..12)
DATEFORMAT_MAPPING.put("","%p");//上午AM或下午 PM
DATEFORMAT_MAPPING.put("","%r");//时间 , 12小时制 (小时hh:分钟mm:秒数ss 后加 AM或PM)
DATEFORMAT_MAPPING.put("","%S");//秒 (00..59)
DATEFORMAT_MAPPING.put("","%s");//秒 (00..59)
DATEFORMAT_MAPPING.put("","%T");//时间 , 24小时制 (小时hh:分钟mm:秒数ss)
DATEFORMAT_MAPPING.put("","%U");//周 (00..53), 其中周日为每周的第一天
DATEFORMAT_MAPPING.put("","%u");//周 (00..53), 其中周一为每周的第一天 
DATEFORMAT_MAPPING.put("","%V");//周 (01..53), 其中周日为每周的第一天 ; 和 %X同时使用
DATEFORMAT_MAPPING.put("","%v");//周 (01..53), 其中周一为每周的第一天 ; 和 %x同时使用
DATEFORMAT_MAPPING.put("","%W");//工作日名称 (周日..周六)
DATEFORMAT_MAPPING.put("","%w");//一周中的每日 (0=周日..6=周六)
DATEFORMAT_MAPPING.put("","%X");//该周的年份,其中周日为每周的第一天, 数字形式,4位数;和%V同时使用
DATEFORMAT_MAPPING.put("","%x");//该周的年份,其中周一为每周的第一天, 数字形式,4位数;和%v同时使用
DATEFORMAT_MAPPING.put("","%Y");//年份, 数字形式,4位数
DATEFORMAT_MAPPING.put("","%y");//年份, 数字形式 (2位数)
*/
DATEFORMAT_MAPPING.put("YYYY-MM-DD HH24:MI:SS","%Y-%m-%d %H:%i:%s");
DATEFORMAT_MAPPING.put("YYYY-MM-DD HH24:MI","%Y-%m-%d %H:%i");
DATEFORMAT_MAPPING.put("YYYY-MM-DD","%Y-%m-%d");
DATEFORMAT_MAPPING.put("HH24:MI:SS","%H:%i:%s");
}
/**
* oracle sql 转换 成 mysql
* @param sql
* @return
*/
public static String trans(String sql){
// Objects.requireNonNull(sql, "sql语句不能为空");
Objects.requireNonNull(sql, "The SQL statement cannot be empty");
logger.debug("before sql -> " + sql);
if(Constants.IS_MYSQL){
sql = decodeToCaseWhen(sql);
sql = nextvalToFunction(sql);
sql = currvalToFunction(sql);
sql = toCharToDateFormat(sql);
sql = toDateToStrtodate(sql);
sql = nvlToIfnull(sql);
sql = sysdateCal(sql);
sql = sysdateToNow(sql);
sql = truncSysdate(sql);
//sql = instr(sql); //@2018年4月19日15:46:47 直接修改 sql 语句,将 第3,4个参数删除都是默认 1
sql = toChar(sql);
logger.debug("after sql -> " + sql);
}
return sql;
}
/**
* oracle decode函数 转换为 case when 语句
* @param decode
* @return
*/
public static String decodeToCaseWhen(String sql){
// Objects.requireNonNull(sql, "sql语句不能为空");
Objects.requireNonNull(sql, "The SQL statement cannot be empty");
Matcher m = DECODE_PATTERN.matcher(sql);
StringBuffer sb = new StringBuffer();
while(m.find()){
String group = m.group(2);
String[] split = group.split(",");
int len = split.length;
StringBuilder caseWhen = new StringBuilder(m.group(1));
caseWhen.append(" ( case ");
caseWhen.append(split[0]);
for(int i = 1;i<len-1;i=i+2){
caseWhen.append(" when ");
caseWhen.append(split[i]);
caseWhen.append(" then ");
caseWhen.append(split[i+1]);
}
if(len%2 == 0){
caseWhen.append(" else ");
caseWhen.append(split[len-1]);
}
caseWhen.append(" end ) ");
logger.debug(m.group() +" --> "+caseWhen.toString());
m.appendReplacement(sb, caseWhen.toString());
}
m.appendTail(sb);
return sb.toString();
}
/**
* oracle nvl 转成 mysql ifNull
* @param sql
* @return
*/
public static String nvlToIfnull(String sql){
return regexReplace(sql, NVL_PATTERN, "IFNULL" ,1);
}
/**
* sysdate 转成 now()
* @param sql
* @return
*/
public static String sysdateToNow(String sql){
return regexReplace(sql, SYSDATE_PATTERN, "now()" ,1);
}
/**
* trunc 函数截取日期 只匹配 sysdate 转换成 date_add 的语句
* @param sql
* @return
*/
public static String truncSysdate(String sql){
return regexReplace(sql, TRUNC_DATE_PATTERN, "date" ,1);
}
/**
* sysdate 日期加减
* ([^\\w]+)(sysdate\\s*([-+])\\s*((\\d+/)*\\d+))([^\\w]+)
* @param sql
* @return
*/
public static String sysdateCal(String sql){
// Objects.requireNonNull(sql, "sql语句不能为空");
Objects.requireNonNull(sql, "The SQL statement cannot be empty");
Matcher m = DATE_CAL_PATTERN.matcher(sql);
StringBuffer sb = new StringBuffer();
while(m.find()){
StringBuilder temp = new StringBuilder();
String signal = m.group(3);//signal - +
String number = m.group(4);// \\d+
temp.append(m.group(1));
temp.append("date_add(now(),interval ");
temp.append(signal);
temp.append(number);
temp.append("*24*60*60 second)");
temp.append(m.group(5));
logger.debug(m.group() +" --> "+temp.toString());
m.appendReplacement(sb, temp.toString());
}
m.appendTail(sb);
return sb.toString();
}
/**
* oracle 序列 转成 mysql 自定义函数 nextval('')
* @return
*/
public static String nextvalToFunction(String sql){
// Objects.requireNonNull(sql, "sql语句不能为空");
Objects.requireNonNull(sql, "The SQL statement cannot be empty");
Matcher m = NEXTVAL_PATTERN.matcher(sql);
StringBuffer sb = new StringBuffer();
while(m.find()){
StringBuilder temp = new StringBuilder();
String seqName = m.group(2);//seq name
temp.append(m.group(1));
temp.append(Constants.NEXTVAL_FUNCTION_NAME);
temp.append("('");
temp.append(seqName);
temp.append("')");
temp.append(m.group(3));
logger.debug(m.group() +" --> "+temp.toString());
m.appendReplacement(sb, temp.toString());
}
m.appendTail(sb);
return sb.toString();
}
/**
* oracle 序列 转成 mysql 自定义函数 currval('')
* @return
*/
public static String currvalToFunction(String sql){
// Objects.requireNonNull(sql, "sql语句不能为空");
Objects.requireNonNull(sql, "The SQL statement cannot be empty");
Matcher m = CURRVAL_PATTERN.matcher(sql);
StringBuffer sb = new StringBuffer();
while(m.find()){
StringBuilder temp = new StringBuilder();
String seqName = m.group(2);//seq name
temp.append(m.group(1));
temp.append(Constants.CURRVAL_FUNCTION_NAME);
temp.append("('");
temp.append(seqName);
temp.append("')");
temp.append(m.group(3));
logger.debug(m.group() +" --> "+temp.toString());
m.appendReplacement(sb, temp.toString());
}
m.appendTail(sb);
return sb.toString();
}
/**
* oracle to_date 函数 转换为 str_to_date
* @param sql
* @return
*/
public static String toDateToStrtodate(String sql){
// Objects.requireNonNull(sql, "sql语句不能为空");
Objects.requireNonNull(sql, "The SQL statement cannot be empty");
Matcher m = TO_DATE_PATTERN.matcher(sql);
StringBuffer sb = new StringBuffer();
while(m.find()){
StringBuilder temp = new StringBuilder();
String fm = m.group(3);//seq name
String mfm = DATEFORMAT_MAPPING.get(fm.replaceAll("'", "").trim().toUpperCase());
// Objects.requireNonNull(mfm, fm + " 没有mysql格式化映射");
Objects.requireNonNull(mfm, fm + " No MySQL formatting mappings");
temp.append(m.group(1));
temp.append("str_to_date(");
temp.append(m.group(2));
temp.append(",'");
temp.append(mfm);
temp.append("'");
logger.debug(m.group() +" --> "+temp.toString());
m.appendReplacement(sb, temp.toString());
}
m.appendTail(sb);
return sb.toString();
}
/**
* oracle to_char 函数 转换为 date_format
* @param sql
* @return
*/
public static String toCharToDateFormat(String sql){
// Objects.requireNonNull(sql, "sql语句不能为空");
Objects.requireNonNull(sql, "The SQL statement cannot be empty");
Matcher m = TO_CHAR_PATTERN.matcher(sql);
StringBuffer sb = new StringBuffer();
while(m.find()){
StringBuilder temp = new StringBuilder();
String fm = m.group(3);//seq name
String mfm = DATEFORMAT_MAPPING.get(fm.replaceAll("'", "").trim().toUpperCase());
// Objects.requireNonNull(mfm, m.group() + " 没有mysql格式化映射");
Objects.requireNonNull(mfm, m.group() + " No MySQL formatting mappings");
temp.append(m.group(1));
temp.append("date_format(");
temp.append(m.group(2));
temp.append(",'");
temp.append(mfm);
temp.append("'");
logger.debug(m.group() +" --> "+temp.toString());
m.appendReplacement(sb, temp.toString());
}
m.appendTail(sb);
return sb.toString();
}
/**
* 数字转字符,只匹配 to_char 有一个参数的
* ([\\W]+)to_char\\s*\\(([^\\),]+))
* @param sql
* @return
*/
public static String toChar(String sql){
// Objects.requireNonNull(sql, "sql语句不能为空");
Objects.requireNonNull(sql, "The SQL statement cannot be empty");
Matcher m = TO_CHAR_CAST_PATTERN.matcher(sql);
StringBuffer sb = new StringBuffer();
while(m.find()){
StringBuilder temp = new StringBuilder();
temp.append(m.group(1));
temp.append(" convert(");
temp.append(m.group(2));
temp.append(" , CHAR ");
logger.debug(m.group() +" --> "+temp.toString());
m.appendReplacement(sb, temp.toString());
}
m.appendTail(sb);
return sb.toString();
}
/**
* instr mysql 只有两个参数
* 查遍所有 instr 函数,第三四个参数都为 1可以省略若不为 1 则不能使用此函数
* ([^\\w]+)(instr)\\s*\\(([^\\)]+)\\)
* @param sql
* @return
*/
public static String instr(String sql){
// Objects.requireNonNull(sql, "sql语句不能为空");
Objects.requireNonNull(sql, "The SQL statement cannot be empty");
Matcher m = INSTR_PATTERN.matcher(sql);
StringBuffer sb = new StringBuffer();
while(m.find()){
StringBuilder temp = new StringBuilder();
String param = m.group(3);//seq name
Matcher dyh = DYH_PATTERN.matcher(param);
StringBuffer ss = new StringBuffer();
while(dyh.find()){
String group = dyh.group(1);
group = group.replaceAll(",", "@@@");
dyh.appendReplacement(ss, group);
}
dyh.appendTail(ss);
String[] params = ss.toString().split(",");
temp.append(m.group(1));
temp.append("instr(");
temp.append(params[0].replaceAll("@@@", ","));
temp.append(",");
temp.append(params[1].replaceAll("@@@", ","));
temp.append(")");
logger.debug(m.group() +" --> "+temp.toString());
m.appendReplacement(sb, temp.toString());
}
m.appendTail(sb);
return sb.toString();
}
/**
* 替换 rownum -> limit
* ([^\\w]+)where([^\\)]+)rownum\\s*(<?=?)\\s*(\\d+)([^\\)]*)
* @param sql
* @return
*/
/*public static String whereRownum(String sql){
Objects.requireNonNull(sql, "sql语句不能为空");
Matcher m = WHERE_ROWNUM_PATTERN.matcher(sql);
StringBuffer sb = new StringBuffer();
while(m.find()){
StringBuilder temp = new StringBuilder();
String signal = m.group(3);
int num = Integer.valueOf(m.group(4).trim());
if(!signal.contains("=")){
num = num -1;
}
temp.append(m.group(1));
temp.append("where");
temp.append(m.group(2));
temp.append(" 1=1 ");
temp.append(m.group(5));
temp.append(" limit ");
temp.append(num);
logger.debug(m.group() +" --> "+temp.toString());
m.appendReplacement(sb, temp.toString());
}
m.appendTail(sb);
return sb.toString();
}*/
/**
* 正则替换
* @param sql
* @param p
* @param replace
* @return
*/
private static String regexReplace(String sql,Pattern p,String replace,Integer groupNum){
// Objects.requireNonNull(sql, "sql语句不能为空");
Objects.requireNonNull(sql, "The SQL statement cannot be empty");
Matcher m = p.matcher(sql);
StringBuffer sb = new StringBuffer();
while(m.find()){
String group = m.group();
if(groupNum != null && groupNum > 0){
String gn = m.group(groupNum);
group = group.replace(gn, replace);
}
logger.debug(m.group() +" --> "+group);
m.appendReplacement(sb, group);
}
m.appendTail(sb);
return sb.toString();
}
public static void main(String[] args) {
String sql = "delete event_record_library where create_time < sysdate-4 and sysdate -4 > now()";
sql = trans(sql);
System.out.println(sql);
}
}

View File

@@ -0,0 +1,290 @@
package com.nms.server.service;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.EventRecordLibrary;
import com.nms.server.bean.ServerIpSegment;
import com.nms.server.bean.ServerTable;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
/**
* <p>变更操作</p>
* <p>针对操作变更未及时下发到指定Client而进行的后续操作</p>
* @date Mar 6, 2012 8:33:40 AM
* @author ZhangGang
*
*/
public class ChangeService extends CommonService{
private Logger logger = Logger.getLogger(ChangeService.class);
public ChangeService(CommonDao dao){
super(dao);
}
public List<EventRecordLibrary> getNewEventRecordList() {
SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
List<EventRecordLibrary> erlList = new LinkedList<EventRecordLibrary>();
StringBuffer sql = new StringBuffer();
sql.append("select ");
sql.append("erl.id, ");
sql.append("erl.record_type, ");
sql.append("erl.record_content, ");
sql.append("erl.seq_ids, ");
sql.append("erl.record_command, ");
sql.append("to_char(erl.create_time,'"+Constants.DB_DATE_FORMAT+"') create_time, ");
sql.append("erl.state ");
sql.append("from event_record_library erl ");
sql.append("where erl.state = 1 ");
sql.append("and erl.NMSSERVER_ID = "+Common.getServerTable().getId());
sql.append(" order by erl.create_time asc");
ArrayList<String> fields = new ArrayList<String>();
fields.add("id");
fields.add("state");
fields.add("record_type");
fields.add("record_command");
fields.add("record_content");
fields.add("seq_ids");
fields.add("create_time");
try {
List<Map<String, String>> maps = dao.dbSelect(sql.toString(), fields);
if (maps!=null && maps.size()>0) {
for (Map<String, String> map : maps) {
EventRecordLibrary erl = new EventRecordLibrary();
erl.setId(StringUtils.isEmpty(map.get("id"))?null:Long.parseLong(map.get("id")));
erl.setState(StringUtils.isEmpty(map.get("state"))?null:Long.parseLong(map.get("state")));
erl.setRecordType(map.get("record_type"));
erl.setRecordCommand(map.get("record_command"));
erl.setRecordContent(map.get("record_content"));
erl.setSeqId(StringUtils.isEmpty(map.get("seq_ids"))?null:Long.parseLong(map.get("seq_ids")));
erl.setCreateTime(StringUtils.isEmpty(map.get("create_time"))?null:format.parse(map.get("create_time")));
erlList.add(erl);
}
}
} catch (Exception e) {
logger.error("EventRecordLibrary encapsulates ERROR",e);
}finally{
dao.clearConn();
}
return erlList;
}
public void saveEventRecordLibrary(String cmd,String seq_id,String type, String content) {
SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
try {
Map<String, String> library = new HashMap<String, String>();
library.put("record_command", cmd);
library.put("record_content", content);
library.put("record_type", type);
library.put("seq_ids", seq_id);
library.put("state", "1");
library.put("NMSSERVER_ID", ""+Common.getServerTable().getId());
library.put("create_time", format.format(System.currentTimeMillis()));
// System.out.println("record_command"+ cmd);
// System.out.println("record_content"+ content);
// System.out.println("record_type"+ type);
// System.out.println("seq_ids"+ seq_id);
// System.out.println("state"+ "1");
// System.out.println("NMSSERVER_ID"+ ""+Common.getServerTable().getId());
// System.out.println("create_time"+ format.format(System.currentTimeMillis()));
dao.insertObj("event_record_library",library);
} catch (Exception e) {
logger.error("Change record save failure", e);
}finally{
dao.clearConn();
}
}
public void updateEventRecordLibrary(EventRecordLibrary event,String createTime,String content) {
if(event.getId() == null){
return ;
}
String sql = "update event_record_library erl set RECORD_CONTENT='"+content+"' ,CREATE_TIME=to_date('"+createTime+"','yyyy-MM-dd HH24:mi:ss' ) where id="+event.getId();
try {
dao.dbUpdate(sql);
} catch (Exception e) {
logger.error("Update the event_record_library exception: Record ID="+event.getId(),e);
}finally{
dao.clearConn();
}
}
public void deleteEventRecordBySeqId(Long id) {
if(id == null ){
return ;
}
String sql = "delete from event_record_library where lower(RECORD_TYPE)=lower('S2C') and SEQ_IDS = '"+id.longValue()+"'";
try {
dao.dbUpdate(sql);
} catch (Exception e) {
logger.error("",e);
}finally{
dao.clearConn();
}
}
public void deleteEventRecordByIds(String ids) {
if(StringUtils.isEmpty(ids)){
return ;
}
String sql = "delete from event_record_library where id in ("+ids+")";
try {
dao.dbUpdate(sql);
} catch (Exception e) {
logger.error("",e);
}finally{
dao.clearConn();
}
}
public void deleteEventRecordOldInfo() {
// String sql = "delete event_record_library t where sysdate - t.create_time > 4";
String sql = "delete from event_record_library where create_time < sysdate-4 ";
try {
dao.dbUpdate(sql);
} catch (Exception e) {
logger.error("",e);
}finally{
dao.clearConn();
}
}
public EventRecordLibrary selectEventRecordInfo(String recordType,String recordCommand,String seqId) {
EventRecordLibrary event = null;
try {
if(StringUtils.isBlank(seqId)) {
return event;
}
ArrayList<Map<String,String>> mapList = null;
ArrayList<String> fields = new ArrayList<String>();
fields.clear();
fields.add("id");
fields.add("RECORD_TYPE");
fields.add("RECORD_CONTENT");
fields.add("SEQ_IDS");
fields.add("RECORD_COMMAND");
fields.add("CREATE_TIME");
fields.add("NMSSERVER_ID");
mapList = dao.dbSelect(" select ID,RECORD_TYPE,RECORD_CONTENT,SEQ_IDS,RECORD_COMMAND,CREATE_TIME,NMSSERVER_ID " +
" from event_record_library erl " +
" where erl.RECORD_TYPE='"+recordType+"' and erl.RECORD_COMMAND='"+recordCommand+"' and erl.SEQ_IDS=" + Long.parseLong(seqId.trim()) +
" order by erl.CREATE_TIME desc",fields);
if(mapList!=null && mapList.size()>0){
Map<String,String> map = mapList.get(0);
if(StringUtils.isNotBlank(map.get("id")) ) {
event = new EventRecordLibrary();
event.setId(Long.valueOf(map.get("id")));
event.setRecordType(map.get("RECORD_TYPE"));
event.setRecordContent(map.get("RECORD_CONTENT"));
event.setSeqId(StringUtils.isBlank(map.get("SEQ_IDS"))? null:Long.valueOf(map.get("SEQ_IDS")));
event.setRecordCommand(map.get("RECORD_COMMAND"));
}
}
} catch (Exception e1) {
logger.error("Query the event_record_library table exception",e1);
}finally{
dao.clearConn();
}
return event;
}
/*public static void main(String [] args) {
CommonDao dao = null;
ChangeService service = null;
try {
dao = new CommonDao();
service = new ChangeService(new CommonDao());
Common.setServerTable(service.getNMSServerParams("10.0.6.242"));
List<EventRecordLibrary> list = service.getNewEventRecordList();
for (int i = 0; i < list.size(); i++) {
EventRecordLibrary library = list.get(i);
pl(library.getId()+" "+library.getSeqId()+" "+library.getRecordType()+" "+library.getState());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(dao!=null)dao.close();
}
}*/
public ServerTable getNMSServerParams(String ip) throws Exception{
ServerTable serverTable = null;
try {
//查询server 信息
ArrayList<String> fields = new ArrayList<String>();
fields.add("id");
fields.add("server_name");
fields.add("server_state");
fields.add("server_ip");
fields.add("server_ipn");
ArrayList<Map<String, String>> mapsList = dao.dbSelect("select st.id,st.server_name,st.server_state, st.server_ip,st.server_ipn from server_table st where st.server_ip='" + ip + "'", fields);
// pl(""+mapsList.size());
if(mapsList!=null && mapsList.size()>0){
serverTable = new ServerTable();
Map<String, String> map = mapsList.get(0);
serverTable.setId(StringUtils.isEmpty(map.get(fields.get(0))) ? null : Long.parseLong(map.get(fields.get(0))));
serverTable.setServerName(StringUtils.isEmpty(map.get(fields.get(1))) ? null : map.get(fields.get(1)));
serverTable.setServerState(StringUtils.isEmpty(map.get(fields.get(2))) ? null : Long.parseLong(map.get(fields.get(2))));
serverTable.setServerIp(StringUtils.isEmpty(map.get(fields.get(3))) ? null : map.get(fields.get(3)));
serverTable.setServerIpn(StringUtils.isEmpty(map.get(fields.get(4))) ? null : Long.parseLong(map.get(fields.get(4))));
}else{
// throw new Exception("IP为 "+ip+" 的DataController信息 数据库中不存在请检查网络设置或进行人工DataController配置");
throw new Exception("IP does not exist in the DataController information database for "+ip+" Check the network settings or manual DataController configuration");
}
//查询server 的管理IP段信息
if(serverTable!= null && serverTable.getId()!=null){
serverTable.setIpSegList(new LinkedList<ServerIpSegment>());
fields.clear();
fields.add("start_ip");
fields.add("start_ipn");
fields.add("end_ip");
fields.add("end_ipn");
mapsList = dao.dbSelect("select sis.start_ip,sis.start_ipn,sis.end_ip,sis.end_ipn from server_ip_segment sis where sis.server_id='" + serverTable.getId().longValue() + "'", fields);
// pl(""+mapsList.size());
if(mapsList!=null && mapsList.size()>0){
for(Map<String, String> map : mapsList){
ServerIpSegment segment = new ServerIpSegment();
segment.setStartIp(StringUtils.isEmpty(map.get(fields.get(0))) ? null : map.get(fields.get(0)));
segment.setStartIpn(StringUtils.isEmpty(map.get(fields.get(1))) ? null : Long.parseLong(map.get(fields.get(1))));
segment.setEndIp(StringUtils.isEmpty(map.get(fields.get(2))) ? null : map.get(fields.get(2)));
segment.setEndIpn(StringUtils.isEmpty(map.get(fields.get(3))) ? null : Long.parseLong(map.get(fields.get(3))));
serverTable.getIpSegList().add(segment);
}
}else{
// throw new Exception("IP为 "+ip+" 的DataController的IP段信息 数据库中不存在 请进行人工配置");
throw new Exception("IP does not exist in the "+ip+" segment information database of DataController for IP. Please configure manually");
}
}else{
// throw new Exception("IP为 "+ip+" 的DataController信息 查询异常 无法查询出ID");
throw new Exception("DataController information with IP "+ip+" query exception Unable to query ID");
}
} catch (Exception e) {
logger.error("By parameter"+ ip+" to get node information failure",e);
}finally{
dao.clearConn();
}
return serverTable;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,707 @@
package com.nms.server.service;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.ContactSetInfo;
import com.nms.server.bean.EmailInfo;
import com.nms.server.common.CommonResources;
import com.nms.server.common.Constants;
import com.nms.server.common.EmailTypeConstants;
import com.nms.server.dao.CommonDao;
import com.nms.server.util.SQLExecuteTimeoutException;
/**
* 创建并保存邮件信息
* 查询邮件信息并将邮件信息整理成单一邮件进行查询
* @date Feb 6, 2012 10:17:56 AM
* @author ZhangGang
*
*/
public class EmailService {
private final Logger logger = Logger.getLogger(EmailService.class);
SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
private CommonDao dao = null;
public EmailService(CommonDao dao){
this.dao = dao;
}
public List<EmailInfo> getEmailInfoList(){
String selectSql = "select et.id , et.to_address ,et.action_type ,et.action_desc ,et.action_ip ,to_char(et.action_date,'"+Constants.DB_DATE_FORMAT+"') action_date,et.content from email_table et where et.send_flag = ? order by et.to_address asc,et.action_type asc,et.action_desc asc,et.action_ip asc,et.action_date asc";
ArrayList<String> fields = new ArrayList<String>();
fields.add("id");
fields.add("to_address");
fields.add("action_type");
fields.add("action_desc");
fields.add("action_ip");
fields.add("action_date");
fields.add("content");
Object [] params = new Object[]{EmailTypeConstants.FLAG_SEND_LATER};
List<EmailInfo> eiList = new LinkedList<EmailInfo>();
try {
ArrayList<Map<String, String>> mapsList = dao.dbSelect(selectSql, fields, EmailTypeConstants.FLAG_SEND_LATER);
if(mapsList!=null && mapsList.size()>0){
for(Map<String, String> maps : mapsList){
EmailInfo ei = new EmailInfo();
ei.setId(StringUtils.isEmpty(maps.get("id"))?null:Long.parseLong(maps.get("id")));
ei.setToAddress(maps.get("to_address"));
ei.setActionType(StringUtils.isEmpty(maps.get("action_type"))?null:Integer.parseInt(maps.get("action_type")));
ei.setActionDesc(maps.get("action_desc"));
ei.setActionIp(maps.get("action_ip"));
ei.setActionDate(maps.get("action_date"));
ei.setContent(maps.get("content"));
eiList.add(ei);
}
}
} catch (SQLException e) {
logger.error("Failure of mail information query", e);
}
return eiList;
}
public String getEmailTypeDescByTypeValue(int type){
switch (type) {
case EmailTypeConstants.TYPE_DETECTION_INFO_RECOVER:
return EmailTypeConstants.DESC_DETECTION_INFO_RECOVER;
case EmailTypeConstants.TYPE_DETECTION_INFO_EXCEPTION:
return EmailTypeConstants.DESC_DETECTION_INFO_EXCEPTION;
case EmailTypeConstants.TYPE_DETECTION_INFO_TIMEOUT:
return EmailTypeConstants.DESC_DETECTION_INFO_TIMEOUT;
case EmailTypeConstants.TYPE_ALARM_INFO_EXCEPTION:
return EmailTypeConstants.DESC_ALARM_INFO_EXCEPTION;
case EmailTypeConstants.TYPE_ALARM_INFO_RECOVER:
return EmailTypeConstants.DESC_ALARM_INFO_RECOVER;
case EmailTypeConstants.TYPE_TASK_NODE_RESULT_ERROR:
return EmailTypeConstants.DESC_TASK_NODE_RESULT_ERROR;
case EmailTypeConstants.TYPE_TASK_STATE_CHANGE:
return EmailTypeConstants.DESC_TASK_STATE_CHANGE;
case EmailTypeConstants.TYPE_SYSTEM_RUNNING_EXCEPTION:
return EmailTypeConstants.DESC_SYSTEM_RUNNING_EXCEPTION;
case EmailTypeConstants.TYPE_SYSTEM_RUNNING_RECOVER:
return EmailTypeConstants.DESC_SYSTEM_RUNNING_RECOVER;
default:
return null;
}
}
public void sendEmailForDetectionBySeqId(Long dId,Long seqId,EmailInfo emailInfo){
//-- 邮件功能是否开启
if(Constants.flag_email != 1){
logger.info("邮件功能已关闭");
return;
}
//-- 数据校验 无效返回
if(dId==null || dId.longValue() == 0l || seqId==null || seqId.longValue() == 0l){
return;
}
//-- 查询联系人设置信息
ContactSetInfo contactSetInfo = this.getContactSetInfoByDetecId(dId);
//-- 获取联系人列表
List<EmailInfo> eiList = new LinkedList<EmailInfo>();
List<String> emaiList = this.getEmailList(contactSetInfo, seqId);
logger.debug("邮件数量 "+(emaiList==null?null:emaiList.size()));
if(emaiList!=null && emaiList.size()>0){
for (Iterator emailIte = emaiList.iterator(); emailIte.hasNext();) {
String addr = (String) emailIte.next();
if(StringUtils.isEmpty(addr))continue; //邮件地址不为空
EmailInfo emailInfo2 = new EmailInfo(emailInfo);
emailInfo2.setToAddress(addr);
eiList.add(emailInfo2);
}
try {
saveEmailInfoList(eiList);
} catch (SQLExecuteTimeoutException e) {
logger.error("",e);
} catch (SQLException e) {
logger.error("",e);
}
}
}
public void sendEmailForMissionBySeqId(Long mId,int missionType,Long seqId,EmailInfo emailInfo){
//-- 邮件功能是否开启
if(Constants.flag_email != 1){
logger.info("邮件功能已关闭");
return;
}
//-- 数据校验 无效返回
if(mId==null || mId.longValue() == 0l || missionType==0 || seqId==null || seqId.longValue() == 0l){
return;
}
//-- 查询联系人设置信息
ContactSetInfo contactSetInfo = this.getContactSetInfoByMissionId(mId);
//-- 获取联系人列表
List<EmailInfo> eiList = new LinkedList<EmailInfo>();
List<String> emaiList = this.getEmailList(contactSetInfo, seqId);
logger.debug("邮件数量 "+(emaiList==null?null:emaiList.size()));
//-- 发邮件
if(emaiList!=null && emaiList.size()>0){
for (Iterator emailIte = emaiList.iterator(); emailIte.hasNext();) {
String addr = (String) emailIte.next();
if(StringUtils.isEmpty(addr))continue;
EmailInfo emailInfo2 = new EmailInfo(emailInfo);
emailInfo2.setToAddress(addr);
eiList.add(emailInfo2);
}
}
try {
saveEmailInfoList(eiList);
} catch (SQLExecuteTimeoutException e) {
logger.error("",e);
} catch (SQLException e) {
logger.error("",e);
}
//-结束
}
/**
* 任务执行邮件通知方法
* 任务类型 1 根据 系统 用户组 指定用户处理
* 任务类型 4 根据 系统 用户组 指定用户处理
* 任务类型 6 根据 下发机器 的管理用户发送通知
* @time Mar 28, 2012-1:53:56 PM
* @param mission 任务信息
* @param emaiTitle 主题
* @param emailContext 内容
*/
public void sendEmailForMission(Long missionId,String emaiTitle,String emailContext){
//-- 邮件功能是否开启
if(Constants.flag_email != 1){
logger.info("邮件功能已关闭");
return;
}
//-- 参数校验
if(missionId==null || StringUtils.isEmpty(emaiTitle) || StringUtils.isEmpty(emailContext)){
return;
}
ContactSetInfo info = this.getContactSetInfoByMissionId(missionId);
LinkedList<String> emailList = null;
ResourceBundle res = ResourceBundle.getBundle(CommonResources.class.getName());
// ContactSetInfo info = getContactSetInfoByMissionId(mId,mType);
String startTime = "";
String endTime = "";
if(info.getStartTime()!=null){
startTime = format.format(info.getStartTime());
}
if(info.getEndTime()!=null){
endTime = format.format(info.getEndTime());
}
String sendInfo = "";
if(info.getMissionType().longValue()==4l){
// sendInfo += " \n周期任务" +(info.getIsLoop()==null?"否":(info.getIsLoop().longValue()==1l?"是":"否"));
// sendInfo += " \n计划执行时间" + startTime+" -- "+endTime;
// sendInfo += " \nPeriodic Task" +(info.getIsLoop()==null?"No":(info.getIsLoop().longValue()==1l?"Yes":"No"));
// sendInfo += " \nPlan Execution Time" + startTime+" -- "+endTime;
sendInfo += " \ni18n_server.EmailService.loopMission_n81i" +(info.getIsLoop()==null?"i18n_server.EmailService.no_n81i":(info.getIsLoop().longValue()==1l?"i18n_server.EmailService.yes_n81i":"i18n_server.EmailService.no_n81i"));
sendInfo += " \ni18n_server.EmailService.plantime_n81i" + startTime+" -- "+endTime;
}
// sendInfo += " \n任务状态" + res.getObject("ms_"+info.getMissionState().intValue())
// + " \n节点组" + info.getNodeGroupName()
// + " \n节点" + info.getNodeIpsName()
// + " \n" + emailContext;
// sendInfo += " \nTask state" + res.getObject("ms_"+info.getMissionState().intValue())
// + " \nNode Group" + info.getNodeGroupName()
// + " \nNode" + info.getNodeIpsName()
// + " \n" + emailContext;
sendInfo += " \ni18n_server.EmailService.missionState_n81i" + res.getObject("ms_"+info.getMissionState().intValue())
+ " \ni18n_server.EmailService.nodegroup_n81i" + info.getNodeGroupName()
+ " \ni18n_server.EmailService.node_n81i" + info.getNodeIpsName()
+ " \n" + emailContext;
EmailInfo emailInfo = new EmailInfo();
emailInfo.setActionDesc(info.getMissionName()+"("+res.getObject("mt_"+info.getMissionType().longValue())+")");
emailInfo.setActionDate(new SimpleDateFormat(Constants.COMMON_DATE_FORMAT).format(new Date()));
emailInfo.setActionType(EmailTypeConstants.TYPE_TASK_STATE_CHANGE);
emailInfo.setSendFlag(EmailTypeConstants.FLAG_SEND_LATER);
emailInfo.setContent(sendInfo);
emailInfo.setSendLevel(EmailTypeConstants.URGENT_IMMEDIATELY);//2013-6-24 hyx 任务状态改变由不紧急修改为紧急
//- 发送邮件业务
try {
//-- 查询联系人参数过滤
switch (info.getMissionType().intValue()) {
case 6:
info.setViewLevel(3l); // 升级部署 通知均为系统内通知
emailList = getEmailList(info, null);
break;
default: //任务1 任务4 均按原有业务发送邮件
emailList = getEmailList(info, null);
break;
}
logger.debug("邮件数量 "+(emailList==null?null:emailList.size()));
//-- 发送邮件
List<EmailInfo> eiList = new LinkedList<EmailInfo>();
if(emailList !=null && emailList.size()>0){
for (Iterator emailIte = emailList.iterator(); emailIte.hasNext();) {
String addr = (String) emailIte.next();
if(StringUtils.isEmpty(addr))continue;
EmailInfo emailInfo2 = new EmailInfo(emailInfo);
emailInfo2.setToAddress(addr);
eiList.add(emailInfo2);
}
saveEmailInfoList(eiList);
}
} catch (Exception e) {
logger.error("",e);
}
logger.info("任务下发 邮件通知 发送完成");
//-结束
}
public boolean saveEmailInfoList(List<EmailInfo> eiList) throws SQLExecuteTimeoutException,SQLException {
String insertSql = " insert into email_table (to_address,action_type,content,send_flag,action_ip,action_date,action_desc,send_level,CREATE_TIME)" +
" values(?,?,?,?,?,to_date(?,'"+Constants.DB_DATE_FORMAT+"'),?,?,to_date(?,'"+Constants.DB_DATE_FORMAT+"'))" ;
List<String[]> paramsList = new LinkedList<String[]>();
if(eiList != null && eiList.size()>0){
String createTime = format.format(new Date());
for(EmailInfo ei :eiList){
paramsList.add(new String[]{ei.getToAddress(),ei.getActionType()+"",ei.getContent(),ei.getSendFlag()+"",ei.getActionIp(),ei.getActionDate(),ei.getActionDesc(),/*ei.getActionDesc2(),*/ei.getSendLevel()==null?EmailTypeConstants.URGENT_LATER+"":ei.getSendLevel()+"",createTime});
}
return dao.dbUpdateByBatch(insertSql, paramsList);
}
return false;
}
/*private void sendEmailForDetectionBySeqId(Long dId,Long seqId,String emaiTitle,String emailContext){
//-- 数据校验 无效返回
if(dId==null || dId.longValue() == 0l || seqId==null || seqId.longValue() == 0l){
return;
}
//-- 查询联系人设置信息
ContactSetInfo contactSetInfo = this.getContactSetInfoByDetecId(dId);
//-- 获取联系人列表
List<String> emaiList = this.getEmailList(contactSetInfo, seqId);
logger.debug("邮件数量 "+(emaiList==null?null:emaiList.size()));
//-- 发邮件
if(emaiList!=null && emaiList.size()>0){
SendMail cn = new SendMail();
for (Iterator emailIte = emaiList.iterator(); emailIte.hasNext();) {
String addr = (String) emailIte.next();
if(StringUtils.isEmpty(addr))continue;
logger.debug("邮件 To "+(addr));
// 设置发件人地址、收件人地址和邮件标题
cn.setAddress(Constants.EMAIL_ADDRESS, addr, emaiTitle);
cn.send(emailContext);
}
}
//-结束
}*/
/*private void sendEmailForMissionBySeqId(Long mId,int missionType,Long seqId,String emaiTitle,String emailContext){
//-- 数据校验 无效返回
if(mId==null || mId.longValue() == 0l || missionType==0 || seqId==null || seqId.longValue() == 0l){
return;
}
//-- 查询联系人设置信息
ContactSetInfo contactSetInfo = this.getContactSetInfoByMissionId(mId);
//-- 获取联系人列表
List<String> emaiList = this.getEmailList(contactSetInfo, seqId);
logger.debug("邮件数量 "+(emaiList==null?null:emaiList.size()));
//-- 发邮件
if(emaiList!=null && emaiList.size()>0){
SendMail cn = new SendMail();
for (Iterator emailIte = emaiList.iterator(); emailIte.hasNext();) {
String addr = (String) emailIte.next();
if(StringUtils.isEmpty(addr))continue;
logger.debug("邮件 To "+(addr));
// 设置发件人地址、收件人地址和邮件标题
cn.setAddress(Constants.EMAIL_ADDRESS, addr, emaiTitle);
cn.send(emailContext);
}
}
//-结束
}*/
/**
* 任务执行邮件通知方法
* 任务类型 1 根据 系统 用户组 指定用户处理
* 任务类型 4 根据 系统 用户组 指定用户处理
* 任务类型 6 根据 下发机器 的管理用户发送通知
* @time Mar 28, 2012-1:53:56 PM
* @param mission 任务信息
* @param emaiTitle 主题
* @param emailContext 内容
*/
/*private void sendEmailForMission(Long missionId,String emaiTitle,String emailContext){
//-- 参数校验
if(missionId==null || StringUtils.isEmpty(emaiTitle) || StringUtils.isEmpty(emailContext)){
return;
}
ContactSetInfo info = this.getContactSetInfoByMissionId(missionId);
LinkedList<String> emailList = null;
ResourceBundle res = ResourceBundle.getBundle(CommonResources.class.getName());
// ContactSetInfo info = getContactSetInfoByMissionId(mId,mType);
String startTime = "";
String endTime = "";
if(info.getStartTime()!=null){
startTime = format.format(info.getStartTime());
}
if(info.getEndTime()!=null){
endTime = format.format(info.getEndTime());
}
String sendInfo = "任务名称:"+info.getMissionName()
+ " \n任务类型" + res.getObject("mt_"+info.getMissionType().longValue());
if(info.getMissionType().longValue()==4l){
sendInfo += " \n周期任务" +(info.getIsLoop()==null?"否":(info.getIsLoop().longValue()==1l?"是":"否"));
}
sendInfo += " \n任务状态" + res.getObject("ms_"+info.getMissionState().intValue());
sendInfo += " \n计划执行时间" + startTime+" -- "+endTime
+ " \n节点组" + info.getNodeGroupName()
+ " \n节点" + info.getNodeIpsName()
+ " \n" + emailContext;
//- 发送邮件业务
try {
//-- 查询联系人参数过滤
switch (info.getMissionType().intValue()) {
case 6:
info.setViewLevel(3l); // 升级部署 通知均为系统内通知
emailList = getEmailList(info, null);
break;
default: //任务1 任务4 均按原有业务发送邮件
emailList = getEmailList(info, null);
break;
}
logger.debug("邮件数量 "+(emailList==null?null:emailList.size()));
//-- 发送邮件
if(emailList !=null && emailList.size()>0){
SendMail cn = new SendMail();
for (Iterator emailIte = emailList.iterator(); emailIte.hasNext();) {
String addr = (String) emailIte.next();
if(StringUtils.isEmpty(addr))continue;
logger.debug("邮件 To "+(addr));
// 设置发件人地址、收件人地址和邮件标题
cn.setAddress(Constants.EMAIL_ADDRESS, addr, emaiTitle);
cn.send(sendInfo);
}
}
} catch (Exception e) {
logger.error("",e);
}
logger.info("任务下发 邮件通知 发送完成");
//-结束
}*/
private LinkedList<String> getEmailList(ContactSetInfo contactSetInfo,Long seqId) {
LinkedList<String> emailList = new LinkedList<String>();
ArrayList<String> fields = new ArrayList<String>();
fields.add("email");
if(contactSetInfo!=null && contactSetInfo.getViewLevel()!=null){
try {
if(contactSetInfo.getViewLevel().intValue()==1){ //个人查看 邮件发送给 创建者
String sql1 = "select distinct xyj.email from xt_yh_jbxx xyj where xyj.yhid = '"+contactSetInfo.getCreateUserId()+"' and xyj.is_receiveemail='0' ";
List<Map<String, String>> map1 = (List<Map<String, String>>)dao.dbSelect(sql1, fields);
if(map1 != null && map1.size()>0){
emailList.add(map1.get(0).get("email"));
}
}else { //非个人
//-- 无限制 或 未指定联系人情况
if(contactSetInfo.getViewLevel().intValue()==4 || (contactSetInfo.getContactUserIds()==null || contactSetInfo.getContactUserIds().length()==0)){
/**
* 查询seqId所在的系统
* 系统关联的用户维护组的有效维护人员接收邮件信息
* */
StringBuffer selectSql = new StringBuffer();
selectSql.append("select distinct xyj.email ");
selectSql.append("from xt_yh_jbxx xyj ");
selectSql.append("left join xt_yh_js_index xyji on xyji.yhid = xyj.yhid ");
selectSql.append("left join xt_js_jbxx xjj on xjj.jsbh = xyji.jsbh ");
selectSql.append("left join gorup_system_table gst on gst.user_group_id = xjj.jsbh ");
selectSql.append("left join system_table st on st.system_id = gst.system_id ");
selectSql.append("left join node_table nt on nt.system_id = gst.system_id ");
selectSql.append("left join nodegroup_table ngt on ngt.group_id = nt.node_group_id ");
selectSql.append("where xyj.is_receiveemail='0' ");
selectSql.append("and nt.node_state = 0 "); // 节点有效状态 0有效
selectSql.append("and ngt.is_valid = 1 "); // 节点组有效状态 1有效
selectSql.append("and st.system_state = 0 "); // 系统有效状态 0有效
selectSql.append("and xjj.zxbz = 0 "); // 用户组有效状态 0有效
selectSql.append("and xjj.type = 1 "); // 组类别状态 1是用户组 0是角色
selectSql.append("and xyj.zxbz = 0 "); // 用户有效状态 0 有效
if(seqId != null && seqId.longValue() != 0){
selectSql.append("and nt.seq_id = "+seqId);
}
//-- 无限制 情况
if(contactSetInfo.getViewLevel().intValue()==4){
}else
//-- 系统内 情况
if(contactSetInfo.getViewLevel().intValue()==3){
selectSql.append("and nt.system_id = '"+contactSetInfo.getSystemId()+"' ");
}else
//-- 组内 情况
if(contactSetInfo.getViewLevel().intValue()==2){
selectSql.append("and xjj.jsbh = '"+contactSetInfo.getCreateUserGroupId()+"' ");
}
List<Map<String, String>> mapList = (List<Map<String, String>>) dao.dbSelect(selectSql.toString(), fields);
if(mapList != null && mapList.size()>0){
for (Iterator<Map<String,String>> mapIte = mapList.iterator(); mapIte.hasNext();) {
Map<String,String> map = mapIte.next();
emailList.add(map.get("email"));
}
}
}
//-- 组或系统内指定联系人情况
else{
String sql0 = "select distinct xyj.email from xt_yh_jbxx xyj where xyj.yhid in ("+contactSetInfo.getContactUserIds()+") ";
List<Map<String, String>> map0List = (List<Map<String, String>>)dao.dbSelect(sql0, fields);
if(map0List != null && map0List.size()>0){
for (Iterator<Map<String,String>> map0Ite = map0List.iterator(); map0Ite.hasNext();) {
Map<String,String> map0 = map0Ite.next();
emailList.add(map0.get("email"));
}
}
}
}
} catch (Exception e) {
logger.error(" Fail to query the list of email addresses to be sent to failure",e);
}finally{
dao.clearConn();
}
}
return emailList;
}
private ContactSetInfo getContactSetInfoByDetecId(Long dId){
ContactSetInfo contactSetInfo = null;
StringBuffer selectSql = new StringBuffer();
selectSql.append("select ");
selectSql.append("dsi.view_level, ");
selectSql.append("dsi.create_user_id, ");
selectSql.append("dsi.create_usergroup_id, ");
selectSql.append("dsi.system_id, ");
selectSql.append("dsi.contact_user_ids ");
selectSql.append("from detection_set_info dsi where dsi.id= '"+dId+"' ");
ArrayList<String> fields = new ArrayList<String>();
fields.add("view_level");
fields.add("create_user_id");
fields.add("create_usergroup_id");
fields.add("system_id");
fields.add("contact_user_ids");
try {
ArrayList<Map<String, String>> mapList = dao.dbSelect(selectSql.toString(), fields);
if(mapList!=null && mapList.size()>0){
Map<String, String> map0 = mapList.get(0);
contactSetInfo = new ContactSetInfo();
contactSetInfo.setViewLevel(map0.get("view_level")==null?null:Long.parseLong(map0.get("view_level")));
contactSetInfo.setCreateUserId(map0.get("create_user_id")==null?null:Long.parseLong(map0.get("create_user_id")));
contactSetInfo.setCreateUserGroupId(map0.get("create_usergroup_id")==null?null:Long.parseLong(map0.get("create_usergroup_id")));
contactSetInfo.setSystemId(map0.get("system_id")==null?null:Long.parseLong(map0.get("system_id")));
contactSetInfo.setContactUserIds(map0.get("contact_user_ids"));
}
} catch (Exception e) {
logger.error("",e);
}finally{
dao.clearConn();
}
return contactSetInfo;
}
private ContactSetInfo getContactSetInfoByMissionId(Long mId){
ContactSetInfo contactSetInfo = null;
StringBuffer selectSql = new StringBuffer();
selectSql.append("select ");
selectSql.append("mst.mission_id, ");
selectSql.append("mst.mission_name, ");
// selectSql.append("ngt.group_name node_group_name, ");
// selectSql.append("mpt.node_groups_id, ");
// selectSql.append("mpt.node_ips_id, ");
selectSql.append("mst.mission_type, ");
selectSql.append("mst.mission_state, ");
selectSql.append("mst.is_loop , ");
selectSql.append("to_char(mst.start_time,'"+Constants.DB_DATE_FORMAT+"' ) start_time, ");
selectSql.append("to_char(mst.end_time,'"+Constants.DB_DATE_FORMAT+"' ) end_time, ");
selectSql.append("mst.view_level, ");
selectSql.append("mst.user_id, ");
selectSql.append("mst.group_id, ");
selectSql.append("mst.system_id, ");
selectSql.append("mst.contact_user_ids ");
selectSql.append("from mission_state_table mst ");
// selectSql.append("left join mission_parameter_table"+missionType+" mpt on mpt.mission_id = mst.mission_id ");
// selectSql.append("left join nodegroup_table ngt on ngt.group_id = mpt.node_groups_id ");
selectSql.append("where mst.mission_id= '"+mId+"' ");
ArrayList<String> fields = new ArrayList<String>();
fields.add("mission_id");
fields.add("mission_name");
// fields.add("node_groups_id");
// fields.add("node_ips_id");
fields.add("mission_type");
fields.add("mission_state");
fields.add("is_loop");
fields.add("start_time");
fields.add("end_time");
fields.add("view_level");
fields.add("user_id");
fields.add("group_id");
fields.add("system_id");
fields.add("contact_user_ids");
try {
ArrayList<Map<String, String>> mapList = dao.dbSelect(selectSql.toString(), fields);
if(mapList!=null && mapList.size()>0){
Map<String, String> map = mapList.get(0);
contactSetInfo = new ContactSetInfo();
contactSetInfo.setMissionId(map.get("mission_id")==null?null:Long.parseLong(map.get("mission_id")));
contactSetInfo.setMissionName(map.get("mission_name"));
contactSetInfo.setMissionType(map.get("mission_type")==null?null:Long.parseLong(map.get("mission_type")));
contactSetInfo.setMissionState(map.get("mission_state")==null?null:Long.parseLong(map.get("mission_state")));
contactSetInfo.setIsLoop(map.get("is_loop")==null?null:Long.parseLong(map.get("is_loop")));
contactSetInfo.setStartTime(map.get("start_time")==null?null:format.parse(map.get("start_time")));
contactSetInfo.setEndTime(map.get("end_time")==null?null:format.parse(map.get("end_time")));
contactSetInfo.setViewLevel(map.get("view_level")==null?null:Long.parseLong(map.get("view_level")));
contactSetInfo.setCreateUserId(map.get("user_id")==null?null:Long.parseLong(map.get("user_id")));
contactSetInfo.setCreateUserGroupId(map.get("group_id")==null?null:Long.parseLong(map.get("group_id")));
contactSetInfo.setSystemId(map.get("system_id")==null?null:Long.parseLong(map.get("system_id")));
contactSetInfo.setContactUserIds(map.get("contact_user_ids"));
ArrayList<String> paramsFields = new ArrayList<String>();
paramsFields.add("node_groups_id");
paramsFields.add("node_ips_id");
String paramsSql = "select mpt.node_groups_id,mpt.node_ips_id from mission_parameter_table"+contactSetInfo.getMissionType().intValue()+" mpt where mpt.mission_id=?";
ArrayList<Map<String, String>> paramsMapList = dao.dbSelect(paramsSql.toString(), paramsFields,mId);
if(paramsMapList!= null && paramsMapList.size()>0){
Map<String, String> map0 = paramsMapList.get(0);
contactSetInfo.setNodeGroupsId(map0.get("node_groups_id"));
contactSetInfo.setNodeIpsId(map0.get("node_ips_id"));
}
}
//节点组和节点名称填写
if(contactSetInfo!= null){
if(contactSetInfo.getNodeGroupsId()!= null){
//查询节点组名称
ArrayList<String> ngnFields = new ArrayList<String>();
ngnFields.add("group_name");
String ngNameSql = "select ngt.group_name from nodegroup_table ngt where ngt.group_id in ("+contactSetInfo.getNodeGroupsId()+")";
ArrayList<Map<String, String>> ngnMapList = dao.dbSelect(ngNameSql.toString(), ngnFields);
if(ngnMapList != null && ngnMapList.size()>0){
StringBuffer ngnsb = new StringBuffer();
for(Map<String, String> map : ngnMapList){
ngnsb.append(","+map.get(ngnFields.get(0)));
}
if(ngnsb.length()>0){
ngnsb.deleteCharAt(0);
}
contactSetInfo.setNodeGroupName(ngnsb.toString());
}
//查询节点名称
ArrayList<String> nnFields = new ArrayList<String>();
nnFields.add("node_name");
String nnNameSql = null;
ArrayList<Map<String, String>> nnMapList = null;
if(contactSetInfo.getNodeIpsId()!= null){
nnNameSql = "select nt.node_name from node_table nt where nt.node_id in ("+contactSetInfo.getNodeIpsId()+")";
nnMapList = dao.dbSelect(nnNameSql.toString(), nnFields);
}else{
nnNameSql = "select nt.node_name from node_table nt where nt.node_group_id in ("+contactSetInfo.getNodeGroupsId()+") ";
if(contactSetInfo.getIsLoop()==null || contactSetInfo.getIsLoop()==0){ //非周期任务
nnNameSql += "and nt.seq_id in (select mrt.seq_id from mission_result_table"+contactSetInfo.getMissionType()+" mrt where mrt.mission_id=?)";
}else{ //周期任务
nnNameSql += "and nt.seq_id in (select distinct mrt.seq_id from mission_result_table4 mrt where mrt.mission_id in (select lmst.cur_mission_id from loopmission_state_table lmst where lmst.mission_id=?))";
}
nnMapList = dao.dbSelect(nnNameSql.toString(), nnFields,mId);
}
if(nnMapList != null && nnMapList.size()>0){
StringBuffer nnsb = new StringBuffer();
for(Map<String, String> map : nnMapList){
nnsb.append(","+map.get(nnFields.get(0)));
}
if(nnsb.length()>0){
nnsb.deleteCharAt(0);
}
contactSetInfo.setNodeIpsName(nnsb.toString());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
dao.clearConn();
}
return contactSetInfo;
}
public static void main(String [] args){
CommonDao dao = null;
try {
dao = new CommonDao();
EmailService emailService = new EmailService(dao);
EmailInfo emailInfo = new EmailInfo(11,"测试名称","10.0.6.113",new SimpleDateFormat(Constants.COMMON_DATE_FORMAT).format(new Date()),"这是一条关于监测设置的测试信息",EmailTypeConstants.FLAG_SEND_LATER,EmailTypeConstants.URGENT_LATER);
//113监测邮件测试
Constants.flag_email = 1;
// emailService.sendEmailForDetectionBySeqId(2570l, 85l, emailInfo);
// EmailInfo emailInfo2 = new EmailInfo(31,"任务XXX","10.0.6.113",new SimpleDateFormat(Constants.COMMON_DATE_FORMAT).format(new Date()),"这是一条关于任务结果的测试信息",0);
// emailService.sendEmailForMissionBySeqId(2570l, 6, 85l, emailInfo2);
emailService.sendEmailForMission(2570l, "任务XXX", "这是一条关于任务状态的测试信息");
pl("测试邮件入库完毕");
} catch (Exception e) {
e.printStackTrace();
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
private static void pl(Object object) {
System.out.println(object==null?null:object.toString());
}
}

View File

@@ -0,0 +1,68 @@
package com.nms.server.service;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.thread.monitor.MonitorManagerThread;
public class ThreadService{
private static Logger logger = Logger.getLogger(ThreadService.class);
public ThreadService(){
}
/**
* 更新主动监测线程操作
* 关闭旧线程,创建新线程
* @time Sep 12, 2012-4:44:03 PM
* @param nm
* @param info
*/
public void updateThread(SetInfo info) {
//- 计算启动后第一次检测时间 默认即时启动
long initialDelay = Constants.HANDSHANK_DELAY_TIME;
if(info.getPlanCheckTime()!=null){
initialDelay = info.getPlanCheckTime().longValue() - (new Date().getTime());
initialDelay = initialDelay > 0l ? initialDelay : 0l;
}
//- 设置名称
String processIden = StringUtils.isEmpty(info.getProcessIden())?"":info.getProcessIden();
//-线程名称
String runnableName = info.getCheckTypeName()+"_"+processIden;
//- 撤销旧监测线程
Common.cancelRunnableAtOnce(runnableName); //撤销 旧任务
//- 监测设置状态无效 结束操作--对于变更,如果修改为无效,则不再启动新监测
if(StringUtils.isEmpty(info.getCheckState()) || "0".equals(info.getCheckState())){//0无效1有效
return;
}
//- 监测方式 非主动 结束操作--为了严谨
if(StringUtils.isEmpty(info.getCheckWay()) || "1".equals(info.getCheckWay())){//0主动1被动
return;
}
logger.info("主动监测设置启动 "+runnableName);
//- 创建线程
Runnable runnable = new MonitorManagerThread(runnableName,info);
//- 添加到 定时线程池
ScheduledFuture<?> future = Common.scheduled.scheduleAtFixedRate(runnable, initialDelay/1000, info.getCheckGap()*60, TimeUnit.SECONDS);
//- 注册线程
Common.registRunnable(runnableName, future);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,375 @@
package com.nms.server.snmp.trap;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import org.apache.log4j.Logger;
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 com.nms.server.bean.SetInfo;
import com.nms.server.bean.TrapMessageInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.CommonService;
import com.nms.server.util.SNMP4JUtils;
/**
* 本类用于监听代理进程的Trap信息
*
* @author YJS
*
*/
public class TrapServer /**extends Service*/
implements CommandResponder{// implements CommandResponder, extends Service
private static Logger logger = Logger.getLogger(TrapServer.class);
private static TrapServer ts = null;
public static TrapServer getInstance() throws IOException{
if(ts == null){
ts = new TrapServer();
logger.info("SNMP Trap Server 启动成功");
}else{
logger.info("SNMP TrapServer 已启动");
}
return ts;
}
private TrapServer() throws IOException{
ThreadPool threadPool = ThreadPool.create("Trap", Constants.SNMP_TRAP_THREAD_POOL_SIZE);
MultiThreadedMessageDispatcher dispatcher = new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());
Address listenAddress = GenericAddress.parse(System.getProperty("snmp4j.listenAddress", "udp:" + Common.getLocalIp() + "/" + Constants.SNMP_TRAP_PORT)); // 本地IP与监听端口
TransportMapping transport = null;
// 对TCP与UDP协议进行处理
if (listenAddress instanceof UdpAddress) {
transport = new DefaultUdpTransportMapping((UdpAddress) listenAddress);
} else {
transport = new DefaultTcpTransportMapping((TcpAddress) listenAddress);
}
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);
// OID authProtocol = getAuthProtocol(Constants.SNMP_V3_AUTH_PROTOCOL); //认证协议
// OID privProtocol = getPrivProtocol(Constants.SNMP_V3_PRIV_PROTOCOL); //加密协议
// OctetString securityName = new OctetString(Constants.SNMP_V3_SECURITY_NAME); //认证用户
// OctetString authPassphrase = new OctetString(Constants.SNMP_V3_AUTH_PASSPHRASE); //认证密码明文
// OctetString privPassphrase = new OctetString(Constants.SNMP_V3_PRIV_PASSPHRASE); //加密密码明文
// snmp.getUSM().addUser(securityName, new UsmUser(securityName, authProtocol, authPassphrase,privProtocol, privPassphrase));
}
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)
{
CommonDao dao = null;
try
{
dao = new CommonDao();
logger.debug((new StringBuilder("接收到snmp event")).append(commandresponderevent.getPDU()).toString());
UdpAddress udpaddress = (UdpAddress)commandresponderevent.getPeerAddress();
String s = udpaddress.getInetAddress().getHostAddress();
PDU pdu = commandresponderevent.getPDU();
logger.debug((new StringBuilder("接收到TRap:")).append(pdu).toString());
TrapMessageInfo trapmessageinfo = new TrapMessageInfo();
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");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.coldStart_n81i");
break;
case 1: // '\001'
// trapmessageinfo.setTrapName("设备热启动");
// trapmessageinfo.setTrapName("Device Hot Start");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.hotStart_n81i");
break;
case 2: // '\002'
// trapmessageinfo.setTrapName("接口关闭");
// trapmessageinfo.setTrapName("The Interface Is Closed");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.interClose_n81i");
break;
case 3: // '\003'
// trapmessageinfo.setTrapName("接口启用");
// trapmessageinfo.setTrapName("Interface Enabled");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.interUsed_n81i");
break;
case 4: // '\004'
// trapmessageinfo.setTrapName("SNMP认证失败");
// trapmessageinfo.setTrapName("SNMP Authentication Failed");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.snmp_n81i");
break;
case 5: // '\005'
// trapmessageinfo.setTrapName("EGP邻居丢失");
// trapmessageinfo.setTrapName("EGP Neighbor Lost");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.egp_n81i");
break;
}
} else
{
trapmessageinfo.setTrapVersion(2);
Variable variable = trapmessageinfo.getOIDValue(SnmpConstants.snmpTrapAddress.toString());
logger.debug("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");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.coldStart_n81i");
else
if (variable1.equals(SnmpConstants.warmStart))
// trapmessageinfo.setTrapName("设备热启动");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.hotStart_n81i");
else
if (variable1.equals(SnmpConstants.linkDown))
// trapmessageinfo.setTrapName("接口关闭");
// trapmessageinfo.setTrapName("The Interface Is Closed");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.interClose_n81i");
else
if (variable1.equals(SnmpConstants.linkUp))
// trapmessageinfo.setTrapName("接口启用");
// trapmessageinfo.setTrapName("Interface Enabled");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.interUsed_n81i");
else
if (variable1.equals(SnmpConstants.authenticationFailure))
// trapmessageinfo.setTrapName("SNMP认证失败");
// trapmessageinfo.setTrapName("SNMP Authentication Failed");
trapmessageinfo.setTrapName("i18n_server.UpgradeService.snmp_n81i");
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.debug("agent IP"+s+" trap信息"+trapInfo.toString());
new CommonService(dao).newClientCheck(s,trapmessageinfo.getTrapVersion());
SetInfo info = Common.getSnmpTrapSetInfo();
String [] dsb = Common.alarmExceptionInfo(info.getId(), s, info.getCheckTypeName(), info.getProcessIden(), trapmessageinfo.getReceiverTime().getTime(), 1,Constants.DETECTION_INFO_ALARM_WRONG, trapInfo.toString());
Common.addAlarmData(dsb);
}
catch (Exception exception)
{
logger.debug((new StringBuilder("解析UDP TRAP发生错误:")).append(exception.getMessage()).toString());
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
public String getTrapName(Variable variable1){
String trapName = "";
Map allTrapTypeDefine = new HashMap();
trapName = allTrapTypeDefine.get(variable1.toString()).toString();
return trapName;
}
void setOIDList(TrapMessageInfo 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(TrapMessageInfo 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();
}
}
/* public static void main(String[] args) {
TrapServer multithreadedtrapreceiver = new TrapServer();
multithreadedtrapreceiver.run();
}*/
/** */
/**
* 解决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;
}
}
/**
* 将十进六制转换成为中文
*//*
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());
}*/
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;
logger.debug("长度==> " + intLength);
for (int j = 0; j < intLength; j++) {
strOut += str[j];
}
strCom += vb.getVariable();
if (str.length != 1) {
logger.debug("==第行=vb.getVariable()=" + SNMP4JUtils.toStringHex(strOut));//显示中文
}
}
return strCom;
}
public static void main(String [] args) {
try {
TrapServer.getInstance();
TrapServer.getInstance();
TrapServer.getInstance();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,40 @@
package com.nms.server.thread;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.dao.CommonDao;
/**
* 定时检查数据库连接是否可用
* @date May 7, 2013 2:31:50 PM
* @author ZhangGang
*
*/
public class DBTestThread implements Runnable{
private Logger logger = Logger.getLogger(DBTestThread.class);
@Override
public void run() {
// Thread.currentThread().setName("数据库连接监听线程");
Thread.currentThread().setName("Database Connection Listening Thread");
CommonDao dao = null;
try {
dao = new CommonDao();
Common.setDbConnectedFlag(true);
} catch (Exception e) {
/* 告警 */
Common.setDbConnectedFlag(false);
logger.error("Try to get a database connection failure", e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
/* public static void main (String [] args) {
new Thread(new DBTestThread()).start();
}*/
}

View File

@@ -0,0 +1,148 @@
package com.nms.server.thread;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.CommonService;
import com.nms.server.thread.dataCollect.DataCollectManagerThread;
import com.nms.server.util.BoneCPPool;
public class DetecDataCollectThread implements Runnable{
private Logger logger = Logger.getLogger(DetecDataCollectThread.class);
public DetecDataCollectThread(){
}
@Override
public void run() {
// Thread.currentThread().setName("DC 数据收集管理线程 监测线程");
Thread.currentThread().setName("DC Data Collection And Management Thread Monitoring Thread");
Object rlt = null;
boolean isDone = false;
boolean isCancel = false;
Future<?> future = null;
try {
Thread.sleep(5000);
future = Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER);
if(future!=null) {
isDone = future.isDone();
isCancel = future.isCancelled();
logger.info("DC已注册数据收集管理线程isDone="+isDone+",isCancel="+isCancel);
rlt = future.get();
logger.info("DC数据收集管理线程执行完毕结果"+rlt);
}else {
logger.info("DC 未注册 数据收集管理 线程,开始注册。。。");
Common.addErrorInfoForMySelf(Constants.ERROR_CODE_DATA_COLLECT,Constants.ERROR_INFO_SATAE_ERROR,Constants.ERROR_DESC_DATA_COLLECT_NO_RUN);
//- DC端主动收集数据监测数据、任务结果、回传文件管理线程
if(Constants.FLAG_DATA_COLLECT==1) {
Thread.sleep(60000);
//注销线程
Common.cancelRunnableAtOnce(Constants.DATA_COLLECT_MANAGER);
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new DataCollectManagerThread(),0, Constants.DATA_COLLECT_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.DATA_COLLECT_MANAGER, fcFuture);
logger.info("DC 数据收集管理 线程 注册成功");
Common.addErrorInfoForMySelf(Constants.ERROR_CODE_DATA_COLLECT,Constants.ERROR_INFO_SATAE_RIGHT_AUTO,Constants.ERROR_DESC_DATA_COLLECT_NO_RUN);
//单独起一个线程,监督数据收集线程是否运行
Common.cancelRunnableAtOnce(Constants.DETECTI_DATA_COLLECT_THREAD_NAME);//取消其实是不起作用的?
Future<?> detecDataCollectFuture = Common.service.submit(new DetecDataCollectThread());
Common.registRunnable(Constants.DETECTI_DATA_COLLECT_THREAD_NAME, detecDataCollectFuture);
}
}
} catch (Exception e) {
logger.error("DC data collection management thread monitoring thread exceptions, result"+rlt,e);
try {
Common.addErrorInfoForMySelf(Constants.ERROR_CODE_DATA_COLLECT,Constants.ERROR_INFO_SATAE_ERROR,Constants.ERROR_DESC_DATA_COLLECT);
//- DC端主动收集数据监测数据、任务结果、回传文件管理线程
if(future!=null) {
isDone = future.isDone();
isCancel = future.isCancelled();
logger.info("DC 数据收集管理线程 运行状态isDone="+isDone+",isCancel="+isCancel);
}
if(Constants.FLAG_DATA_COLLECT==1 && future!=null && future.isDone()) {//已执行完毕
Thread.sleep(60000);
//注销线程
logger.info("DC 数据收集管理 线程 已执行完毕(异常导致),再次注册。。。");
Common.cancelRunnableAtOnce(Constants.DATA_COLLECT_MANAGER);
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new DataCollectManagerThread(),0, Constants.DATA_COLLECT_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.DATA_COLLECT_MANAGER, fcFuture);
logger.info("DC 数据收集管理 线程 注册成功");
Common.addErrorInfoForMySelf(Constants.ERROR_CODE_DATA_COLLECT,Constants.ERROR_INFO_SATAE_RIGHT_AUTO,Constants.ERROR_DESC_DATA_COLLECT);
//单独起一个线程,监督数据收集线程是否运行
Common.cancelRunnableAtOnce(Constants.DETECTI_DATA_COLLECT_THREAD_NAME);
Future<?> detecDataCollectFuture = Common.service.submit(new DetecDataCollectThread());
Common.registRunnable(Constants.DETECTI_DATA_COLLECT_THREAD_NAME, detecDataCollectFuture);
}
}catch(Exception ee) {
logger.error("DC data collection management thread is abnormal when registered again",ee);
}
}finally{
// try{
// //单独起一个线程,监督数据收集线程是否运行
// Common.cancelRunnableAtOnce(Constants.DETECTI_DATA_COLLECT_THREAD_NAME);
// Future<?> detecDataCollectFuture = Common.service.submit(new DetecDataCollectThread());
// Common.registRunnable(Constants.DETECTI_DATA_COLLECT_THREAD_NAME, detecDataCollectFuture);
// }catch (Exception e) {
// logger.error("DC 数据收集管理线程 监测线程 注销 异常", e);
// }
logger.debug("DC 数据收集管理线程 监测线程 结束");
}
}
public static void main (String []args){
try {
System.out.println(Long.MAX_VALUE/1000/60/60/24);
BoneCPPool.initPool();
CommonDao dao = new CommonDao();
CommonService service = new CommonService(dao);
// 初始化自身信息(失败情况下会由Web唤醒)
if(!service.initServerParams()){
return;
}
// //- DC端主动收集数据监测数据、任务结果、回传文件管理线程
if(Constants.FLAG_DATA_COLLECT==1) {
//注销线程
Common.cancelRunnableAtOnce(Constants.DATA_COLLECT_MANAGER);
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new DataCollectManagerThread(),0, Constants.DATA_COLLECT_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.DATA_COLLECT_MANAGER, fcFuture);
}
//
// new Thread(new DetecDataCollectThread()).start();
//
// //- 错误信息DC程序运行异常捕获报警解析管理线程
// if(Constants.FLAG_ERROR_INFO==1){
// //注销线程
// Common.cancelRunnableAtOnce(Constants.ERROR_INFO_RESOVE_MANAGER);
// ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new ErrorInfoResoveManagerThread(), 0, 30, TimeUnit.SECONDS);
// //注册 管理线程
// Common.registRunnable(Constants.ERROR_INFO_RESOVE_MANAGER, fcFuture);
// }
}catch(Exception e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,115 @@
package com.nms.server.thread;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
public class DetecSelfThread implements Runnable{
private Logger logger = Logger.getLogger(DetecSelfThread.class);
public DetecSelfThread(){
}
@Override
public void run() {
// Thread.currentThread().setName("DC 性能监测线程");
Thread.currentThread().setName("DC Performance Monitoring Thread");
CommonDao dao = null;
try {
// dao = new CommonDao();
if(Constants.sslServer==null) {
logger.info("DC监听端口状况60702sslServer=null");
}else {
logger.info("DC监听端口状况60702isBind="+Constants.sslServer.isBound());
}
Future<?> future = Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER);
Future<?> futureDetect = Common.getFutureMap().get(Constants.DETECTI_DATA_COLLECT_THREAD_NAME);
if(future!=null) {
boolean isDone = future.isDone();
boolean isCancel = future.isCancelled();
logger.info("DC已注册数据收集管理线程isDone="+isDone+",isCancel="+isCancel);
}else {
logger.info("DC未注册数据收集管理线程");
}
if(futureDetect!=null) {
logger.info("DC 数据收集管理线程 监测线程 运行中isDone="+futureDetect.isDone()+",isCancel="+futureDetect.isCancelled());
}else {
logger.info("DC 数据收集管理线程 监测线程 未启动");
}
long freeMemory = Runtime.getRuntime().freeMemory()/1024/1024;
long totalMemory = Runtime.getRuntime().totalMemory()/1024/1024;
long maxMemory = Runtime.getRuntime().maxMemory()/1024/1024;
long usedMemory = totalMemory - freeMemory;
int activeCount = Thread.activeCount();//活跃线程数
logger.debug("内存使用情况total-> " + totalMemory +" MB, used -> "+ usedMemory +" MB, max -> " + maxMemory+" MB, free -> " + freeMemory+" MB \r\n 活跃线程数: "+ activeCount);
Common.detecSelf();
if(logger.isDebugEnabled() && "druid".equalsIgnoreCase(Constants.DB_POOL_TYPE)){
}
// int [] links = getDBLinkSize(dao);
/* 查询当前DC数据库连接数 */
// logger.debug("当前数据库连接数:"+links[0]+" 活动连接数:"+links[1]);
// System.gc();
} catch (Exception e) {
logger.error("Monitoring their own thread abnormality",e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
logger.debug("结束");
}
}
public static void main (String []args){
new Thread(new DetecSelfThread()).start();
/*Map<String, String> map = System.getenv();
pl("用户名称"+map.get("USERNAME"));
pl("计算机名称"+map.get("COMPUTERNAME"));
pl(""+map.get("USEROOMAIN"));*/
}
/**
* 查询当前DC的数据库连接数
* @time Jan 13, 2013-4:25:03 PM
* @param dao
* @return
* @throws Exception
*/
public int[] getDBLinkSize(CommonDao dao) throws Exception{
ArrayList<String> fields = new ArrayList<String>();
fields.add("dbLinks");
fields.add("activeLinks");
// Map<String, String> map = System.getenv();
String dbLinkSizeSql = "select count(1) dbLinks,count(decode(status,'ACTIVE',1,0,0)) activeLinks from v$session t where lower(username) =lower(?) and lower(t.MACHINE) = lower(?)";
String dbUserName = Constants.DB_USER_NAME;
// String computerName = map.get("COMPUTERNAME");
String computerName = InetAddress.getLocalHost().getHostName();
logger.debug("计算机名称:"+computerName);
// logger.debug("计算机名称:"+name);
ArrayList<Map<String, String>> data = dao.dbSelect(dbLinkSizeSql, fields,dbUserName,computerName);
if(data!= null && data.size()>0){
String val = data.get(0).get("dbLinks");
String val2 = data.get(0).get("activeLinks");
return new int[]{val == null ? -1 : Integer.parseInt(val),val2 == null ? -1 : Integer.parseInt(val2)};
}else{
return new int[]{-1,-1};
}
}
public static void pl(Object obj) {
System.out.println(obj==null?null:obj.toString());
}
}

View File

@@ -0,0 +1,25 @@
package com.nms.server.thread;
import com.nms.server.util.socket.SSLSocketCallable;
/**
* 通过通讯获取本机IP(暂未使用)
* @date Mar 14, 2013 5:23:58 PM
* @author ZhangGang
*
*/
public class GetLocalIpFromWeb extends SSLSocketCallable{
public GetLocalIpFromWeb(String ip, Integer port) throws Exception {
super(ip, port);
}
protected Object toDo() throws Exception {
Thread.currentThread().setName("Get The IP Thread");
this.sendMessage("char:getLocalIp");
String lIp = this.receiveMessage();
this.sendMessage(SUCCESS);
return lIp;
}
}

View File

@@ -0,0 +1,491 @@
package com.nms.server.thread;
import java.io.File;
import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.nms.server.bean.ServerTable;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.CommonService;
import com.nms.server.service.ThreadService;
import com.nms.server.service.UpgradeService;
import com.nms.server.snmp.trap.TrapServer;
import com.nms.server.thread.alarmData.AlarmDataResoveManagerThread;
import com.nms.server.thread.change.ChangeManagerThread;
import com.nms.server.thread.dataCollect.DataCollectManagerThread;
import com.nms.server.thread.dataCollect.NoDetectDataCollectManagerThread;
import com.nms.server.thread.dataCollect.NonRltTaskResultCollectManagerThread;
import com.nms.server.thread.deleteFiles.DeleteFilesManagerThread;
import com.nms.server.thread.detecData.DetecDataResoveManagerThread;
import com.nms.server.thread.detectDataHandler.DataInsertManagerThread;
import com.nms.server.thread.detectDataHandler.DataResolveThread;
import com.nms.server.thread.detectDataHandler.DetectInfoInsertThread;
import com.nms.server.thread.email.RefreshEmailFlagThread;
import com.nms.server.thread.errorinfo.ErrorInfoResoveManagerThread;
import com.nms.server.thread.file.UnZipManagerThread;
import com.nms.server.thread.file.upload.FileUploadManagerThread;
import com.nms.server.thread.mission.InitRunningMissionThread;
import com.nms.server.thread.mission.LoadNewMissionThread;
import com.nms.server.thread.mission.MissionResultManagerThread;
import com.nms.server.thread.overrunData.DataFileReaderManagerThread;
/**
* DC初始化启动线程
* 初始化流程
* 1、初始化数据库连接加载DC自身信息
* 2、初始化本地目录信息公共缓存信息
* 3、启动各解析线程
* 4、启动任务和主动监测现成
* 5、启动SNMP TRAP端口
* 6、变更启动标示
* @date Mar 27, 2013 2:47:31 PM
* @author ZhangGang
*
*/
public class InitServerThread implements Runnable{
private Logger logger = Logger.getLogger(InitServerThread.class);
@Override
public void run() {
// Thread.currentThread().setName("初始化线程");
Thread.currentThread().setName("Initialization thread");
CommonDao dao = null;
try {
// 连接数据库
dao = new CommonDao();
CommonService service = new CommonService(dao);
// 初始化自身信息(失败情况下会由Web唤醒)
if(!service.initServerParams()){
return;
}
// 根据初始化成功标示初始化DC实际操作信息
if(!Constants.flag_init){
//- 目录及缓存信息监测类型和表、数据字段、告警、ip主机映射等
initCommonInfo(dao);
try
{
//- 启动SNMP监测服务端口
Common.getSnmp().addCommandResponder(TrapServer.getInstance());
} catch (Exception e)
{
logger.error("Start the SNMP monitoring service port exception", e);
}
//- 监测数据解析
if(Constants.FLAG_DETEC_RESOVE==1){
if(Constants.DETECT_INSERT_THREAD_MODE == 1){//单线程
//注销线程
Common.cancelRunnableAtOnce(Constants.DETEC_DATA_RESOVE_MANAGER);
int delay = 0;//管理线程延时多久启动
Date dbNow = service.getDbTime();
long dbLong = dbNow.getTime();
int period = Constants.DETEC_DATA_RESOLVE_PERIOD*1000;//周期ms
ServerTable st = Common.getServerTable();
int count = st.getConut();
int index = st.getIndex();
int cst = (index-1) *period/count;//当前dc 的时间窗口 开始时间
int pass = (int) (dbLong%period);
if(cst >= pass){
delay = cst - pass;
}else{
delay = period -pass + cst;
}
logger.debug(""+count+" 个 有效DC,当前DC index : "+ index+", 数据库当前时间 " + dbNow.toLocaleString() +" ,DETEC_DATA_RESOLVE_PERIOD " + Constants.DETEC_DATA_RESOLVE_PERIOD +" s , 监测数据解析入库管理线程延迟:" + delay +" ms 启动");
/**
* 解析线程scheduleWithFixedDelay不能修改为scheduleAtFixedRate是因为:解析管理线程很快就会执行完毕,不会像收集线程,需要等待节点收集完毕,
* 而且解析线程会尝试5次如果都在解析则会将数据存入硬盘如果改了那么解析的周期就更短了因为管理线程几乎用不了1秒就执行完了
* 这样解析线程就只有5秒左右的执行时间会有大问题的解析线程需要延长时间收集线程需要缩短时间
*/
/**
* 2018年6月14日14:34:49 修改 根据dc 个数固定 管理线层启动 时间窗口分散一下dc 入库时间,固定周期时间启动
*/
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleAtFixedRate(new DetecDataResoveManagerThread(), delay, period, TimeUnit.MILLISECONDS);
//注册 管理线程
Common.registRunnable(Constants.DETEC_DATA_RESOVE_MANAGER, fcFuture);
}else if(Constants.DETECT_INSERT_THREAD_MODE == 2){//多线程info表一个线程其它每个监测详细信息表一个线程共用一个线程池
int im = Constants.DETECT_INFO_THREAD_MODE;
int it = Constants.DETECT_INFO_THREAD_TIME;
int id = Constants.DETECT_INFO_THREAD_DELAY;
int dm = Constants.DETECT_DETAIL_THREAD_MODE;
int dt = Constants.DETECT_DETAIL_THREAD_TIME;
int dd = Constants.DETECT_DETAIL_THREAD_DELAY;
Common.cancelRunnableAtOnce(Constants.DETECT_INFO_THREAD_KEY);
Common.cancelRunnableAtOnce(Constants.DETECT_DETAIL_THREAD_KEY);
Common.cancelRunnableAtOnce(Constants.DETECT_RESOVE_THREAD_KEY);
//info入库线程运行模式1每隔 n秒 运行一次2间隔 n 秒运行一次
if(im == 1){
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleAtFixedRate(new DetectInfoInsertThread(), id, it, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.DETECT_INFO_THREAD_KEY, fcFuture);
}else{
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new DetectInfoInsertThread(), id, it, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.DETECT_INFO_THREAD_KEY, fcFuture);
}
if(dm == 1){
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleAtFixedRate(new DataInsertManagerThread(), dd, dt, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.DETECT_DETAIL_THREAD_KEY, fcFuture);
}else{
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new DataInsertManagerThread(), dd, dt, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.DETECT_DETAIL_THREAD_KEY, fcFuture);
}
Future<?> future = Common.service.submit(new DataResolveThread());
Common.registRunnable(Constants.DETECT_RESOVE_THREAD_KEY, future);
}else{
logger.error("detect.insert.thread.mode = " + Constants.DETECT_INSERT_THREAD_MODE +" is error");
}
}
//- 错误信息DC程序运行异常捕获报警解析管理线程
if(Constants.FLAG_ERROR_INFO==1){
//注销线程
Common.cancelRunnableAtOnce(Constants.ERROR_INFO_RESOVE_MANAGER);
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new ErrorInfoResoveManagerThread(), 0, Constants.ERROR_INFO_RESOVE_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.ERROR_INFO_RESOVE_MANAGER, fcFuture);
}
//- 告警数据解析管理线程
if(Constants.FLAG_ALARM_RESOVE==1){
//注销线程
Common.cancelRunnableAtOnce(Constants.ALARM_DATA_RESOVE_MANAGER);
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new AlarmDataResoveManagerThread(), 0, Constants.DETEC_DATA_RESOLVE_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.ALARM_DATA_RESOVE_MANAGER, fcFuture);
}
//-硬盘数据(监测数据、告警数据、任务结果:由于数据量过大,暂时无法入库,而存放在硬盘上的数据)解析入库管理线程
if(Constants.FLAG_FILES_READER_RESOVE==1){
//注销线程
Common.cancelRunnableAtOnce(Constants.OVERRUN_DATA_RESOVE_MANAGER);
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new DataFileReaderManagerThread(), 0, Constants.DISK_DATA_RESOLVE_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.OVERRUN_DATA_RESOVE_MANAGER, fcFuture);
}
//- DC端主动收集数据监测数据、任务结果、回传文件管理线程
if(Constants.FLAG_DATA_COLLECT==1) {
//注销线程
Common.cancelRunnableAtOnce(Constants.DATA_COLLECT_MANAGER);
/**
* 收集线程scheduleWithFixedDelay修改为scheduleAtFixedRate是因为:
* scheduleWithFixedDelay:等待线程执行完毕,还会再等待指定的周期时间
* scheduleAtFixedRate为了节省时间且线程执行完毕
* 1.线程执行时间大于周期间隔,则直接执行下一周期
* 2.线程执行时间小于周期间隔,则两次线程开始执行时间点的间隔就是设定的周期
*
* (解析线程需要延长时间,收集线程需要缩短时间)
*/
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleAtFixedRate(new DataCollectManagerThread(),0, Constants.DATA_COLLECT_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.DATA_COLLECT_MANAGER, fcFuture);
Common.cancelRunnableAtOnce(Constants.NO_DETECT_DATA_NODE_DATA_COLLECT_MANAGER);
ScheduledFuture<?> enFuture = Common.scheduled.scheduleAtFixedRate(new NoDetectDataCollectManagerThread(),0, Constants.ERROR_NODE_DATA_COLLECT_PERIOD, TimeUnit.SECONDS);
Common.registRunnable(Constants.NO_DETECT_DATA_NODE_DATA_COLLECT_MANAGER, enFuture);
}
//- 定时的刷新是否启用邮件发送功能:从数据库读取配置
if(Constants.FLAG_EMAIL_START==1) {
//注销线程
Common.cancelRunnableAtOnce(Constants.EMAIL_START_THREAD);
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new RefreshEmailFlagThread(),0, Constants.REFRESH_EMAIL_FLAG_PEROID, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.EMAIL_START_THREAD, fcFuture);
}
//定时删除log线程
if(Constants.FLAG_DELETE_TMP_FILES==1) {
//注销线程
Common.cancelRunnableAtOnce(Constants.DELETE_TMP_FILES_MANAGER);
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new DeleteFilesManagerThread(),0, Constants.DELETE_TMP_FILES_PERIOD, TimeUnit.HOURS);
//注册 管理线程
Common.registRunnable(Constants.DELETE_TMP_FILES_MANAGER, fcFuture);
}
//DC端定时的去收集执行完成但无任务结果返回的任务的结果信息
if(Constants.FLAG_NONRLTTASK_RESULT_COLLECT==1) {
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new NonRltTaskResultCollectManagerThread(),0, Constants.NONRLTTASK_RESULT_COLLECT_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.NONRLTTASK_RESULT_COLLECT_MANAGER, fcFuture);
}
//- 文件上传管理线程
if(Constants.FLAG_FILE_UPLOAD==1){
//注销线程
Common.cancelRunnableAtOnce(Constants.MISSION_FILE_UPLOAD);
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new FileUploadManagerThread(), 0, Constants.MISSION_FILE_UPLOAD_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.MISSION_FILE_UPLOAD, fcFuture);
}
//- 变更操作管理线程
if(Constants.FLAG_CHANGE_OPERATIONS==1){
//注销线程
Common.cancelRunnableAtOnce(Constants.CHANGE_OPERATIONS_MANAGER);
ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new ChangeManagerThread(), 0, Constants.CHANGE_OPERATIONS_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.CHANGE_OPERATIONS_MANAGER, fcFuture);
}
//- 任务初始化分配和任务线程启动
if(Constants.FLAG_MISSION==1){
//-- 启动已执行任务加载线程
Common.scheduled.schedule(new InitRunningMissionThread(null),Constants.MISSION_FIRST_START, TimeUnit.SECONDS);
//-- 启动已创建任务加载线程
Common.scheduled.scheduleWithFixedDelay(new LoadNewMissionThread(null), Constants.MISSION_CHECK_NEW_START, Constants.MISSION_CHECK_NEW_PERIOD, TimeUnit.SECONDS);
//启动任务结果管理线程
if(Constants.FLAG_MISSION_RESULT==1){
//注销线程
Common.cancelRunnableAtOnce(Constants.MISSION_RESULT_RESOVE_MANAGER);
//logger.debug(Constants.MISSION_RESULTS_SAVE_START+" -- "+Constants.MISSION_RESULTS_SAVE_PERIOD);
ScheduledFuture<?> mrFuture = Common.scheduled.scheduleWithFixedDelay(new MissionResultManagerThread(),Constants.MISSION_RESULTS_SAVE_START, Constants.MISSION_RESULTS_SAVE_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
Common.registRunnable(Constants.MISSION_RESULT_RESOVE_MANAGER, mrFuture);
}
}
//服务端NMSC监测任务添加--一种监测--此处的握手监测仅为非服务器的握手监测
if(Constants.FLAG_NMSC==1){
initDrivingDetectionThread(dao,Constants.DETEC_NMSC_STR);
}
//服务端SNMP监测任务添加-systemsnmp4jobjectsnmp:特设的电源、风扇、网元系统信息等?---snmp类型的监测多个
if(Constants.FLAG_SNMP==1){
initDrivingDetectionThread(dao,Constants.DETEC_SNMP_STR);
}
//服务端PING监测任务添加--一种监测
if(Constants.FLAG_PING==1){
initDrivingDetectionThread(dao,Constants.DETEC_PING_STR);
}
//服务端SWITCH监测任务添加-交换机、特种设备:端口流量监测等--一种监测
if(Constants.FLAG_SWITCH==1){
initDrivingDetectionThread(dao,Constants.DETEC_SWITCH_STR);
}
//服务端SYSTEMDATE监测任务添加--一种监测
if(Constants.FLAG_SYSTEMDATE==1){
initDrivingDetectionThread(dao,Constants.DETEC_SYSTEMDATE_STR);
}
//压缩文件解压操作
if(Constants.FLAG_ZIP==1){
//启动时,执行一次压缩文件解压操作
Common.service.submit(new UnZipManagerThread());
}
if(Constants.DETECSELFTHREAD_FLAG){
//缓存数据量监测线程
Common.cancelRunnableAtOnce(Constants.DETECTI_SELF_THREAD_NAME);
ScheduledFuture<?> dsFuture = Common.dcPrivScheduled.scheduleAtFixedRate(new DetecSelfThread(),Constants.DETECSELFTHREAD_INITIALDELAY,Constants.DETECSELFTHREAD_PERIOD,TimeUnit.SECONDS);
Common.registRunnable(Constants.DETECTI_SELF_THREAD_NAME, dsFuture);
}
//单独起一个线程,监督数据收集线程是否运行:放在收集数据线程之后即可
if(Constants.FLAG_DATA_COLLECT==1) {
Common.cancelRunnableAtOnce(Constants.DETECTI_DATA_COLLECT_THREAD_NAME);
Future<?> detecDataCollectFuture = Common.service.submit(new DetecDataCollectThread());
Common.registRunnable(Constants.DETECTI_DATA_COLLECT_THREAD_NAME, detecDataCollectFuture);
}
//DC缓存信息定时刷新功能
Common.cancelRunnableAtOnce(Constants.RESET_SERVER_THREAD_NAME);
ScheduledFuture<?> rsFuture = Common.dcPrivScheduled.scheduleAtFixedRate(new ResetServerThread(-1),8,8,TimeUnit.HOURS);
Common.registRunnable(Constants.RESET_SERVER_THREAD_NAME, rsFuture);
//数据库连接监听线程
Common.cancelRunnableAtOnce(Constants.DB_CONNECTION_THREAD_NAME);
ScheduledFuture<?> dbcFuture = Common.dcPrivScheduled.scheduleAtFixedRate(new DBTestThread(),3,3,TimeUnit.MINUTES);
Common.registRunnable(Constants.DB_CONNECTION_THREAD_NAME, dbcFuture);
logger.info("------- DataController Start Success------------");
Constants.flag_init = true;
}
} catch (SQLException e) {
logger.error("Failed to get database connection, execute again in 5 minutes"+ e.getMessage());
Common.scheduled.schedule(this, 5, TimeUnit.MINUTES);
Common.addErrorInfoForMySelf(Constants.ERROR_CODE_DB_CONNECT,Constants.ERROR_INFO_SATAE_ERROR,"");
} catch (Exception e) {
logger.error("DataController initialization failure",e);
Common.scheduled.schedule(this, 5, TimeUnit.MINUTES);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
logger.debug("启动程序dao已关闭");
}
}
/**
* 初始化主动监测线程
* @time Sep 20, 2011-7:07:36 PM
* @param dao
* @return
*/
public boolean initDrivingDetectionThread(CommonDao dao,String checkType){
boolean isSuccess = true;
CommonService commonService = new CommonService(dao);
ThreadService service = new ThreadService();
//--获取checkType 监测配置并启动监测任务
List<SetInfo> setList = commonService.getDrivingSetInfo(checkType);//获得checkType类型的所有监测设置
logger.info("检查主动监测类别:"+checkType+" 关联监测设置:"+(setList==null?0:setList.size())+"");
//-- checkType 监测任务启动 和 客户端启动监测任务启动
if(setList!=null && setList.size()>0){
for (Iterator setIte = setList.iterator(); setIte.hasNext();) {
SetInfo si = (SetInfo) setIte.next();
if(Constants.DETEC_SNMP_STR.equalsIgnoreCase(checkType)){
if(Constants.DETEC_SWITCH_STR.equalsIgnoreCase(si.getCheckTypeName())){
continue;
}
}
service.updateThread(si);
}
}
return isSuccess;
}
/**
* 初始化公共信息方法
* <p>Common类中的公共数据集合在此方法中进行数据初始化</p>
* Init server
* @time Aug 24, 2011-9:55:44 AM
* @return
*/
public boolean initCommonInfo(CommonDao dao) {
initCheck();
boolean flag = true;
CommonService service = new CommonService(dao);
UpgradeService upService = new UpgradeService(dao);
try{
//-- 从数据库中查询邮件创建信息
Constants.flag_email = service.getFlagEmail();
//-- checkTypeName TableModel Map Init监测类别名称 与 检测类别信息)
service.updateCheckTableInfo(Common.getInsertTable(), null);
service.updateSetInfoName(Common.getSetInfoNameMape(), null);
//-- Table Columns Map Init数据库表结构信息
service.updateTableColumnsMap(Common.getTableMap(), null);
//alarm Ping Init告警数据结构信息
service.updateAlarmInfo(Common.getAlarmInfoMap(),null);
//-- LoginIp nodeip Initseq_id-物理节点信息)
service.updateSimpleNodeByUUID(null);
//--ClientIP-seq_id信息
service.updateSeqIdByNodeIp(Common.getIpSeqIdMap(),null);
service.updateUserPwdByNodeIp(Common.getIpUserPwdMap(),null);
// init loop Mission info
upService.updateLoopMissionInfo(Common.getLoopMissionInfoMap(), null);
upService.updateLoopMissionRoundInfo(Common.getLoopMissionRoundInfoList(), null);
// init detection info
List<SetInfo> siList = service.getDrivingSetInfo(Constants.ALARM_SNMP_TRAP_STR);
if(siList !=null && siList.size()>0){
Common.setSnmpTrapSetInfo(siList.get(0));
}
}catch (Exception e) {
logger.debug("NMSServer参数初始化失败", e);
System.exit(0);
}
return flag;
}
/**
* 程序启动时校验操作
* <p>必要文件目录的存在校验操作、及相关必要存在校验操作</p>
* @time Aug 24, 2011-10:14:35 AM
* @return
*/
public void initCheck() {
File file = new File(Constants.MISSION_FILE_UPLOAD_DIR);
if (!file.exists()) {
file.mkdirs();
}
file = new File(Constants.MISSION_FILE_DOWNLOAD_DIR);
if (!file.exists()) {
file.mkdirs();
}
file = new File(Constants.ZIP_FILE_DETECT_DATA_DIR);
if (!file.exists()) {
file.mkdirs();
}
file = new File(Constants.ZIP_FILE_TASK_RESULT_DIR);
if (!file.exists()) {
file.mkdirs();
}
file = new File(Constants.ZIP_FILE_TASK_RETURN_DIR);
if (!file.exists()) {
file.mkdirs();
}
file = new File(Constants.ZIP_RESOVE_DETECT_DATA_DIR);
if (!file.exists()) {
file.mkdirs();
}
file = new File(Constants.ZIP_RESOVE_TASK_RESULT_DIR);
if (!file.exists()) {
file.mkdirs();
}
file = new File(Constants.ZIP_RESOVE_TASK_RESULT_DIR);
if (!file.exists()) {
file.mkdirs();
}
file = new File(Constants.ZIP_RESOVE_TASK_RETURN_DIR);
if (!file.exists()) {
file.mkdirs();
}
file = new File(Constants.ERROR_DETEC_FILE_DIR);
if (!file.exists()) {
file.mkdirs();
}
// return flag;
}
}

View File

@@ -0,0 +1,106 @@
package com.nms.server.thread;
import java.io.File;
import java.io.IOException;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.ChangeService;
import com.nms.server.util.CommandExecUtil;
public class ResetServerThread implements Runnable{
private Logger logger = Logger.getLogger(ResetServerThread.class);
private Integer model = -1; //缺省为-1
public ResetServerThread(Integer model){
this.model = model==null?this.model:model;
}
@Override
public void run() {
// Thread.currentThread().setName("程序整理线程");
Thread.currentThread().setName("Program Manage Thread");
CommonDao dao = null;
try {
dao = new CommonDao();
ChangeService service = new ChangeService(dao);
switch (model) {
case 1: //更新自身参数信息
//NMSServer参数获取失败后结束程序初始化
//- 系统信息初始化监测类型和表、数据字段、告警、ip主机映射等
if(!Constants.flag_init){//新安装DCDC没在web的管理范围内初始化失败
logger.info("启动失败,再次启动");
Common.service.submit(new InitServerThread());
}else{
logger.info("启动成功,仅更新参数");
service.initServerParams();//web端修改DC信息(管理范围修改)时执行
new InitServerThread().initCommonInfo(dao);
logger.info("参数更新完成");
}
/*业务重新梳理
* List<NodeModel> list = service.getAllEffectiveNodeInfo();
if(list!= null && list.size()>0){
Iterator<NodeModel> ite = list.iterator();
while(ite.hasNext()){
NodeModel model = ite.next();
Common.runChangeRunnable(new SSLClient(model.getNodeIp(), Constants.SSL_CLIENT_PORT,"char:reInit","init"));
}
}*/
break;
// case 2://重启DC
// String os = System.getProperty("os.name");
// if (os.startsWith("Windows")) {//重启服务
//// String path = new File(Constants.SYSTEM_PATH).getParent()+File.separator+Constants.COMMON_TEMP_DIR+File.separator+Constants.COMMON_RUNTIME_PID_FILE;
//// String processName = "DataController.exe";
//// String path = System.getProperty("user.dir")+"/"+processName;
//// String serverName = "DataController";
//
// logger.info("web端超周期无监测数据开始开始重启DC。。。");
//
// //不行------自己把自己杀了,就没法把自己重启了
//// if(!CommandExecUtil.killProcess(processName)){/* 删除已存在的进程 */
//// logger.info("程序停止失败");
//// }else if(CommandExecUtil.processRunningCheck(processName)){/* 校验程序是否已停止 */
//// logger.info("程序停止失败,请手动关闭进程["+processName+"]");
//// }else if(!CommandExecUtil.startNetService(serverName)){/* 启动进程 */
//// logger.info("程序启动失败");
//// }else if(CommandExecUtil.processRunningCheck(processName)){/* 校验程序是否已启动 */
//// logger.info("程序启动成功");
//// }else{
//// logger.info("程序启动失败");
//// }
//
// } else if (os.startsWith("Linux")) {//执行restart.sh脚本
// String path = new File(System.getProperty("user.dir")).getParentFile().getAbsolutePath()+"/shell/restart.sh";
// logger.info("linux下重启DC的restart.sh脚本路径为"+path+"开始重启DC。。。");
// CommandExecUtil.execLinuxCmd(path);
// } else {
// throw new IOException("unknown operating system: " + os);
// }
// break;
case -1: //预留操作
//执行系统清理 (监测结果集合、任务结果集合、重启线程池,重启通讯)
System.gc();
service.deleteEventRecordOldInfo();//超过4天的变更就删除NC没启动就一直执行不成功(或者给服务器节点发送只有交换机才有的)
logger.info("执行gc操作");
break;
default:
logger.warn("Indeterminate mode parameter, no operation");
return;
}
} catch (Exception e) {
logger.error("NmsServer initialization failure",e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
logger.debug("启动程序dao已关闭");
}
}
}

View File

@@ -0,0 +1,68 @@
package com.nms.server.thread;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import org.apache.log4j.Logger;
import com.nms.server.common.Constants;
public class WritePidThread implements Runnable{
@Override
public void run() {
// Thread.currentThread().setName("写PID线程");
Thread.currentThread().setName("Write the PID thread");
Logger logger = Logger.getLogger(WritePidThread.class);
/* 获取程序运行PID */
String path = new File(Constants.SYSTEM_PATH).getParent()+File.separator+Constants.COMMON_TEMP_DIR+File.separator+Constants.COMMON_RUNTIME_PID_FILE;
String name = ManagementFactory.getRuntimeMXBean().getName();
logger.info("当前程序PID:>"+(name.split("@")[0]));
/* 判断系统类型是否写文件 */
String os = System.getProperty("os.name");
if(os!=null && !os.toLowerCase().startsWith("windows")){
logger.info("非Windows系统 结束执行");
return ;
}
/* 获取输出文件并检查文件路径是否存在 */
File file = new File(path);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
/* 将PID写入文件 */
FileOutputStream oStream = null;
try {
oStream = new FileOutputStream(path,false);
oStream.write(name.split("@")[0].getBytes());
oStream.flush();
logger.info("写PID完成:>"+file.getAbsolutePath());
} catch (IOException e) {
logger.error("Write PID failure", e);
}finally{
try {
if(oStream!=null)
oStream.close();
oStream = null;
} catch (IOException e) {
logger.error("", e);
}
logger.info("线程关闭");
}
}
public static void main(String [] args) {
new Thread(new WritePidThread()).start();
}
public static void pl (Object obj) {
System.out.println(obj==null?null:obj.toString());
}
}

View File

@@ -0,0 +1,167 @@
package com.nms.server.thread.alarmData;
import java.io.File;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.concurrent.Future;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.StringUtil;
public class AlarmDataResoveManagerThread implements Runnable{
private Logger logger = Logger.getLogger(AlarmDataResoveManagerThread.class);
private int testNum = 0;//尝试运行线程Constants.ALARM_DATA_RESOVE的次数
public void run() {
// Thread.currentThread().setName("告警数据解析管理线程");
Thread.currentThread().setName("Alarm Data Parsing Management Threads");
//将线程运行程序尽可能的catch捕获异常
try {
boolean runFlag = Common.isDbConnected();//测试数据库连接
//- 检查线程运行状态
Future<?> future = Common.getFutureMap().get(Constants.ALARM_DATA_RESOVE);
if(future != null && !future.isCancelled() && !future.isDone() && runFlag){ //运行中
runFlag = false;
logger.info("告警解析 运行中 不再启动");
}
/*
* 连续超过Constants.CHECK_WARNING_DATA_OVERRUN次数时将数据存入硬盘中
* 否则 正常执行数据解析线程
* */
if(!runFlag){ //判断并结束线程
testNum = (testNum%Constants.CHECK_WARNING_DATA_OVERRUN);
testNum++;
if(testNum==Constants.CHECK_WARNING_DATA_OVERRUN) {
if(Constants.FLAG_WARN_DATA_SAVE_DISK_RESOVE==1) {
/*
* 连续多个周期仍未解析完成
* 说明list里存有大量的数据则先将当前未解析的数据列表存入硬盘
* 然后停掉解析线程,将正在解析的数据列表中的剩余数据存入硬盘
* */
logger.warn("Create a database connection failure data to write to the hard disk");
saveWarningDataToDisk();
}
}
return;
}else{ //重置计数器 程序继续执行
testNum = 1;
}
//- 非升级操作判断
if(Common.SERVER_UN_UPGRADE_FLAG){
//-- 启动新解析线程
//-- 变更存储区
Common.changeAlarmDataFlag(); //变更数据存放集合
LinkedList<String []> adList = Common.getAlarmDataList(); // 获取非存放状态的数据集合
if(adList != null && adList.size()>0){
logger.info("告警解析 空闲中 启动");
// future = Common.service.submit(new AlarmDataResoveThread("告警解析",adList));
future = Common.service.submit(new AlarmDataResoveThread("Alarm Parsing",adList));
//注册 告警线程
Common.getFutureMap().put(Constants.ALARM_DATA_RESOVE, future);
}else{
logger.info("告警数据为0解析结束");
}
}
} catch (Exception e) {
logger.error("Running exception",e);
}
}
/**
* 数据库是否可连接判断
* @time Mar 7, 2013-2:22:42 PM
* @return
*/
public boolean dbTest() {
CommonDao dao = null;
try {
// if(!false)throw new Exception("强制异常");
dao = new CommonDao();
logger.debug("尝试获取数据库连接成功");
return true;
} catch (Exception e) {
logger.error("Try to get a database connection failure", e);
/* 告警 */
return false;
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
//2013-2-19 hyx :当告警数据量过大时,将数据先存放到硬盘,再定时入库(由单独的定时线程实现)
public void saveWarningDataToDisk() {
LinkedList<String []> notResolvingWarningDataList = Common.getNotResovlingWarnDataList(); // 获取未在解析的告警数据集合
try {
//终止正在解析告警数据的线程并将正在解析的list里未解析的数据存入硬盘
Future<?> future = Common.getFutureMap().get(Constants.ALARM_DATA_RESOVE);
if(future != null && !future.isCancelled() && !future.isDone()){ //运行中
future.cancel(true);
}
LinkedList<String []> warningDataList = Common.getAlarmDataList(); // 获取非存放状态的数据集合(正在解析的list)
saveStrToFile(warningDataList);
//将未在解析的list存放到硬盘上
saveStrToFile(notResolvingWarningDataList);
}catch(IndexOutOfBoundsException e) {
logger.error("When the alarm data is too much, the data is stored in the hard disk",e);
}catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}
}
private void saveStrToFile(LinkedList<String[]> dataList) {
String filePath = "";
int dataSize = dataList.size();//如果不按此时的size来操作则list里的数据可能会一直在增加就会一直循环下去
logger.info("告警数据过多,共"+dataSize+"条告警数据,等待存入硬盘");
try {
for(int j=0;j<dataSize;j++) {
if(dataList.size()>0) {
String[] data= dataList.get(0);
filePath = Constants.OVERRUN_WARNING_FILE_DIR+"/"+Common.getDateDirName()+"/"+Calendar.getInstance().getTimeInMillis()+"_"+j+".csv";
File file = new File(filePath);
String dataStr = StringUtil.linkToString(data, Constants.COMMON_DATA_SPLIT, "");
FileUtils.writeStringToFile(file, dataStr);
// String[] msg = FileUtils.readFileToString(file).split(Constants.COMMON_DATA_SPLIT);
// System.out.println(FileUtils.readFileToString(file));
dataList.remove(0);
logger.info("告警数据过多,已保存至"+filePath);
}
}
}catch(Exception e) {
logger.error("When the alarm data is too much, the data is stored in the hard disk",e);
}
}
public static void main(String[] args) {
String [] alarms = {"1","2","3","4"};
String [] alarms2 = {"21","2","3","4"};
String [] alarms3 = {"31","2","3","4"};
Common.addAlarmData(alarms);
Common.addAlarmData(alarms2);
Common.changeAlarmDataFlag();
Common.addAlarmData(alarms3);
new AlarmDataResoveManagerThread().saveWarningDataToDisk();
}
}

View File

@@ -0,0 +1,211 @@
package com.nms.server.thread.alarmData;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.CommonService;
/**
* 告警数据解析线程
*
* @author ZGGG3
*
*/
public class AlarmDataResoveThread implements Callable<Object> {
private Logger logger = Logger.getLogger(AlarmDataResoveThread.class);
volatile boolean stop = false;//线程是否被取消标志
private String name; // 自定义Thread Name
private LinkedList<String []> adList;
public AlarmDataResoveThread(String name,LinkedList<String []> adList) {
this.name = name;
this.adList = adList;
}
/*
* 线程操作
*
* 依次解析urlList中仍存在的Files
*
* 实现了依次解析Files由于后期实现多线程解析操作
*/
public Object call() {
// 为当前线程命名 ,用与开发阶段友好输出。
Thread.currentThread().setName(name);
//-- 空数据集合 结束操作
if(adList == null || adList.size() == 0 ){
return null;
}
logger.debug(" 解析数量 "+adList.size());
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
CommonDao dao = null;
try {
dao = new CommonDao();
CommonService service = new CommonService(dao);
int totalCount = adList.size();
long sTime = System.currentTimeMillis();
logger.debug("缓存告警数据 " + (totalCount)+ "条,解析开始");
//-- 遍历解析
Iterator<String []> adIte = adList.iterator();
while (adIte.hasNext()&& !stop) {//线程未被中断
try {
String [] alarms = adIte.next();
if(alarms!=null && alarms.length>0){
String dateTime = null;
if(alarms.length>6){
dateTime = format.format(Long.parseLong(alarms[5]));
}
logger.debug("告警数据 监测时间》"+dateTime+" 内容》"+Arrays.toString(alarms));
service.resoveAlarms(alarms);
}
//解析入库一条数据从list中remove一条数据
adIte.remove();
}catch (InterruptedException e) {
logger.error("Alarm data parsing threads are interrupted",e);
stop = true;
}
//判断当前线程是否被中断
if (Thread.currentThread().isInterrupted()) {
// 线程中断状态,不会改变中断状态的值
logger.info("告警数据解析线程 被中断");
stop = true;
}
}
//将告警数据入库后,需要检查新入库的数据是否为无效(处理告警数据的有效性标志)
updateDetectWarningDataValid(dao);
long eTime = System.currentTimeMillis();
long curTime = eTime-sTime;
int m=(int)curTime/1000/60;
int s=(int)((long)(curTime/1000)%60);
int ms=(int)curTime%1000;
logger.debug((totalCount)+ "条,解析完成 耗时:"+(m)+""+(s)+""+(ms)+"毫秒");
}catch (Exception e) {
logger.error("Running exception",e);
}finally{
// adList.clear();
if(dao!=null){
dao.close();
dao=null;
}
logger.debug("数据清理 解析完成");
}
return null;
}
//检查入库的告警数据中是否有无效的数据,有则置为无效
public void updateDetectWarningDataValid(CommonDao dao) throws Exception{
CommonService service = new CommonService(dao);
Map<String,String> detectSetSeqIdMap = service.getDetectSetInfo();//查询有效监测设置对应的seqid
Map<String,String[]> detectWarnDataSeqIdMap = service.getDetectSeq(Constants.DETECTION_WARNING_TABLE_NAME);//统计 告警数据 表: 监测设置<->已有有效数据的seqid
Iterator detectWarnDateSeqIte = detectWarnDataSeqIdMap.entrySet().iterator();
String invalidSeqIds = "";
List<String> sqls = new ArrayList<String>();
while(detectWarnDateSeqIte.hasNext()) {
invalidSeqIds = "";
Entry en = (Entry)detectWarnDateSeqIte.next();
String setId = (String)en.getKey();
String seqIdsValid = detectSetSeqIdMap.get(setId);//得到监测设置当前有效的seqids1,2,3
// System.out.println("有效key:value="+setId+":"+seqIdsValid);
if(seqIdsValid!=null) {//如果有效的监测设置内没有此监测设置,则不予处理
seqIdsValid = "," + seqIdsValid + ",";
String[] seqIds = (String[])en.getValue();
for(String seqIdTmp:seqIds) {
// System.out.println("告警数据seqId="+seqIdTmp);
if(seqIdTmp!=null && !"".equals(seqIdTmp)) {
if(!seqIdsValid.contains(","+seqIdTmp+",")) {//不在有效范围内,则更新为无效
invalidSeqIds = invalidSeqIds + seqIdTmp + ",";
}
}
}
if(invalidSeqIds.endsWith(",")) {
invalidSeqIds = invalidSeqIds.substring(0,invalidSeqIds.length()-1);
sqls.add("update "+Constants.DETECTION_WARNING_TABLE_NAME+" t set valid=0 where t.valid=1 and t.detection_set_info_id="+setId+" and t.seq_id in ("+invalidSeqIds+")");
}
}
}
dao.dbUpdateByBatch(sqls);
}
/* public static void main(String[] args) {
CommonDao dao = null;
try {
dao = new CommonDao();
new AlarmDataResoveThread("xx",null).updateDetectWarningDataValid(dao);
}catch(Exception e) {
e.printStackTrace();
}
}*/
public static void main(String[] args) {
CommonDao dao = null;
try {
dao = new CommonDao();
CommonService service = new CommonService(dao);
// boolean flag = initCheck();
//-- CheckType TableName Map Init监测类别数据库表名映射结构信息
service.updateCheckTableInfo(Common.getInsertTable(), null);
//-- Table Columns Map Init数据库表结构信息
service.updateTableColumnsMap(Common.getTableMap(), null);
//-- LoginIp nodeip Initseq_id-物理节点信息)
service.updateSimpleNodeByUUID(null);
//-- ClientIP-seq_id信息
service.updateSeqIdByNodeIp(Common.getIpSeqIdMap(),null);
//alarm Ping Init告警数据结构信息
service.updateAlarmInfo(Common.getAlarmInfoMap(),null);
// init loop Mission info
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
long l = Calendar.getInstance().getTimeInMillis();
LinkedList<String []> adList = new LinkedList<String[]>();
adList.add("141$@$143$@$cpu$@$detection288$@$1364280094312$@$1364280094312$@$1$@$0$@$总的使用率(%)12.5%大于告警值1% 不正常;".split(Constants.COMMON_DATA_SPLIT));
Future<?> future = Common.service.submit(new AlarmDataResoveThread("",adList));
try {
future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Common.service.shutdown();
System.out.println(Calendar.getInstance().getTimeInMillis()-l);
}
}

View File

@@ -0,0 +1,127 @@
package com.nms.server.thread.change;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.NodeModel;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.ChangeService;
import com.nms.server.service.CommonService;
import com.nms.server.thread.change.socket.ChangeSocketThread;
import com.nms.server.thread.socket.SocketCMD;
import com.nms.server.util.DateUtil;
/**
* 节点是否报主动告警:
* 更新其影响的所有的节点是否报主动告警(通讯不成功的,保存入库,后续再进行通信)
* @date 2014-5-26
* @author hyx
*/
public class ChangeForActiveAlarmInfo implements Runnable{
private final Logger logger = Logger.getLogger(ChangeForActiveAlarmInfo.class);
private String datas;
private Long recordId;
/**
* @param datastrueNC报主动告警falseNC不报主动告警
*/
public ChangeForActiveAlarmInfo(Long recordId,String datas){
this.datas = datas;
this.recordId = recordId;
}
public void run() {
// Thread.currentThread().setName("NC是否报主动告警 变更");
Thread.currentThread().setName("Whether NC Reports Active Alarm Changes");
CommonDao dao = null;
try {
dao = new CommonDao();
ChangeService service = new ChangeService(dao);
if(StringUtils.isBlank(datas)){
logger.warn("Whether NC reports active alarm change invalid data"+datas);
if(recordId!=null){
service.deleteEventRecordByIds(recordId.toString());//删除数据库中记录的通信信息
}
return ;
}
JSONObject jObject = JSONObject.fromObject(datas);
Boolean showAutoAlarm = (Boolean)jObject.get("showAutoAlarm");
String webHandleTime = (String)jObject.get("webHandleTime");
// Boolean isStartActiveAlarm = datas.equalsIgnoreCase("true") ? true : false;
//组织数据
logger.debug("下发NC是否报主动告警操作"+showAutoAlarm+" web端操作时间"+webHandleTime);
JSONObject jsonObj = new JSONObject();
jsonObj.put("showAutoAlarm", showAutoAlarm);
jsonObj.put("webHandleTime", webHandleTime);
this.changeActiveAlarmStartInfo(jsonObj, service);
if(recordId!=null){
service.deleteEventRecordByIds(recordId.toString());
}
} catch (Exception e) {
logger.error("",e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
public void changeActiveAlarmStartInfo(JSONObject jObject,CommonService service){
//变更范围的节点IP
List<NodeModel> ipList = service.getAllEffectiveNodeInfo();
logger.debug("NC是否报主动告警 节点变更数量"+ipList.size());
Iterator<NodeModel> ipIte = ipList.iterator();
while (ipIte.hasNext()) {
NodeModel ip = ipIte.next();
//仅向0服务器节点发送变更信息0服务器
if(ip!= null && ip.getNodeIp()!= null && ip.getNodeType().longValue()==0l && Common.hasIpInIpSegment(ip.getNodeIp())){
Common.runChangeRunnable(new ChangeSocketThread(null,ip.getNodeIp(),Constants.SSL_CLIENT_PORT,SocketCMD.WEB_NOTICE_ACTIVE_ALARM_START_ALERT,jObject));
}else{
// downLatch.countDown();
}
}
}
/**
* Agent端通知变更方法
* @time Sep 20, 2011-2:33:37 PM
* @param ip
* @param jObject
*/
// public void sendToClient(String ip,Object jObject) {
// try {
// Common.runChangeRunnable(new ChangeSocketThread(null,ip,Constants.SSL_CLIENT_PORT,"char:updateConfig",jObject));
// } catch (Exception e) {
// logger.debug("配置变更下发"+ip+"异常"+e.getMessage());
// }
// }
// public static void main(String [] args) {
//// String[] datas = new String[]{"202","401"};
// CommonDao dao = new CommonDao();
// CommonService service = new CommonService(dao);
// SetInfo old = service.getSetInfoById(226l);
// SetInfo news = service.getSetInfoById(1l);
// OperationsUpdateBySetInfo thread = new OperationsUpdateBySetInfo(old,news);
// thread.run();
//
// }
}

View File

@@ -0,0 +1,74 @@
package com.nms.server.thread.change;
import java.util.Arrays;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.ChangeService;
/**
* 监测类别信息变更更新操作类
* @date Dec 11, 2012 4:01:20 PM
* @author ZhangGang
*
*/
public class ChangeForCheckType implements Runnable{
private final Logger logger = Logger.getLogger(ChangeForCheckType.class);
private String [] data = null;
private Long recordId;
/**
* 构造方法
* @param recordId 库表记录ID 可为空
* @param data 变更的监测类别ID
*/
public ChangeForCheckType(Long recordId,String [] data){
this.recordId = recordId;
this.data = data;
}
public void run(){
// Thread.currentThread().setName("监测类别变更");
Thread.currentThread().setName("Monitoring Class Change");
CommonDao dao = null;
try {
dao = new CommonDao();
ChangeService service = new ChangeService(dao);
if(data == null || data.length==0){ //无效数据
logger.warn("It is not effective to monitor class change information"+(data==null?null:Arrays.toString(data)));
/*删除记录*/
if(recordId!=null){
service.deleteEventRecordByIds(recordId.toString());
}
return ;
}
String idstr = data[0];
long checkTypeId = Long.parseLong(idstr);
logger.info("更新监测类别ID "+checkTypeId);
//只更新缓存,对于表结构的改变,需要动代码
/* 查询 监测类别名称 */
String obj = service.getCheckTypeNameById(checkTypeId);
//重新初始化 checkType TableName Map
service.updateCheckTableInfo(Common.getInsertTable(), obj);
//重新初始化 Alarm Info Map
service.updateAlarmInfo(Common.getAlarmInfoMap(), checkTypeId);
//重新初始化 Table Columns Map
service.updateTableColumnsMap(Common.getTableMap(), obj);
/* 删除库表中的记录 */
if(recordId!=null){
service.deleteEventRecordByIds(recordId.toString());
}
} catch (Exception e) {
logger.error("",e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
}

View File

@@ -0,0 +1,207 @@
package com.nms.server.thread.change;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.AlarmInfo;
import com.nms.server.bean.NodeModel;
import com.nms.server.bean.NodegroupModel;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.ChangeService;
import com.nms.server.service.ThreadService;
import com.nms.server.thread.change.socket.ChangeSocketThread;
/**
* 执行由节点或节点组状态的变更而变更的操作类
* @date Dec 23, 2011 1:58:04 PM
* @author ZhangGang
*
*/
public class ChangeForNodeGroup implements Runnable{
private final Logger logger = Logger.getLogger(ChangeForCheckType.class);
private String [] data = null;
private Long recordId;
/**
* @param recordId 库表记录ID 可为空
* @param data [groupId,nodeId] [节点组Id:节点ID 节点Id为空时即为节点组信息 ]
*/
public ChangeForNodeGroup(Long recordId,String [] data){
this.recordId = recordId;
this.data = data;
}
@Override
public void run() {
// Thread.currentThread().setName("节点状态变更");
Thread.currentThread().setName("Node State Change");
CommonDao dao = null;
try {
dao = new CommonDao();
ChangeService service = new ChangeService(dao);
/* 有效性判断 */
if(data == null || StringUtils.isEmpty(data[0])){
logger.warn("Not effective node state change information"+(data==null?null:Arrays.toString(data)));
if(recordId!=null){
service.deleteEventRecordByIds(recordId.toString());
}
return ;
}
/* 整理变更数据 最终以节点为主 */
Long nodeGroupId = Long.parseLong(data[0]);
NodegroupModel nodeGroup = service.getNodeGroupInfoById(nodeGroupId);//nodeGroup state 1有效 0无效
if(nodeGroup == null ){logger.warn("No query to the end of the node group change operation groupId"+nodeGroupId);return;}
String nodeIdStr = (data.length<=1?null:data[1]);
List<NodeModel> nodeList = new ArrayList<NodeModel>();
if(StringUtils.isNotEmpty(nodeIdStr)){ //节点不为空
Long nodeId = Long.parseLong(nodeIdStr);
NodeModel node = service.getNodeInfoById(nodeId);//node state 0有效 1无效
if(node!= null && node.getNodeIp()!= null && Common.hasIpInIpSegment(node.getNodeIp())){
nodeList.add(node);
}
}else{ //节点为空节点组判断
nodeList = service.getNodeInfoByGroupId(nodeGroupId);
}
logger.debug(nodeGroup.getGroupId()+" "+nodeGroup.getGroupName()+" 影响的节点数为:"+(nodeList==null?0:nodeList.size()));
Iterator<NodeModel> ite = nodeList.iterator();
/* 遍历各节点 处理相关setinfo */
while (ite.hasNext()) {
try {
NodeModel node = (NodeModel) ite.next();
boolean isPhysical = false;
if (node == null) {
continue;
}
//节点类型判断
if(node.getNodeType() != null && node.getNodeType().longValue() != 0l ){
logger.info("IP为"+node.getNodeIp()+"的节点 其节点类型不是服务器,变更无需下发,仅需更新DC的缓存信息");
//更新缓存中节点的信息
service.updateSeqIdByNodeIp(Common.getIpSeqIdMap(), node.getNodeIp());
service.updateUserPwdByNodeIp(Common.getIpUserPwdMap(),node.getNodeIp());
service.updateSimpleNodeByUUID(node.getSeqId());
continue;
}
//-- 节点无效性继承自nodeGroup
logger.debug("逻辑节点 id"+node.getNodeId()+" 自身状态:"+(node.getNodeState()==0?"有效":"无效")+" 组状态:"+(nodeGroup.getIsValid()==1?"有效":"无效")+" 最终状态:"+((new Long(0).equals(nodeGroup.getIsValid())?1l:node.getNodeState()==null?null:node.getNodeState().longValue())==0l?"有效":"无效"));
node.setNodeState(new Long(0).equals(nodeGroup.getIsValid())?1l:node.getNodeState());
//-- 变更节点监测信息,分布走
//--第一步查询状态变更的节点ID和他的Seq_id (已完成)
//--第二步查询节点状态有效唯一的Id或者null (已完成)
//--第三步当第一步节点有效时比较第一步的节点id和第二步的节点Id是有相等 或者 当第一步节点无效时null已完成
//--第四步如果第三步为true则作为物理节点处理否则逻辑节点处理
List<SetInfo> setInfoList = null;
if(service.checkUpdateNodeIsPhysicalNode(node)){ //是物理节点
logger.debug(node.getNodeIp()+" 该节点可作为物理节点");
isPhysical = true;
setInfoList = service.selectSetInfoList(null, null, node.getSeqId(), null, null, null, null, null,false);
}else{ //逻辑节点
logger.debug(node.getNodeIp()+" 该节点仅为逻辑节点");
setInfoList = service.selectSetInfoList(null, null, null, null, nodeGroupId+"", nodeGroup.getIsValid(), node.getNodeId()+"", null,false);
}
//更新缓存中节点的信息
service.updateSeqIdByNodeIp(Common.getIpSeqIdMap(), node.getNodeIp());
service.updateUserPwdByNodeIp(Common.getIpUserPwdMap(),node.getNodeIp());
service.updateSimpleNodeByUUID(node.getSeqId());
/** 更新其影响的监测设置的操作
* */
logger.debug(node.getNodeIp()+" 影响变更的监测设置数量为:"+(setInfoList==null?0:setInfoList.size()));
if(setInfoList!=null && setInfoList.size()>0){
for (int i = 0 ; i < setInfoList.size() ; i++) {
try {
SetInfo setInfo = setInfoList.get(i);
//非物理节点,跳过全局
if(!isPhysical && setInfo.getViewLevel()==4l){logger.debug(node.getNodeIp()+" 逻辑节点跳过全局监测:"+setInfo.getCheckTypeName());continue;}
// 监测方式0主动 1被动
if("0".equals(setInfo.getCheckWay())){ //主动监测状态有NMSServer自己处理
logger.debug("变更主动监测 "+setInfo.getCheckTypeName()+"跳过");
//
String runnableName = setInfo.getCheckTypeName()+"_"+setInfo.getProcessIden();
if(!Common.isRunnableRegist(runnableName)){
ThreadService service2 = new ThreadService();
service2.updateThread(setInfo);
}
// //- 设置名称
// String processIden = StringUtils.isEmpty(setInfo.getProcessIden())?"":setInfo.getProcessIden();
//
// //-- 监测设置 线程名称 typeName_processIden
// String runnableName = setInfo.getCheckTypeName()+"_"+processIden;
//
// //根据线程类别 线程对象
// MonitorManagerThread managerThread = (MonitorManagerThread) Common.getMonitorRunnableFromMap(runnableName);
//
// if(managerThread!= null){
// if(0l == node.getNodeState()){ //0有效
// managerThread.addIp(node);
// }else { // 1无效
// managerThread.removeIp(node.getNodeIp());
// }
// }else{
// logger.warn("主动监测线程:"+runnableName+" 不存在");
// }
setInfoList.remove(setInfo);
i--;
}else{ //被动状态监测设置发送到NMSClient端
logger.debug("变更被动监测 "+setInfo.getCheckTypeName());
//监测设置的 无效性 继承自失败节点的状态
logger.debug("监测设置 id"+setInfo.getId()+" 自身状态:"+(setInfo.getCheckState().equals("1")?"有效":"无效")+" 节点状态:"+(node.getNodeState().longValue()==0?"有效":"无效")+" 最终状态:"+((new Long(1).equals(node.getNodeState())?"0":setInfo.getCheckState()).equals("1")?"有效":"无效"));
setInfo.setCheckState(new Long(1).equals(node.getNodeState())?"0":setInfo.getCheckState());
}
} catch (Exception e) {
logger.error("",e);
}
}
//向node 下发所有被动监测监测设置信息
if(setInfoList.size()>0){
List<AlarmInfo> alarmInfoList = service.selectAlarmInfoBySetIfoList(setInfoList);
//组织数据
JSONObject jsonObj = new JSONObject();
jsonObj.put("number", Calendar.getInstance().getTimeInMillis());
jsonObj.put("setInfo", setInfoList);
jsonObj.put("alarmInfo", alarmInfoList);
Common.runChangeRunnable(new ChangeSocketThread(null,node.getNodeIp(),Constants.SSL_CLIENT_PORT,"char:updateConfig",jsonObj));
}
}
} catch (Exception e) {
logger.error("",e);
}
}
/** 更新其影响的其他的操作
* initTask
* */
//删除变更记录
if(recordId!=null){
service.deleteEventRecordByIds(recordId.toString());
}
} catch (Exception e) {
logger.error("",e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
}

View File

@@ -0,0 +1,196 @@
package com.nms.server.thread.change;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.AlarmInfo;
import com.nms.server.bean.NodeModel;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.ChangeService;
import com.nms.server.service.CommonService;
import com.nms.server.service.ThreadService;
import com.nms.server.thread.change.socket.ChangeSocketThread;
/**
* 监测设置信息变更时
* 通过新旧设置信息的对别,判断并更新
* 其影响的所有的节点的监测设置
* (通讯不成功的监测设置通讯,保存入库,后续)
* @date Dec 27, 2011 2:57:35 PM
* @author ZhangGang
*/
public class ChangeForSetInfo implements Runnable{
private final Logger logger = Logger.getLogger(ChangeForSetInfo.class);
private String datas;
private Long recordId;
/**
* @param o SetInfo old监测设置信息
* @param n SetInfo new监测设置信息
*/
public ChangeForSetInfo(Long recordId,String datas){
this.recordId = recordId;
this.datas = datas;
}
public void run() {
// Thread.currentThread().setName("监测设置变更");
Thread.currentThread().setName("Monitoring Settings Change");
JSONObject jObject = JSONObject.fromObject(datas);
SetInfo o = (SetInfo) JSONObject.toBean(jObject.getJSONObject("old"), SetInfo.class);
SetInfo n = (SetInfo) JSONObject.toBean(jObject.getJSONObject("new"), SetInfo.class);
// logger.debug("old checktypename "+o.getCheckTypeName());
// logger.debug("new checktypename "+n.getCheckTypeName());
CommonDao dao = null;
try {
dao = new CommonDao();
ChangeService service = new ChangeService(dao);
if(n == null){
logger.warn("Monitoring settings to change invalid data"+jObject.toString());
if(recordId!=null){
service.deleteEventRecordByIds(recordId.toString());
}
return ;
}
/**old 与 new的节点组和节点的变化影响该设置的监测变更范围
* old 与 new的监测状态有效性的变化影响的是监测设置是否执行
* */
boolean flag = true;
//-- 监测范围变更校验
if(o==null){ //新增监测告警设置时0=null
flag = true;
}else{ //修改
String oldGIds = StringUtils.isBlank(o.getNodeGroupsId())?"0":o.getNodeGroupsId();
String newGIds = StringUtils.isBlank(n.getNodeGroupsId())?"0":n.getNodeGroupsId();
if(oldGIds.equals(newGIds)){ //节点组相等
String oldNIPs = StringUtils.isBlank(o.getNodeIpsId())?"": o.getNodeIpsId();
String newNIPs = StringUtils.isBlank(n.getNodeIpsId())?"": n.getNodeIpsId();
if(oldNIPs.equals(newNIPs)){ //节点IP相等
flag = true;
}else{
flag = false;
}
}else{
flag = false;
}
}
if(!flag){ //范围变更
logger.debug("停用旧监测设置操作");
o.setCheckState("0");//0关闭监测设置
//组织数据
JSONObject jsonObj = new JSONObject();
List<SetInfo> setInfoList = new ArrayList<SetInfo>();
setInfoList.add(o);
jsonObj.put("number", Calendar.getInstance().getTimeInMillis());
jsonObj.put("setInfo", setInfoList);
this.changeSetInfo(o,jsonObj, service);
}else{ //范围无变化
}
SetInfo news = service.getSetInfoById(n.getId());
//查询 变更的告警信息集合
List<AlarmInfo> alarmInfoList = service.getAlarmInfoListBySetInfoId(news.getId());
//----------------------------------------------------------------------
//NMSServer 解析更新
//checkType TableName Map Init
service.updateCheckTableInfo(Common.getInsertTable(), news.getCheckTypeName());
service.updateSetInfoName(Common.getSetInfoNameMape(), null);
//tableMap Init
service.updateTableColumnsMap(Common.getTableMap(), news.getCheckTypeName());
//alarm Ping Init
service.updateAlarmInfo(Common.getAlarmInfoMap(),news.getId());
//----------------------------------------------------------------------
//5秒后执行新监测设置下发
Thread.currentThread().sleep(5000);
//组织数据
logger.debug("下发新监测设置操作");
JSONObject jsonObj = new JSONObject();
List<SetInfo> setInfoList = new ArrayList<SetInfo>();
setInfoList.add(news);
jsonObj.put("number", Calendar.getInstance().getTimeInMillis());
jsonObj.put("setInfo", setInfoList);
jsonObj.put("alarmInfo", alarmInfoList);
this.changeSetInfo(news,jsonObj, service);
if(recordId!=null){
service.deleteEventRecordByIds(recordId.toString());
}
} catch (Exception e) {
logger.error("",e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
public void changeSetInfo(SetInfo info,JSONObject jObject,CommonService service){
logger.info("监测设置"+info.getId()+" 指定CheckTypeName"+info.getCheckTypeName());
logger.info("监测设置"+info.getId()+" 状态:"+(StringUtils.isEmpty(info.getCheckState())?"无效操作":"1".equals(info.getCheckState())?"启动操作":"停用操作"));
logger.info("监测设置"+info.getId()+" 节点组ID"+info.getNodeGroupsId());
logger.info("监测设置"+info.getId()+" 指定Ip"+info.getNodeIpsId());
//判断是主动监测还是被动监测
if("0".equals(info.getCheckWay())){ //主动 server
//监测重新载入
new ThreadService().updateThread(info);
}else { //1被动 client
//校验 变更范围的节点IP
List<NodeModel> ipList = service.getNodeModelListBySetInfo(info);
//工作数量对象(ipList.size()个工作数,阻塞当前线程执行,直至所有子线程完成执行)
// CountDownLatch downLatch = new CountDownLatch(ipList.size());
logger.debug("监测设置"+info.getId()+" 节点变更数量"+ipList.size());
Iterator<NodeModel> ipIte = ipList.iterator();
while (ipIte.hasNext()) {
NodeModel ip = ipIte.next();
//仅向0服务器节点发送变更信息0服务器
if(ip!= null && ip.getNodeIp()!= null && ip.getNodeType().longValue()==0l && Common.hasIpInIpSegment(ip.getNodeIp())){
Common.runChangeRunnable(new ChangeSocketThread(null,ip.getNodeIp(),Constants.SSL_CLIENT_PORT,"char:updateConfig",jObject));
}else{
// downLatch.countDown();
}
}
}
}
/**
* Agent端通知变更方法
* @time Sep 20, 2011-2:33:37 PM
* @param ip
* @param jObject
*/
public void sendToClient(String ip,Object jObject) {
try {
Common.runChangeRunnable(new ChangeSocketThread(null,ip,Constants.SSL_CLIENT_PORT,"char:updateConfig",jObject));
} catch (Exception e) {
logger.debug("配置变更下发"+ip+"异常"+e.getMessage());
}
}
// public static void main(String [] args) {
//// String[] datas = new String[]{"202","401"};
// CommonDao dao = new CommonDao();
// CommonService service = new CommonService(dao);
// SetInfo old = service.getSetInfoById(226l);
// SetInfo news = service.getSetInfoById(1l);
// OperationsUpdateBySetInfo thread = new OperationsUpdateBySetInfo(old,news);
// thread.run();
//
// }
}

View File

@@ -0,0 +1,45 @@
package com.nms.server.thread.change;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
/**
* 周期性检查数据库,将检索变更通讯并下发
* @date Mar 31, 2012 10:03:04 AM
* @author ZhangGang
*
*/
public class ChangeManagerThread implements Runnable{
Logger logger = Logger.getLogger(ChangeManagerThread.class);
@Override
public void run() {
//将线程运行程序尽可能的catch捕获异常
try {
// Thread.currentThread().setName("变更操作管理线程");
Thread.currentThread().setName("Changing The Operation Management Thread");
Future<?> future = Common.getFutureMap().get(Constants.CHANGE_OPERATIONS);
if(future != null && !future.isCancelled() && !future.isDone()){ //运行中
logger.info("变更操作线程 运行中 不再启动新线程");
}else{
//为空或空闲中
logger.info("变更操作线程 空闲中 启动新线程");
// future = Common.service.submit(new ChangeThread("变更操作线程"));
future = Common.service.submit(new ChangeThread("Changing The Operating Thread"));
//注册
Common.getFutureMap().put(Constants.CHANGE_OPERATIONS, future);
}
} catch (Exception e) {
logger.error("",e);
}
}
}

View File

@@ -0,0 +1,534 @@
package com.nms.server.thread.change;
import static com.nms.server.common.Constants.WEB_SOCKET_IP;
import static com.nms.server.common.Constants.WEB_SOCKET_PORT;
import static com.nms.server.thread.socket.SocketCMD.DOWNLOAD_PLUGIN_SCRIPT;
import static com.nms.server.thread.socket.SocketCMD.SEND_PLUGIN_SCRIPT_FILE;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.google.common.collect.Sets;
import com.nms.server.bean.EventRecordLibrary;
import com.nms.server.bean.NodeModel;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.ChangeService;
import com.nms.server.service.CommonService;
import com.nms.server.util.FileUtils;
import com.nms.server.util.StringUtil;
import com.nms.server.util.socket.SSLSocketCallable;
import com.nms.server.util.socket.SocketUtils;
/**
* 下发第三方监测脚本文件
*/
public class ChangePluginScriptFile implements Runnable {
private static final Logger logger = Logger.getLogger(ChangePluginScriptFile.class);
/*
* 脚本文件临时存储目录
*/
private File pluginScriptDir;
/*
* 接收脚本文件的NC节点列表
*/
private Set<String> ncNodesIpStrSet;
/**
* 向DC管理的所有有效服务器节点发送脚本文件
*
* @param dpluginScriptDir 脚本文件临时存储目录
*/
public ChangePluginScriptFile(File pluginScriptDir) {
this.pluginScriptDir = pluginScriptDir;
}
/**
* 向指定的NC节点发送脚本文件
*
* @param pluginScriptDir 脚本文件临时存储目录
* @param ncNodesIpStrSet 待接收脚本的NC节点列表
*/
public ChangePluginScriptFile(File pluginScriptDir, Set<String> ncNodesIpStrSet) {
this.pluginScriptDir = pluginScriptDir;
this.ncNodesIpStrSet = ncNodesIpStrSet;
}
/*
* 用于统计向特定节点发送的脚本文件
*/
private Map<String, List<File>> sendRecordList = new HashMap<String, List<File>>();
/*
* 统计文件剩余发送次数用于清理DC临时脚本文件
*/
private Map<String, Integer> fileSendLastCount = new HashMap<String, Integer>();
@SuppressWarnings("unchecked")
public void run() {
CommonDao dao = null;
try {
dao = new CommonDao();
ChangeService changeService = new ChangeService(dao);
// Thread.currentThread().setName("发送监测脚本文件");
Thread.currentThread().setName("Send A Monitoring Script File");
Collection<File> files = FileUtils.listFiles(pluginScriptDir, null, false);
if (ncNodesIpStrSet == null) {
// 未指定接收的NC节点时根据检测设置确定待接收脚本的NC节点
Map<String, SetInfo> setInfoMap = new HashMap<String, SetInfo>();
List<SetInfo> setInfos = changeService.getAllSetInfo(1, 1);
for (SetInfo setInfo : setInfos) {
if("2".equals(setInfo.getIsControlStart())) {
setInfoMap.put(setInfo.getProcessIden(), setInfo);
}
}
for (File pluginFile : files) {
String processIden = pluginFile.getName().replaceAll("\\w+_(\\w+)\\.\\w+", "$1");
SetInfo setInfo = setInfoMap.get(processIden);
// 校验 变更范围的节点IP
List<NodeModel> ipNodeModelList = changeService.getNodeModelListBySetInfo(setInfo);
for (NodeModel ip : ipNodeModelList) {
// 仅向0服务器节点发送变更信息0服务器
if (ip != null && ip.getNodeIp() != null && ip.getNodeType().longValue() == 0l
&& Common.hasIpInIpSegment(ip.getNodeIp())) {
addToSendRecordList(ip.getNodeIp(), pluginFile); //
addTofileSendLastCount(pluginFile); //
}
}
}
ncNodesIpStrSet = sendRecordList.keySet();
} else {
// 已指定待接收脚本的NC节点
for (File pluginFile : files) {
for (String ip : ncNodesIpStrSet) {
addToSendRecordList(ip, pluginFile); // 统计向特定节点发送的脚本文件
addTofileSendLastCount(pluginFile); // 统计文件剩余发送次数
}
}
}
for (String ip : ncNodesIpStrSet) {
Common.runChangeRunnable(new SendPluginScriptFile(ip, sendRecordList.get(ip)));
}
// 延时清理脚本
new Thread(new DeletePluginScriptDirAfterSending()).start();
} catch (Exception e) {
logger.error("", e);
} finally {
if (dao != null) {
dao.close();
dao = null;
}
}
}
private void addTofileSendLastCount(File pluginFile) {
Integer count = fileSendLastCount.get(pluginFile.getName());
count = (count != null) ? count : 0;
fileSendLastCount.put(pluginFile.getName(), count + 1);
}
private void addToSendRecordList(String nodeIp, File pluginFile) {
if (sendRecordList.containsKey(nodeIp)) {
sendRecordList.get(nodeIp).add(pluginFile);
} else {
List<File> files = new ArrayList<File>();
files.add(pluginFile);
sendRecordList.put(nodeIp, files);
}
}
protected class SendPluginScriptFile extends SocketUtils implements Callable<Object> {
private String cmd;
private List<File> fileList;
public SendPluginScriptFile(String ip, List<File> fileList) {
super(ip, Constants.SSL_CLIENT_PORT);
this.cmd = SEND_PLUGIN_SCRIPT_FILE;
this.fileList = fileList;
}
@Override
public Object call() throws Exception {
// Thread.currentThread().setName("发送文件 To:>" + ip);
Thread.currentThread().setName("Send File To:>" + ip);
CommonDao dao = null;
try {
if(fileList == null || fileList.size()<1){
logger.info("没有脚本文件需要发送");
return null;
}
createClientSocket();
this.sendMessage(cmd);
logger.debug("cmd:> " + cmd + " 发送命令结果>> " + this.receiveMessage());
StringBuffer sb = new StringBuffer();
for (File file : fileList) {
sb.append(",").append(file.getName());
}
this.sendMessage(sb.substring(1));
this.receiveMessage();
this.bpSendFileByBath(fileList, pluginScriptDir.getCanonicalPath());
logger.debug("cmd:> " + cmd + " 发送脚本文件>> " + this.receiveMessage());
return true;
} catch (Exception e) {
String errorInfo = "Target communication:>" + ip + " create failure" + e.getMessage();
logger.error(errorInfo, e);
dao = new CommonDao();
ChangeService changeService = new ChangeService(dao);
Map<String, String> recordContent = new HashMap<String, String>();
HashSet<String> pluginFileNames = new HashSet<String>();
for (File pluginFile : fileList) {
pluginFileNames.add(pluginFile.getName());
}
String content = StringUtils.join(pluginFileNames.iterator(), "");
recordContent.put("scriptNames", content);
changeService.saveEventRecordLibrary(cmd, Common.getIpSeqIdMap().get(ip) + ""
, "S2C", JSONObject.fromObject(recordContent).toString());
return false;
} finally {
close(); // close socket
if(dao != null) {
dao.close();
dao = null;
}
// 文件剩余发送次数为0时由DeletePluginScriptDirAfterSending线程清理脚本
for (File file : fileList) {
fileSendLastCount.put(file.getName(), fileSendLastCount.get(file.getName()) - 1);
}
}
}
}
/**
* NC初始化时发送脚本文件
*
* @param ip 接收脚本的NC节点
*/
public static void sendPluginFileWhenNcInit(final String ip) {
ChangePluginScriptFile task = null;
File tempPluginDir = ChangePluginScriptFile.getNewTempPluginDirectory();
CommonDao dao = null;
List<String> prefixNameList = new ArrayList<String>();
try {
Set<String> ipList = new HashSet<String>(1);
ipList.add(ip);
task = new ChangePluginScriptFile(tempPluginDir, ipList);
dao = new CommonDao();
CommonService service = new CommonService(dao);
List<SetInfo> setInfoList = service.selectSetInfoList(1l, null, Common.getIpSeqIdMap().get(ip), null, null, 1l, null, 0l, true);
for (SetInfo setInfo : setInfoList) {
if("2".equals(setInfo.getIsControlStart())) {
String prefixName = setInfo.getCheckTypeName() + "_" + setInfo.getProcessIden() + ".";
prefixNameList.add(prefixName);
}
}
} catch (SQLException e) {
logger.error(e.getMessage(), e);
} finally {
if (dao != null) {
dao.close();
dao = null;
}
}
boolean bool = task.waitForGettingScriptFromWeb(tempPluginDir, prefixNameList);
if (bool) {
Common.service.execute(task);
} else { // 向Web请求脚本失败记录eventRecordLibrary
try {
dao = new CommonDao();
ChangeService changeService = new ChangeService(dao);
Map<String, String> recordContent = new HashMap<String, String>();
String content = StringUtils.join(prefixNameList.iterator(), "");
recordContent.put("scriptNames", content);
changeService.saveEventRecordLibrary(SEND_PLUGIN_SCRIPT_FILE, Common.getIpSeqIdMap().get(ip) + "",
"S2C", JSONObject.fromObject(recordContent).toString());
} catch (SQLException e) {
logger.error(e.getMessage(), e);
} finally {
if (dao != null) {
dao.close();
dao = null;
}
}
}
}
/**
* 解析失败暂存信息,重新发送脚本文件<br/>
*
* @param mrlList
*/
public static void sendPluginFileBaseOnEventRecord(List<EventRecordLibrary> recordList) {
if(recordList == null || recordList.isEmpty()) {
return;
}
// W2S [脚本名前缀,...]
Set<String> w2sDetecSetInfos = new HashSet<String>();
// S2C key:NC地址, value:[脚本名前缀,...]
Map<String, Set<String>> s2cDetecSetInfos = new HashMap<String, Set<String>>();
CommonDao dao = null;
try {
dao = new CommonDao();
ChangeService changeService = new ChangeService(dao);
for (EventRecordLibrary record : recordList) {
if (SEND_PLUGIN_SCRIPT_FILE.equalsIgnoreCase(record.getRecordCommand())) { // 脚本下发
Map<?, ?> map = StringUtil.getMapFromJsonObjStr(record.getRecordContent());
String recordType = record.getRecordType();
String scriptNames = (String) map.get("scriptNames");
if("W2S".equals(recordType)) {
for (String scriptName : scriptNames.split(",")) {
w2sDetecSetInfos.add(scriptName);
}
} else if("S2C".equals(recordType)) {
for (String scriptName : scriptNames.split(",")) {
String ip = Common.getNodeIpByUUID(record.getSeqId());
Set<String> scriptNameSet = s2cDetecSetInfos.get(ip);
if(scriptNameSet == null) {
scriptNameSet = new HashSet<String>();
}
scriptNameSet.add(scriptName);
s2cDetecSetInfos.put(ip, scriptNameSet);
}
}
}
changeService.deleteEventRecordByIds(record.getId() + "");
}
} catch (SQLException e) {
logger.error("Delete EventRecordLibrary", e);
}
// W2S, 向DC管理的所有有效节点发送脚本文件
if(!w2sDetecSetInfos.isEmpty()) {
File tempPluginDir = ChangePluginScriptFile.getNewTempPluginDirectory();
ChangePluginScriptFile task = new ChangePluginScriptFile(tempPluginDir);
boolean bool = task.waitForGettingScriptFromWeb(tempPluginDir, w2sDetecSetInfos);
if(bool) {
Common.service.execute(task);
} else { // 向Web请求脚本失败记录eventRecordLibrary
try {
dao = new CommonDao();
ChangeService changeService = new ChangeService(dao);
Map<String, String> recordContent = new HashMap<String, String>();
String content = StringUtils.join(w2sDetecSetInfos.iterator(), ",");
recordContent.put("scriptNames", content);
changeService.saveEventRecordLibrary(SEND_PLUGIN_SCRIPT_FILE, "",
"W2S", JSONObject.fromObject(recordContent).toString());
} catch (SQLException e) {
logger.error(e.getMessage(), e);
} finally {
if (dao != null) {
dao.close();
dao = null;
}
}
}
}
// S2C, 向指定节点发送脚本文件
Iterator<Entry<String, Set<String>>> it = s2cDetecSetInfos.entrySet().iterator();
while(it.hasNext()) {
Entry<String, Set<String>> entry = it.next();
Set<String> recvIpSet = Sets.newHashSet(entry.getKey());
File tempPluginDir = ChangePluginScriptFile.getNewTempPluginDirectory();
ChangePluginScriptFile task = new ChangePluginScriptFile(tempPluginDir, recvIpSet);
Set<String> prefixNames = entry.getValue();
boolean bool = task.waitForGettingScriptFromWeb(tempPluginDir, prefixNames);
bool = false;
if(bool) {
Common.service.execute(task);
} else { // 向Web请求脚本失败记录eventRecordLibrary
try {
dao = new CommonDao();
ChangeService changeService = new ChangeService(dao);
Map<String, String> recordContent = new HashMap<String, String>();
String content = StringUtils.join(prefixNames.iterator(), ",");
recordContent.put("scriptNames", content);
String ips = Common.getIpSeqIdMap().get(recvIpSet.iterator().next())+"";
changeService.saveEventRecordLibrary(SEND_PLUGIN_SCRIPT_FILE, ips,
"S2C", JSONObject.fromObject(recordContent).toString());
} catch (SQLException e) {
logger.error(e.getMessage(), e);
} finally {
if (dao != null) {
dao.close();
dao = null;
}
}
}
}
}
/**
* 根据脚本名称从Web获取脚本文件并等待脚本获取完成
*
* @param dir
* @param prefixNames
* @return
*/
protected Boolean waitForGettingScriptFromWeb(File dir, Collection<String> prefixNames) {
GetScriptFileFromWeb task = null;
task = this.new GetScriptFileFromWeb(dir, prefixNames);
FutureTask<Object> future = new FutureTask<Object>(task);
new Thread(future).start();
try {
Object result = future.get();
if(result == null) {
logger.debug("从Web服务器获取脚本失败脚本列表" + prefixNames);
return false;
}
return (Boolean) result;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return false;
}
protected class GetScriptFileFromWeb extends SSLSocketCallable {
Logger logger = Logger.getLogger(GetScriptFileFromWeb.class);
private File tempPluginDir; // 脚本存储目录
private String prefixNames; // 脚本名称列表(逗号分隔)
public GetScriptFileFromWeb(File tempPluginDir, Collection<String> prefixNames) {
super(WEB_SOCKET_IP, WEB_SOCKET_PORT);
this.tempPluginDir = tempPluginDir;
if(prefixNames != null && prefixNames.size() > 0){
StringBuilder sb = new StringBuilder();
for(String s : prefixNames){
if(StringUtils.isNotBlank(s)){
sb.append(",");
sb.append(s);
}
}
if(sb.length() >0){
sb.deleteCharAt(0);
this.prefixNames = sb.toString();
}
}
}
@Override
protected Object toDo() throws Exception {
// Thread.currentThread().setName("下载第三方监测脚本文件");
Thread.currentThread().setName("Download Third Party Monitoring Script Files");
if(StringUtils.isBlank(prefixNames)){
return true;
}
this.sendMessage(DOWNLOAD_PLUGIN_SCRIPT);
this.receiveMessage();
this.sendMessage(prefixNames);
String fileName = this.receiveMessage();
// 重复请求脚本Web无对应脚本时返回为空
if(FAIL.equalsIgnoreCase(fileName) || StringUtils.isBlank(fileName)) {
logger.error("The Web server does not monitor " + prefixNames + "the corresponding script file");
return false;
} else {
this.sendMessage(SUCCESS);
this.bpReceiveFileByBath(tempPluginDir.getCanonicalPath());
logger.info("已接收脚本文件:" + Arrays.toString(tempPluginDir.list()));
return true;
}
}
}
protected class DeletePluginScriptDirAfterSending implements Runnable {
@Override
public void run() {
while (!fileSendLastCount.isEmpty()) {
Iterator<Entry<String, Integer>> iterator = fileSendLastCount.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Integer> entry = iterator.next();
if(entry.getValue() == 0) {
iterator.remove();
}
}
try {
TimeUnit.SECONDS.sleep(2L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
FileUtils.deleteAllFiles(pluginScriptDir, true);
}
}
/**
* web向DC下发脚本或DC向web请求脚本过程中每次都创建新的临时目录<br/>
* DC向NC下发脚本完成后将删除临时目录
*
* @return
*/
public static File getNewTempPluginDirectory() {
File tempPluginDir = new File(Constants.PLUGIN_SCRIPT_FILE_DIR, System.currentTimeMillis()+"");
if (!tempPluginDir.exists()) {
tempPluginDir.mkdirs();
}
return tempPluginDir;
}
}

View File

@@ -0,0 +1,173 @@
package com.nms.server.thread.change;
import static com.nms.server.thread.socket.SocketCMD.SEND_PLUGIN_SCRIPT_FILE;
import java.util.List;
import java.util.concurrent.Callable;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.EventRecordLibrary;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.ChangeService;
import com.nms.server.thread.ResetServerThread;
import com.nms.server.thread.change.socket.ChangeSocketThread;
import com.nms.server.thread.mission.LoadNewMissionThread;
public class ChangeThread implements Callable<Object>{
Logger logger = Logger.getLogger(ChangeThread.class);
ChangeService changeService = null;
String name ;
/**
* 监测设置信息变更请求命令(设置告警修改)
*/
private String WEB_NOTICE_SET_INFO_ALERT = "char:setInfoAlert";
/**
* 节点或节点组状态变更请求命令节点组id:节点id缺省为0
*/
private String WEB_NOTICE_NODE_AND_GROUP_STATE_ALERT = "char:nodeAndGroupAlert";
/**
* 监测类别信息变更包括字段的变更(表结构改变)请求命令
*/
private String WEB_NOTICE_CHECK_TYPE_ALERT = "char:checkTypeIdAlert";
/**
* 任务信息变更请求命令
*/
private String WEB_NOTICE_MISSION_INFO_ALERT = "char:missionInfoAlert";
/**
* DC控制信息
*/
private String WEB_NOTICE_DATACONTROLLER = "char:Datacontroller";
/**
* 节点是否报主动告警变更请求命令
*/
private String WEB_NOTICE_ACTIVE_ALARM_START_ALERT = "char:isActiveAlarmStart";
public ChangeThread (String name){
this.name = name;
}
@Override
public Object call() throws Exception {
Thread.currentThread().setName(name);
CommonDao dao = null;
try {
dao = new CommonDao();
final ChangeService service = new ChangeService(dao);
List<EventRecordLibrary> mrlList = service.getNewEventRecordList();
//工作数量对象(ipList.size()个工作数,阻塞当前线程执行,直至所有子线程完成执行)
// CountDownLatch downLatch = new CountDownLatch(mrlList.size());
// 根据发送失败暂存信息,重新发送脚本文件
ChangePluginScriptFile.sendPluginFileBaseOnEventRecord(mrlList);
StringBuffer ids = new StringBuffer();
if(mrlList != null && mrlList.size()>0){
for (final EventRecordLibrary record : mrlList) {
boolean delFlag = false;
try {
//-- WEB TO SERVER 通讯,当DC查询了W2S的记录后就代表web和DC通信成功了剩下的就是DC和NC的通信了
if("W2S".equals(record.getRecordType())){
if(WEB_NOTICE_SET_INFO_ALERT.equals(record.getRecordCommand())){
Common.service.submit(new ChangeForSetInfo(record.getId(),record.getRecordContent()));
}else if(WEB_NOTICE_NODE_AND_GROUP_STATE_ALERT.equals(record.getRecordCommand())){
String datas = record.getRecordContent();
String [] data = datas.split(":");
Common.service.submit(new ChangeForNodeGroup(record.getId(),data));
}else if(WEB_NOTICE_CHECK_TYPE_ALERT.equals(record.getRecordCommand())){
String datas = record.getRecordContent();
String [] data = datas.split(":");
Common.service.submit(new ChangeForCheckType(record.getId(),data));
}else if(WEB_NOTICE_MISSION_INFO_ALERT.equals(record.getRecordCommand())){//新增任务
String datas = record.getRecordContent();
String [] data = datas.split(":");
if(StringUtils.isNotEmpty(data[0])){
Common.service.submit(new LoadNewMissionThread(Long.parseLong(data[0]) ));
}
delFlag = true;
}else if(WEB_NOTICE_DATACONTROLLER.equals(record.getRecordCommand())){
String datas = record.getRecordContent();
if(StringUtils.isNotEmpty(datas)){
Common.service.submit(new ResetServerThread(Integer.parseInt(datas) ));
}
delFlag = true;
}else if(WEB_NOTICE_ACTIVE_ALARM_START_ALERT.equals(record.getRecordCommand())){//NC是否报主动告警
//5秒后执行下发:否则多次更改状态时,可能不一定按设置的先后时间来
Thread.sleep(5000);
String datas = record.getRecordContent();
if(StringUtils.isNotEmpty(datas)){
Common.service.submit(new ChangeForActiveAlarmInfo(record.getId(),record.getRecordContent()));
}
delFlag = true;
} else {
// -- 无法判断直接删除
delFlag = true;
}
}
//-- SERVER TO CLIENT 通讯 针对于单节点的通信 监测设置的变更 节点状态的有效无效
else if("S2C".equals(record.getRecordType())){
if(SEND_PLUGIN_SCRIPT_FILE.equals(record.getRecordCommand())) {
// 第三方检测脚本下发通过ChangePluginScriptFile.sendPluginFileBaseOnEventRecord实现
continue;
} else {
if(record.getSeqId()!=null && record.getSeqId().longValue()!=0l){
String ip = Common.getNodeIpByUUID(record.getSeqId());
Common.runChangeRunnable(
new ChangeSocketThread(record.getId(),ip,
Constants.SSL_CLIENT_PORT,
record.getRecordCommand(),
JSONObject.fromObject(record.getRecordContent()))
);
}
}
}
} catch (NumberFormatException e) {
logger.error("", e);
}
if(delFlag)ids.append(",'"+record.getId()+"'");
}
if(ids.length() > 0){
ids.deleteCharAt(0);
logger.debug("待删除的 recordid" + ids);
service.deleteEventRecordByIds(ids.toString());
}
}
} catch (Exception e) {
logger.error("Change operation exception", e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
return null;
}
/* public static void p(Object ss){
System.out.print(ss==null?null:ss.toString());
}
public static void pl(Object ss){
System.out.println(ss==null?null:ss.toString());
}*/
}

View File

@@ -0,0 +1,108 @@
package com.nms.server.thread.change.socket;
import java.util.concurrent.Callable;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.EventRecordLibrary;
import com.nms.server.common.Common;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.ChangeService;
import com.nms.server.thread.socket.SocketCMD;
import com.nms.server.util.DateUtil;
import com.nms.server.util.socket.SocketUtils;
/**
* 变更通讯线程
* 发送变更信息通讯
* 线程返回值:
* -3 命令参数为空
* -2 通讯创建失败
* -1 变更信息保存入库
* 0 通讯成功并删除变更信息
*/
public class ChangeSocketThread extends SocketUtils implements Callable<Object> {
//日志组件对象
private static Logger logger = Logger.getLogger(ChangeSocketThread.class);
private String cmd;
private Object obj;
private Long recordId;
public ChangeSocketThread(Long recordId,String ip, int port,String cmd,Object data) {
super(ip, port);
this.recordId = recordId;
this.cmd = cmd;
this.obj = data;
}
@Override
public Object call(){
// Thread.currentThread().setName("变更通讯 To:>"+ip);
Thread.currentThread().setName("Change Communication To:>"+ip);
try {
createClientSocket();
if(StringUtils.isEmpty(cmd)){
return -3;
}
if(cmd.contains("char")){
this.sendMessage(cmd);
logger.debug("cmd:> "+cmd+" 发送命令结果>> "+this.receiveMessage());
this.sendMessage(((JSONObject)obj).toString());
logger.debug("cmd:> "+cmd+" 发送数据结果>> "+this.receiveMessage());
}
CommonDao dao = null;
try {
dao = new CommonDao();
ChangeService service = new ChangeService(dao);
if(recordId!=null){
service.deleteEventRecordByIds(recordId.toString());
}
} catch (Exception e) {
logger.error("Change record save failure", e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
return 0;
} catch (Exception e) {
String errorInfo = "Target communication:>"+ip+" create failure"+e.getMessage();
logger.error(errorInfo);
//Common.addErrorInfo(EmailTypeConstants.ERROR_SOCKET, ip, new Date(), (long)EmailTypeConstants.STATE_FAIL, errorInfo);
if(recordId==null){
CommonDao dao = null;
try {
dao = new CommonDao();
ChangeService service = new ChangeService(dao);
if(SocketCMD.WEB_NOTICE_ACTIVE_ALARM_START_ALERT.equalsIgnoreCase(cmd)) {//对于NC节点是否报主动告警的变更保存针对发给同一客户端NC的只保存一条避免多次变更后导致NC是否主动报警不是最新状态因为采用的是多线程所以不一定按时间先后
EventRecordLibrary event = service.selectEventRecordInfo("S2C", cmd, Common.getIpSeqIdMap().get(ip)+"");
if (event!=null) {//更新
service.updateEventRecordLibrary(event,DateUtil.getCurrentTime(),((JSONObject)obj).toString());
}else {//新增
service.saveEventRecordLibrary(cmd, Common.getIpSeqIdMap().get(ip)+"", "S2C", ((JSONObject)obj).toString());
}
}else {
service.saveEventRecordLibrary(cmd, Common.getIpSeqIdMap().get(ip)+"", "S2C", ((JSONObject)obj).toString());
}
} catch (Exception e1) {
logger.error("Change record save failure", e1);
return -1;
}finally{
if(dao!=null){dao.close();dao = null;}
}
}
return -2;
}finally{
close();
}
}
}

View File

@@ -0,0 +1,274 @@
package com.nms.server.thread.dataCollect;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.DetectInfo;
import com.nms.server.bean.NodeModel;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.CommonService;
import com.nms.server.thread.monitor.util.MonitorUtil;
import com.nms.server.util.BoneCPPool;
import com.nms.server.util.ExceptionPrintUtils;
//监测数据主动收集管理线程
public class DataCollectManagerThread implements Runnable{
private Logger logger = Logger.getLogger(DataCollectManagerThread.class);
private long startTime = Calendar.getInstance().getTimeInMillis();
public void run() {
// Thread.currentThread().setName("数据(监测数据、任务结果、回传文件)收集管理线程");
Thread.currentThread().setName("Data (Monitoring data, Task results, Return files) To Collect Management Threads");
CommonDao dao = null;
try {
dao = new CommonDao();
CommonService service = new CommonService(dao);
//- 非升级操作判断
if(Common.SERVER_UN_UPGRADE_FLAG){//---起什么作用?
//循环向自己管辖的Client端收集数据
List<String> ipList = new LinkedList<String>();
ipList = service.getAllComputerIp();//当前DC管理范围内+有效节点+有效节点组+服务器节点
int j=0;
String key="";
/*
* 2013-7-29 hyx
* 获得所有握手监测的节点信息若数据收集的节点在握手监测节点范围内则收集数据的同时进行握手监测传递true确认一个从握手监测中删除一个节点最后未握手的节点则不在数据收集范围内这种情况不应该存在
*/
Map<String,SetInfo> nodeMap = getNmsclientNodeList(service);//ip:setinfo
//20160901 hyx 增加此代码的原因是数据收集管理线程运行一段时间后会出现获取数据库连接一直阻塞的情况而此时其它线程是可以正常获取数据库连接的一个原因可能是之前没有dao=null另一个原因可能是之后的数据收集及超时操作可能由于各种原因如异常节点较多导致连接最后没能正常关闭所以在连接不使用的时候尽早关闭
try {
if(dao!=null){
dao.close();
dao=null;
}
} catch (Exception e)
{
logger.error("Data collection management thread early closing database connection exception", e);
}
boolean nmsclientFlag = false;//节点是否进行握手监测的标识
Map<String,Future<?>> ipFutureMap = new HashMap<String,Future<?>>();
int ipNum = ipList.size();
for(int i=0;i<ipNum;i++) {//最多启动几个线程,之后呢??其它未收集的怎么办??应该超过池里的线程之后,会排队吧,等有空闲的了,再开启线程??
String ip = ipList.get(i);
if(ip!= null && !Common.noDetectDataNodeList.contains(ip)){
//- 检查线程运行状态 运行中无操作
key = Constants.DATA_COLLECT+":"+ip;
Future<?> future = Common.getFutureMap().get(key);
if(future != null && !future.isCancelled() && !future.isDone()){ //运行中
logger.info(""+ip+"的数据(监测数据、任务结果、回传文件)收集执行线程 运行中 不再启动新收集线程");
continue;
}
SetInfo setInfo = nodeMap.get(ip);
if(nodeMap.containsKey(ip)) {//当前节点需要进行握手监测
nmsclientFlag = true;
// future = Common.service.submit(new DataCollectThread("数据收集执行线程:>"+ip,ip,Constants.SSL_CLIENT_PORT,nmsclientFlag,setInfo,startTime));
future = Common.service.submit(new DataCollectThread("Data Collection Execution Thread:>"+ip,ip,Constants.SSL_CLIENT_PORT,nmsclientFlag,setInfo,startTime));
ipFutureMap.put(ip, future);
}else {//当前节点不需要进行握手监测
nmsclientFlag = false;
future = Common.service.submit(new DataCollectThread("Data Collection Execution ThreadNo need shakehand:>"+ip,ip,Constants.SSL_CLIENT_PORT,nmsclientFlag,setInfo,startTime));
}
//注册
Common.getFutureMap().put(key, future);
j++;
}
}
logger.info("*******************************************共"+ipNum+"个节点(实际收集"+(ipNum-Common.noDetectDataNodeList.size())+"个),数据(监测数据、任务结果、回传文件)收集执行线程启动个数:"+j);
//握手监测信息
Iterator ite = ipFutureMap.entrySet().iterator();
Thread.sleep(Constants.DATA_COLLECT_DAILY*1000);//默认2分钟socket超时20多秒ping失败13秒ssh失败20多秒共计1分钟左右再加上数据收集的时间2分钟满足
for(;ite.hasNext();) {
Entry en = (Entry)ite.next();
String ip = (String)en.getKey();
if(Common.noDetectDataNodeList.contains(ip)){
continue;
}
SetInfo setInfo = nodeMap.get(ip);
Object rlt = null;
Future<?> futureTmp = (Future<?>)en.getValue();
try {
logger.info("对节点"+ip+"的数据收集及握手监测 等待中。。。");
rlt = futureTmp.get(2, TimeUnit.MILLISECONDS);//如果在执行时间内没有获取结果则直接返回null
} catch (TimeoutException e) {
logger.debug(""+ip+" 的数据收集超时("+Constants.DATA_COLLECT_DAILY+"秒)");
String keyTmp = Constants.DATA_COLLECT+":"+ip;
Common.cancelRunnableAtOnce(keyTmp);//此处很重要,需要取消线程的执行,如果取消失败,或者不及时,会生成两条握手监测数据(收集线程一条,管理线程一条)
}finally{
DetectInfo detectInfo = rlt!=null?((DetectInfo)rlt):(new DetectInfo());
detectInfo.setTestTimes(1);//尝试次数
detectInfo.setCheckTime(System.currentTimeMillis());//监测时间
try{
/**
* -- 监测数据描述信息非空web界面的状态信息才生成监测数据:
* 1、监测数据为空可能是收集线程超时导致ping或者ssh未执行完毕未生成描述信息
* 2、此时web端进行超周期设置时过滤掉异常的节点异常节点的异常信息还是采用之前周期的-此功能 20160906 web端还未实现
*/
if(StringUtils.isBlank(detectInfo.getDescInfo())){
detectInfo.setDescInfo(Constants.NO_DETECTDATA_STATUS_INFO);
logger.info("对节点"+ip+"的数据集超时,未获取监测数据");
MonitorUtil.createMonitorData(ip, setInfo, startTime, Common.getAlarmInfoMap().get(setInfo.getId()+ ""), detectInfo);
if(!Common.noDetectDataNodeList.contains(ip)){
Common.addNoDeteDataNode(ip);
logger.info("对节点"+ip+"的数据集超时,将节点加入无监测数据列表,由无监测数据收集线程进行收集");
}
}
} catch (Exception ex) {
logger.error(ExceptionPrintUtils.printExceptionStack(ex));
String processIden = setInfo.getProcessIden()==null ? "" : setInfo.getProcessIden();
String[] alarm = Common.alarmExceptionInfo(setInfo.getId(), ip, Constants.DETEC_NMSC_STR,processIden , startTime, 1,Constants.DETECTION_INFO_ALARM_WRONG, ex.getMessage());
Common.addAlarmData(alarm);
}
}
logger.info("对节点"+ip+"的数据收集及握手监测 完毕"+Constants.DATA_COLLECT_DAILY);
}
}
} catch (Exception e) {
logger.error("Monitoring data collection management threads run abnormity",e);
} finally {
if(dao!=null){
dao.close();
dao=null;
}
logger.debug("执行结束");
}
}
//获得进行握手监测的所有节点:握手的条件:到首次监测时间+节点有效(节点组有效)+监测设置内的节点+监测设置有效
private Map<String,SetInfo> getNmsclientNodeList(CommonService service){
List<NodeModel> nodeList = new ArrayList<NodeModel>();
Map<String,SetInfo> nodeMap = new HashMap<String,SetInfo>();
try
{
if(Constants.FLAG_NMSC==1){
List<SetInfo> setList = service.getDrivingSetInfo(Constants.DETEC_NMSC_STR);//获得checkType类型的所有监测设置
if(setList!=null && setList.size()>0){
List<NodeModel> nodeTmpList = new ArrayList<NodeModel>();
for (Iterator setIte = setList.iterator(); setIte.hasNext();) {
SetInfo setInfo = (SetInfo) setIte.next();
//如果首次监测时间没到,则不用查询节点
//- 计算启动后第一次检测时间 默认即时启动
long initialDelay = 0l;
if(setInfo.getPlanCheckTime()!=null){
initialDelay = setInfo.getPlanCheckTime().longValue() - (new Date().getTime());
initialDelay = initialDelay > 0l ? initialDelay : 0l;
}
if(initialDelay<=0) {//到首次监测时间了,查询进行握手监测的节点
//节点可能存在重复的情况
nodeTmpList = service.getNodeModelListBySetInfo(setInfo);
nodeList.addAll(nodeTmpList);
}else {
logger.info("握手监测,未到首次监测时间,距离首次监测时间还有:"+initialDelay/1000/60+"分钟");
}
for(NodeModel node:nodeTmpList) {
nodeMap.put(node.getNodeIp(), setInfo);
}
}
logger.debug("本次服务器握手监测的节点数为:"+nodeMap.size());
}
}else {
logger.info("未开启握手监测标识");
}
} catch (Exception e)
{
logger.error("Obtaining a node exception for handshake monitoring", e);
}
return nodeMap;
}
public static void main(String[] args) throws Exception {
CommonDao dao = null;
ScheduledFuture<?> future = null;
Object rlt = null;
try
{
Thread.sleep(3000);
BoneCPPool.initPool();
Thread.sleep(3000);
// DataCollectManagerThread runThread = new DataCollectManagerThread();
// Thread thread = new Thread(runThread);
// thread.start();
dao = new CommonDao();
CommonService service = new CommonService(dao);
// 初始化自身信息(失败情况下会由Web唤醒)
if(!service.initServerParams()){
return;
}
future = Common.scheduled.scheduleWithFixedDelay(new DataCollectManagerThread(), 0, 300, TimeUnit.SECONDS);
Common.registRunnable(Constants.DATA_COLLECT_MANAGER, future);
Thread.sleep(7000);
System.out.println(future==null?"null3":future.isDone());
System.out.println(future==null?"null4":future.isCancelled());
System.out.println("***************=====结束了?");
rlt = future.get();
Thread.sleep(5000);
// future.cancel(true);
//发生异常未捕捉后:
System.out.println("future="+future);
System.out.println(future==null?"null55":future.isDone());
System.out.println(future==null?"null55":future.isCancelled());
System.out.println("==============结束了55");
System.out.println("rlt="+rlt);
} catch (Exception e)
{
System.out.println("catch*******************");
System.out.println("eeeeeeeefuture="+future);
System.out.println(future==null?"eeeeeeeeenull55":future.isDone());
System.out.println(future==null?"eeeeeeeeeenull55":future.isCancelled());
System.out.println("eeeeeeeeee==============结束了55");
System.out.println("eeeeeeeerlt="+rlt);
System.out.println("数据收集线程是否注册-catch-done"+Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER).isDone());
System.out.println("数据收集线程是否注册-catch-cancel"+Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER).isCancelled());
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(dao!=null){
dao.close();
dao=null;
}
System.out.println("finally**********************************");
// Common.scheduled.shutdown();//关闭线程池
// System.out.println(Common.scheduled.isTerminated());//?????????
// System.out.println(Common.scheduled.isShutdown());
System.out.println("数据收集线程是否注册-catch-done"+Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER).isDone());
System.out.println("数据收集线程是否注册-catch-cancel"+Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER).isCancelled());
// System.out.println("关闭线程池");
}
}
}

View File

@@ -0,0 +1,613 @@
package com.nms.server.thread.dataCollect;
import java.io.File;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.DetectInfo;
import com.nms.server.bean.MissionResult2;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.thread.file.UnZipManagerThread;
import com.nms.server.thread.socket.SocketCMD;
import com.nms.server.util.socket.SSLSocketCallableForDateCollection;
/**
* 数据(监测数据、任务结果、回传文件)收集线程 DC发送要收集数据的命令
* Agent端发送6种数据命令中的一种就开始收集如果Agent发送6种数据命令之外的命令就结束此次通信
*
* @author hyx
*
*/
public class DataCollectThread extends SSLSocketCallableForDateCollection {
Logger logger = Logger.getLogger(DataCollectThread.class);
private String name; // 自定义Thread Name
private boolean nmsclientFlag = true;// 是否进行握手监测
private SetInfo setInfo;
private long startTime;//数据收集服务器第一次启动的时间
public DataCollectThread(String name, String ip, Integer port,
boolean nmsclientFlag, SetInfo setInfo,long startTime) throws Exception {
super(ip, port);
this.name = name;
this.nmsclientFlag = nmsclientFlag;
this.setInfo = setInfo;
this.startTime = startTime;
}
/**
* 与Client端进行通信SSLSocketCallable已经握手过了 收集监测数据、任务结果、回传文件
*/
@Override
protected Object toDo() throws Exception {
// 为当前线程命名 ,用与开发阶段友好输出。
Thread.currentThread().setName(name);
int zipDetect = 0;
int csvDetect = 0;
int zipTaskResult = 0;
int objTaskResult = 0;
int zipTaskReturn = 0;
int fileTaskReturn = 0;
DetectInfo nmscDetec = null;
try {
// 进行通信:SSLSocketCallable已经建立握手了
sendMessage(SocketCMD.REQ_DATA_COLLECT);// DC要进行数据的收集监测数据、任务结果、回传文件
String msg0 = receiveMessage();// Client:发送数据文件类型监测数据、任务结果、回传文件的zip、csv或者list或者没有数据结束通信或者关闭socket则会收到null
// 执行到此,说明通信已经建立,进行握手
if (nmsclientFlag && StringUtils.isNotBlank(msg0)) {
nmscDetec = Common.doNmsClientDetect(ip, setInfo, startTime);
}
// else if (StringUtils.isBlank(msg0) && Constants.IS_HANDEL_EXCEPTION_NODE){
// nmscDetec = Common.errorNodeToDo(name, nmsclientFlag, setInfo, ip, Calendar.getInstance().getTimeInMillis(), startTime);
// }
while (Constants.FLAG_DATA_COLLECT_ONLY_HANDSHAKE==1 && true) {
logger.info("数据收集client端" + this.ip + "回应信息:" + msg0);
if (Thread.currentThread().isInterrupted()) {
// 线程被中断,结束收集线程
logger.info("收集线程 被中断,停止收集数据");
return nmscDetec;
}
// 监测数据---start
if (SocketCMD.DETECT_DATA_ZIP_TYPE.equalsIgnoreCase(msg0)) {
logger.info("数据类型监测数据的zip文件");
this.sendMessage(SUCCESS);// DC告诉client我知道你要发送zip类型的数据了
String uploadPath = Constants.ZIP_FILE_DETECT_DATA_DIR;
String fileName = receiveMessage();// client发送zip文件的名称
this.sendMessage(SUCCESS);// DC收到zip文件的名称给client回成功信息
bpReceiveFile(uploadPath + File.separator + fileName);// client收到zip文件名发送成功后发送zip文件DC接收client发送的zip文件
this.sendMessage(SUCCESS);// DC接收完client发送的zip文件存入指定路径后给client回接收成功信息
// 启动并注册 解压文件线程
Future<?> future = Common.getFutureMap().get(
Constants.UNZIP_FILE_MANAGER);
if (future == null) {
future = Common.scheduled.scheduleWithFixedDelay(
new UnZipManagerThread(), 0, 30,
TimeUnit.SECONDS);
Common.registRunnable(Constants.UNZIP_FILE_MANAGER,
future);
}
zipDetect++;
msg0 = receiveMessage();// Client:再次发送数据文件类型,或者没有数据,结束通信
} else if (SocketCMD.DETECT_DATA_CSV_TYPE
.equalsIgnoreCase(msg0)) {
logger.info("数据类型监测数据的csv文件");
sendMessage(SUCCESS);// DC告诉client我知道你要发送csv类型的数据了client端就开始发送csv文件
LinkedList<byte[]> bslist = receiveFileBytesByBath();// DC端就准备接收csv文件
if (bslist != null && bslist.size() > 0) {
int detectDataNum = Common.getAllDeteDataNum();
if(bslist.size()>Constants.MAX_COLLECT_RESOVE_DETECT_DATA_NUM
|| detectDataNum>=Constants.MAX_DETECT_DATA_RESOVE_LIMIT_NUM){
//存入dc_overrun/detect/zip_resove等待之后解析避免内存过大导致内存溢出
logger.info("收集数据过多:"+bslist.size()+"条,或者 内存中监测数据总数过大:"+detectDataNum+" 为避免内存溢出,暂时存入硬盘,待之后解析入库,");
Common.saveByteToFile(bslist);
}else {
Common.addAllDeteDataList(bslist);
}
} else {
logger.debug("接收 监测数据 文件数:0");
}
sendMessage(SUCCESS);// DC端csv文件接收完毕后告诉client端文件接收完毕
csvDetect++;
msg0 = receiveMessage();// Client:再次发送数据文件类型,或者没有数据,结束通信
}
// 监测数据---end
// 任务结果---start
else if (SocketCMD.TASK_RESULT_ZIP_TYPE.equalsIgnoreCase(msg0)) {
logger.info("数据类型任务结果的zip文件");
this.sendMessage(SUCCESS);// DC告诉client我知道你要发送zip类型的数据了
String uploadPath = Constants.ZIP_FILE_TASK_RESULT_DIR;
String fileName = receiveMessage();// client发送zip文件的名称
this.sendMessage(SUCCESS);// DC收到zip文件的名称给client回成功信息
bpReceiveFile(uploadPath + File.separator + fileName);// client收到zip文件名发送成功后发送zip文件DC接收client发送的zip文件
this.sendMessage(SUCCESS);// DC接收完client发送的zip文件存入指定路径后给client回接收成功信息
// 启动并注册 解压文件线程
Future<?> future = Common.getFutureMap().get(
Constants.UNZIP_FILE_MANAGER);
if (future == null) {
future = Common.scheduled.scheduleWithFixedDelay(
new UnZipManagerThread(), 0, 30,
TimeUnit.SECONDS);
Common.registRunnable(Constants.UNZIP_FILE_MANAGER,
future);
}
zipTaskResult++;
msg0 = receiveMessage();// Client:再次发送数据文件类型,或者没有数据,结束通信
} else if (SocketCMD.TASK_RESULT_OBJ_TYPE
.equalsIgnoreCase(msg0)) {// --
// 接收返回的任务结果修改为receiveObject
logger.info("数据类型任务结果的List<String[]>");
sendMessage(SUCCESS);
List<String> resultList = (List<String>) receiveObject();
sendMessage(SUCCESS);
for (String result : resultList) {
logger.info("任务结果:" + result);
String[] misRlt2 = result
.split(Constants.COMMON_DATA_SPLIT);
MissionResult2 result2 = Common
.resoveMissionResult(misRlt2);
Common.addResultToResultList(result2);// 没有addAll因为传递的任务结果可能是不同类型的任务结果1-6
}
objTaskResult++;
msg0 = receiveMessage();// Client:再次发送数据文件类型,或者没有数据,结束通信
}
// 任务结果---end
// 回传文件---start
else if (SocketCMD.TASK_RETURN_ZIP_TYPE.equalsIgnoreCase(msg0)) {
logger.info("数据类型回传文件的zip文件");
this.sendMessage(SUCCESS);// DC告诉client我知道你要发送zip类型的数据了
String uploadPath = Constants.ZIP_FILE_TASK_RETURN_DIR;
String fileName = receiveMessage();// client发送zip文件的名称
this.sendMessage(SUCCESS);// DC收到zip文件的名称给client回成功信息
bpReceiveFile(uploadPath + File.separator + fileName);// client收到zip文件名发送成功后发送zip文件DC接收client发送的zip文件
this.sendMessage(SUCCESS);// DC接收完client发送的zip文件存入指定路径后给client回接收成功信息
// 启动并注册 解压文件线程
Future<?> future = Common.getFutureMap().get(
Constants.UNZIP_FILE_MANAGER);
if (future == null) {
future = Common.scheduled.scheduleWithFixedDelay(
new UnZipManagerThread(), 0, 30,
TimeUnit.SECONDS);
Common.registRunnable(Constants.UNZIP_FILE_MANAGER,
future);
}
zipTaskReturn++;
msg0 = receiveMessage();// Client:再次发送数据文件类型,或者没有数据,结束通信
} else if (SocketCMD.TASK_RETURN_FILE_TYPE
.equalsIgnoreCase(msg0)) {// -- 接收任务4“启动”的回传文件
sendMessage(SUCCESS);
String msg1 = receiveMessage();
sendMessage(SUCCESS);
logger.info(msg1);
String[] result = msg1.split(Constants.COMMON_DATA_SPLIT);
MissionResult2 result2 = Common.resoveMissionResult(result);
String fileName = receiveMessage();
sendMessage(SUCCESS);
logger.debug("MISSION_FILE_UPLOAD_DIR"
+ Constants.MISSION_FILE_UPLOAD_DIR);
this.bpReceiveFile(Constants.MISSION_FILE_UPLOAD_DIR
+ fileName);
sendMessage(SUCCESS);
logger.debug("MISSION_FILE_UPLOAD_DIR"
+ Constants.MISSION_FILE_UPLOAD_DIR + fileName);
result2.setFileInfo(fileName);
Common.addResultToResultList(result2);
fileTaskReturn++;
msg0 = receiveMessage();// Client:再次发送数据文件类型,或者没有数据,结束通信
}
// 回传文件---end
else {// 如果没有这个else且对方发送的命令非以上6种则会死循环
logger.info("数据收集线程与client端" + this.ip + "的通信结束");
break;
}
}
logger.debug("client端" + this.ip + ",监测数据zip文件发送次数" + zipDetect);// 每次可以发送多个zip
logger.debug("client端" + this.ip + ",监测数据csv文件发送次数" + csvDetect);// 每次可以发送多个csv
logger.debug("client端" + this.ip + ",任务结果zip文件发送次数" + zipTaskResult);// 每次可以发送多个
logger.debug("client端" + this.ip + ",任务结果obj文件发送次数" + objTaskResult);// 每次可以发送多个
logger.debug("client端" + this.ip + ",回传文件zip文件发送次数" + zipTaskReturn);// 每次可以发送多个
logger.debug("client端" + this.ip + ",回传文件file文件发送次数"
+ fileTaskReturn);// 每次可以发送多个
} catch (Exception e) {
logger.error("Anomaly in the process of data collection", e);
// if(nmscDetec==null && Constants.IS_HANDEL_EXCEPTION_NODE){
// nmscDetec = Common.errorNodeToDo(name, nmsclientFlag, setInfo, ip, Calendar.getInstance().getTimeInMillis(), startTime);
// }
}
return nmscDetec;
}
// //创建握手监测信息
// protected void createNmsClientDetectData(DetectInfo detectInfo){
// if(detectInfo!=null){
// int testTimes = 1;
// Long checkTime = System.currentTimeMillis();
// detectInfo.setTestTimes(testTimes);//尝试次数
// detectInfo.setCheckTime(checkTime);//监测时间
// try{
// /**
// * -- 监测数据描述信息非空web界面的状态信息才生成监测数据:
// * 1、监测数据为空可能是收集线程超时导致ping或者ssh未执行完毕未生成描述信息
// * 2、此时web端进行超周期设置时过滤掉异常的节点异常节点的异常信息还是采用之前周期的-此功能 20160906 web端还未实现
// */
// if(StringUtils.isNotBlank(detectInfo.getDescInfo())){
// MonitorUtil.createMonitorData(ip, setInfo, startTime, Common.getAlarmInfoMap().get(setInfo.getId()+ ""), detectInfo);
// }
// } catch (Exception ex) {
// logger.error(ExceptionPrintUtils.printExceptionStack(ex));
// String processIden = setInfo.getProcessIden()==null ? "" : setInfo.getProcessIden();
// String[] alarm = Common.alarmExceptionInfo(setInfo.getId(), ip, Constants.DETEC_NMSC_STR,processIden , startTime, 1,Constants.DETECTION_INFO_ALARM_WRONG, ex.getMessage());
// Common.addAlarmData(alarm);
// }
// }
// }
// 收集数据前先进行握手监测通信
// private DetectInfo doNmsClientDetect() {
// logger.info("开始握手监测>" + ip);
// DetectInfo detectInfo = null;
// try {
// // -- 发送握手命令
// String sendTime = Calendar.getInstance().getTimeInMillis() + "";
// // sendMessage(SocketCMD.CLIENT_REQ_HAND_SHAKE);//DC与NC握手通信后NC会关闭socket导致无法收集数据
// // String msg = receiveMessage();//收到回复的信息后,说明握手成功了
//
// String backTime = Calendar.getInstance().getTimeInMillis() + "";
// // -- 信息保存到监测信息对象中
// detectInfo = new DetectInfo();
//
// StringBuffer nmsClientDetailDetectInfo = new StringBuffer();
// nmsClientDetailDetectInfo.append(SocketCMD.CLIENT_REQ_HAND_SHAKE);// 发送信息
// nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);// 分隔符
// nmsClientDetailDetectInfo.append(SUCCESS + ":"
// + SocketCMD.CLIENT_REQ_HAND_SHAKE + "|" + sendTime);// 返回信息:DC端伪造的因为也不需要NC回复信息了
// nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);// 分隔符
// nmsClientDetailDetectInfo.append("0");// 是否可达,0:可达1不可达
// nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);// 分隔符
// nmsClientDetailDetectInfo.append(sendTime);// 发送时间
// nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);// 分隔符
// nmsClientDetailDetectInfo.append(backTime);// 返回时间
// nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);// 分隔符
// nmsClientDetailDetectInfo.append(DateUtil.getSecondsFromBeinToEnd(
// new Date(Long.parseLong(sendTime)).getTime(), new Date(Long
// .parseLong(backTime)).getTime())
// + "");// 延迟时间
//
// detectInfo.getDetailDatas().add(
// nmsClientDetailDetectInfo.toString());
//
// detectInfo.setDescInfo("开始"
// + DateUtil.getStringByLongStr(sendTime)
// + " NMSClient握手"
// + DateUtil.getStringByLongStr(backTime)
// + " 成功 ");
//
// } catch (Exception e) {
// logger.error("生成节点:"+ip+"信息发生异常", e);
// }finally{
// if (Thread.currentThread().isInterrupted()) {
// // 线程被中断,结束收集线程
// logger.info("收集线程 被中断");
// return detectInfo;
// }else {
// Common.createNmsClientDetectData(setInfo, ip, detectInfo, startTime);
// }
// }
//
// return detectInfo;
// }
//
// @Override
// protected DetectInfo errorNodeToDo(Long checkTime){
// if(Constants.IS_HANDEL_EXCEPTION_NODE) {
// return Common.errorNodeToDo(name, nmsclientFlag, setInfo, ip, checkTime, startTime);
// }else {
// return null;
// }
// }
// @Override
// protected DetectInfo errorNodeToDo(Long checkTime){
// Thread.currentThread().setName(name + "(异常节点)");
// if (Thread.currentThread().isInterrupted()) {
// // 线程被中断,结束收集线程
// logger.info("收集线程 被中断");
// return null;
// }
// if(!nmsclientFlag){//对于不需要进行握手监测的节点,则不进行握手
// return null;
// }
// DetectInfo detectInfo = null;
// String stateInfo = "";
// try{
// detectInfo = new DetectInfo();
// String failStartTime = Calendar.getInstance().getTimeInMillis()
// + "";
// long maxTimes = 1l;
//
// if (setInfo != null && setInfo.getCheckMaxTimes() != null) {
// maxTimes = setInfo.getCheckMaxTimes();
// }
//
// String[] pingData = pingHandshake(ip, maxTimes);
//
// String failEndTime = Calendar.getInstance().getTimeInMillis() + "";
//
// if ((StringUtils.isEmpty(pingData[1]) || "0".equals(pingData[1]))) {// ping不通无握手监测详细数据
// stateInfo = "网络异常";
// } else {
// // 可以ping通进行ssh测试 如果ssh可以通 就产生一条握手失败信息 如果ssh不同就产生一条ssh失败信息
// String sshResult = Constants.SUCCESS;
// if("1".equals(Constants.FLAG_HANDWALK_SSH)){
// String[] userPwdInfo = Common.getIpUserPwdMap().get(ip);
// if (userPwdInfo!=null &&
// userPwdInfo.length>=3 && "1".equals(userPwdInfo[2])) {//应该判断nc的操作系统不是dc的,1:linux; 2:windows; 3:other
// sshResult = sshConnect(ip,userPwdInfo[0],userPwdInfo[1]);
// }
// }
//
// if (Constants.SUCCESS.equals(sshResult)) {
// stateInfo = "开始" + DateUtil.getStringByLong(checkTime)
// + " NMSClient握手" + DateUtil.getCurrentTime() + " 失败 ";
// StringBuffer detailInfo = new StringBuffer();
// detailInfo.append(SocketCMD.CLIENT_REQ_HAND_SHAKE);// 发送信息
// detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
// detailInfo.append("");// 返回信息
// detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
// detailInfo.append("1");// 是否可达,0:可达1不可达
// detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
// detailInfo.append(failStartTime);// 发送时间
// detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
// detailInfo.append(failEndTime);// 返回时间
// detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
// detailInfo.append(DateUtil.getSecondsFromBeinToEnd(new Date(
// Long.parseLong(failStartTime)).getTime(), new Date(Long
// .parseLong(failEndTime)).getTime())
// + "");// 延迟时间
// detectInfo.getDetailDatas().add(detailInfo.toString());
// }else{
// stateInfo = sshResult;
// }
// }
// }catch (Exception e) {
// logger.error("生成异常节点:"+ip+"信息发生异常", e);
// }finally{
// detectInfo.setDescInfo(stateInfo);
// logger.info("与 " + ip + " 的握手监测发生异常 失败:" + stateInfo);
// createNmsClientDetectData(detectInfo);//生成监测数据信息
// }
// return detectInfo;
// }
//
// private String[] pingHandshake(String ip, long maxTimes) {
//
// String command = ""; // 命令语句
// int minTime = Integer.MAX_VALUE, maxTime = 0, totalTime = 0, curTime; // 最短时间,最长时间,总时间,时间变量
// int snum = 0, fnum = 0; // 发包成功和失败数
//
// // 判断系统类型 win or Linux
// String system = (String) (System.getProperty("os.name")).toLowerCase();
//
// if (system.toLowerCase().indexOf("win") != -1) {
// command += "ping -n 4 " + ip;// 尝试次数 -n
// } else if (system.toLowerCase().indexOf("linux") != -1) {
// command += "ping -c 4 " + ip;
// } else {
// command += "ping -w 4 " + ip;
// }
//
// String stateInfo = "";
// String[] datas2 = new String[7];
// Process process = null;
// BufferedReader in = null; // 读取 Ping命令返回的信息
// StringBuffer buffer = new StringBuffer();
// try {
// logger.debug("ping command:" + command);
// process = Runtime.getRuntime().exec(command);
// in = new BufferedReader(new InputStreamReader(process
// .getInputStream()));
// String line = null;
// long count = maxTimes + 10;
// int index;
// // 最多多读10行
// while ((line = in.readLine()) != null && count != 0) {
// if ("".equals(line)) {
// count--;
// continue;
// } // 空串跳过
// buffer.append(line + "\n");
// line = line.toLowerCase();
// logger.debug("line:" + line);
// if (line.indexOf("ttl") > 0) { // 获得成功响应的数据
// count--; // 计数器自减1
// // 截取time 值
// if ((index = line.lastIndexOf("ms")) != -1) {
// byte[] buf = line.getBytes();
// int start = 0, end = buf.length, i, j;
// // 下标末点
// for (i = index; i >= 0; i--) {
// if (Character.isDigit((char) buf[i])) {
// end = i;
// break;
// }
// }
// if (i == 0)
// continue;
// // 下标起点
// for (j = end; j >= 0; j--) {
// if (!Character.isDigit((char) buf[j])) {
// start = j + 1;
// break;
// }
// }
// // 时间值截取
// curTime = Integer.parseInt(new String(buf, start, end
// + 1 - start));
// snum++; // 成功接收次数加1
// totalTime += curTime; // 计算总时间
//
// if (curTime < minTime) {
// minTime = curTime;
// } // 最小时间
//
// if (curTime > maxTime) {
// maxTime = curTime;
// } // 最大时间
// }
// } else if (line.split(" ").length < 4) {
// count--; // 计数器自减1
// fnum++; // 失败接收次数加1
// } else {
// stateInfo += line + "\n";
// }
// }
//
// if (totalTime == 0) {
// minTime = 0;
// }
//
// // 已发送包数
// datas2[0] = "" + (snum + fnum);
// datas2[1] = "" + snum;
// datas2[2] = "" + fnum;
//
// BigDecimal fnum0 = new BigDecimal(fnum);
// BigDecimal tnum0 = new BigDecimal(snum + fnum);
// DecimalFormat df = new DecimalFormat("####0.00");
// if (tnum0.intValue() != 0) {
// datas2[3] = ""
// + ((new BigDecimal(df.format(fnum0.divide(tnum0, 4,
// RoundingMode.HALF_UP))))
// .multiply(new BigDecimal(100)));
// }
// datas2[4] = "" + minTime;
// datas2[5] = "" + maxTime;
// datas2[6] = "" + (snum == 0 ? 0 : (totalTime / snum));
// } catch (Exception e) {
// logger.error(ExceptionPrintUtils.printExceptionStack(e));
// } finally {
// if (in != null) {
// try {
// in.close();
// } catch (IOException e) {
// logger.error("", e);
// }
// }
// if (process != null)
// process.destroy();
// process = null;
// }
//
// /*
// * if(state==-1){ isSuccess = false; }else{ isSuccess = true; }
// */
// return datas2;
// }
//
// private String sshConnect(String hostname, String username, String password) {
// String result = Constants.SUCCESS;
// long a = new Date().getTime();
// Connection conn = null;
// Session sess = null;
// try {
// if(StringUtils.isNotBlank(hostname)){
// conn = new Connection(hostname);
// conn.connect();
// long b = new Date().getTime();
// logger.debug("SSHConnect----链接ip耗时" + (b - a) + "毫秒," + (b - a)
// / 1000 + "秒");
// boolean isAuthenticated = conn.authenticateWithPassword(username,
// password);
// if (isAuthenticated == true) {
// sess = conn.openSession();
// sess.execCommand("date");
// InputStream stdout = new StreamGobbler(sess.getStdout());
// BufferedReader stdoutReader = new BufferedReader(
// new InputStreamReader(stdout, Charset.forName("utf-8")));
// while (true) {
// String line = stdoutReader.readLine();
// if (line == null){
// break;
// }
// }
// }
// long c = new Date().getTime();
// logger.debug("SSHConnect----测试完成,总耗时:" + (c - a) + "毫秒," + (c - a)/1000 + "秒");
// }
// } catch (IOException e) {
// long d = new Date().getTime();
// logger.error("SSHConnect----连接异常,耗时:" + (d - a) + "毫秒," + (d - a)
// / 1000 + "秒", e);
// if(e.getMessage().contains("Authentication")){
// result = "SSH 登录用户名或密码错误";
// }else {
// result = "SSH 连接失败";
// }
// } catch (Exception e1) {
// long e = new Date().getTime();
// logger.error("SSHConnect----连接异常,耗时:" + (e - a) + "毫秒," + (e - a)
// / 1000 + "秒", e1);
// result = "SSH 连接失败";
// }finally {
// if(conn!=null){
// conn.close();
// }
// if(sess!=null){
// sess.close();
// }
// }
// return result;
// }
// public static void main(String[] args) {
/*
* try {
*
* Future<?> future = null; long start = System.currentTimeMillis();
* future = Common.service.submit(new
* DataCollectThread("数据收集执行线程","10.0.6.234"
* ,Constants.SSL_CLIENT_PORT,true));
* System.out.println("done1:"+future.isDone());
*
* // System.out.println("new:"+new
* DataCollectThread("数据收集执行线程","10.0.6.102"
* ,Constants.SSL_CLIENT_PORT,true).toDo()); // Thread.sleep(3000); //
* System.out.println("done2:"+future.isDone());
* System.out.println("get:"+future.get());
* System.out.println("done3:"+future
* .isDone()+"="+(System.currentTimeMillis()-start));
*
* try { future.get(Constants.MISSION_UPGRADE_DAILY, TimeUnit.SECONDS);
* } catch (Exception e) { // logger.error("DC清理数据超时 缓存数据存入硬盘", e); }
*
*
* // new
* DataCollectThread("数据收集执行线程","10.0.6.113",Constants.SSL_CLIENT_PORT
* ,true).call(); } catch (Exception e) { // TODO Auto-generated catch
* block e.printStackTrace(); }
*/
// }
}

View File

@@ -0,0 +1,251 @@
package com.nms.server.thread.dataCollect;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.nms.server.bean.DetectInfo;
import com.nms.server.bean.NodeModel;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.CommonService;
import com.nms.server.thread.monitor.util.MonitorUtil;
import com.nms.server.thread.socket.SocketCMD;
import com.nms.server.util.BoneCPPool;
import com.nms.server.util.DateUtil;
//监测数据主动收集管理线程
public class NoDetectDataCollectManagerThread implements Runnable{
private Logger logger = Logger.getLogger(NoDetectDataCollectManagerThread.class);
private long startTime = Calendar.getInstance().getTimeInMillis();
public void run() {
// Thread.currentThread().setName("无监测数据节点 数据(监测数据、任务结果、回传文件)收集管理线程");
Thread.currentThread().setName("No Monitoring Data Node Data (Monitoring data, Task results, Return files) Collect Management Threads");
CommonDao dao = null;
try {
dao = new CommonDao();
CommonService service = new CommonService(dao);
//- 非升级操作判断
if(Common.SERVER_UN_UPGRADE_FLAG && Common.noDetectDataNodeList.size()>0){
//循环向自己管辖的Client端收集数据
List<String> ipList = new LinkedList<String>();
ipList = service.getAllComputerIp();//当前DC管理范围内+有效节点+有效节点组+服务器节点
/*
* 2013-7-29 hyx
* 获得所有握手监测的节点信息若数据收集的节点在握手监测节点范围内则收集数据的同时进行握手监测传递true确认一个从握手监测中删除一个节点最后未握手的节点则不在数据收集范围内这种情况不应该存在
*/
Map<String,SetInfo> nodeMap = getNmsclientNodeList(service);//ip:setinfo
//20160901 hyx 增加此代码的原因是数据收集管理线程运行一段时间后会出现获取数据库连接一直阻塞的情况而此时其它线程是可以正常获取数据库连接的一个原因可能是之前没有dao=null另一个原因可能是之后的数据收集及超时操作可能由于各种原因如异常节点较多导致连接最后没能正常关闭所以在连接不使用的时候尽早关闭
try {
if(dao!=null){
dao.close();
dao=null;
}
} catch (Exception e)
{
logger.error("Data collection management thread early closing database connection exception", e);
}
List<String> list = Common.pingHandshake(Common.noDetectDataNodeList);
String stateInfo = "";
String failStartTime = "";
String failEndTime = "";
int ipSize = Common.noDetectDataNodeList.size();
for(int i=0;i<ipSize;i++){
String ip = Common.noDetectDataNodeList.get(i);
logger.debug("ip:"+ip+" i="+i);
if(!ipList.contains(ip)){
Common.noDetectDataNodeList.remove(ip);//判断当前ip是否在dc管辖范围内如果不在就删除
i--;
ipSize--;
continue;
}
if(nodeMap.get(ip)==null){continue;}//不需要握手的节点不用产生监测数据
failStartTime = Calendar.getInstance().getTimeInMillis()+ "";
DetectInfo detectInfo = new DetectInfo();
if(!list.contains(ip)){ //ping不成功的节点 网络异常
// stateInfo = "网络异常";
// stateInfo = "Network Exception";
stateInfo = "i18n_server.NoDetectDataCollectManagerThread.network_n81i";
logger.info("ip "+ip+" 异常信息:网络异常");
}else{//ping成功的节点 进行ssh
String sshResult = Constants.SUCCESS;
if(1==Constants.FLAG_HANDWALK_SSH){
String[] userPwdInfo = Common.getIpUserPwdMap().get(ip);
if (userPwdInfo!=null &&
userPwdInfo.length>=3 && "1".equals(userPwdInfo[2])) {//应该判断nc的操作系统不是dc的,1:linux; 2:windows; 3:other
sshResult = Common.sshConnect(ip,userPwdInfo[0],userPwdInfo[1]);
}
}
if(Constants.SUCCESS.equals(sshResult)){
//ping和ssh都成功
logger.debug("ip "+ip+"恢复正常,从异常节点列表中删除");
Common.noDetectDataNodeList.remove(ip);
i--;
ipSize--;
// stateInfo = "开始" + DateUtil.getStringByLong(startTime)+" NMSClient握手" + DateUtil.getCurrentTime() + " 失败 ";
// stateInfo = "Start" + DateUtil.getStringByLong(startTime)+" NMSClient Shakehand" + DateUtil.getCurrentTime() + " failed";
stateInfo = "i18n_server.NoDetectDataCollectManagerThread.start_n81i" + DateUtil.getStringByLong(startTime)+" i18n_server.NoDetectDataCollectManagerThread.shakehand_n81i" + DateUtil.getCurrentTime() + " i18n_server.NoDetectDataCollectManagerThread.faild_n81i";
}else{
logger.debug("ip "+ip+" 异常信息:"+sshResult);
stateInfo = sshResult;
}
failEndTime = Calendar.getInstance().getTimeInMillis()+ "";
StringBuffer detailInfo = new StringBuffer();
detailInfo.append(SocketCMD.CLIENT_REQ_HAND_SHAKE);// 发送信息
detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
detailInfo.append("");// 返回信息
detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
detailInfo.append("1");// 是否可达,0:可达1不可达
detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
detailInfo.append(failStartTime);// 发送时间
detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
detailInfo.append(failEndTime);// 返回时间
detailInfo.append(MonitorUtil.SEPARATOR);// 分隔符
detailInfo.append(DateUtil.getSecondsFromBeinToEnd(new Date(
Long.parseLong(failStartTime)).getTime(), new Date(Long
.parseLong(failEndTime)).getTime())+ "");// 延迟时间
detectInfo.getDetailDatas().add(detailInfo.toString());
}
detectInfo.setDescInfo(stateInfo);
Common.createNmsClientDetectData(nodeMap.get(ip),ip,detectInfo, startTime);//生成监测数据信息
}
}
} catch (Exception e) {
logger.error("Monitoring data collection management threads run abnormity",e);
} finally {
if(dao!=null){
dao.close();
dao=null;
}
logger.debug("执行结束");
}
}
//获得进行握手监测的所有节点:握手的条件:到首次监测时间+节点有效(节点组有效)+监测设置内的节点+监测设置有效
private Map<String,SetInfo> getNmsclientNodeList(CommonService service){
List<NodeModel> nodeList = new ArrayList<NodeModel>();
Map<String,SetInfo> nodeMap = new HashMap<String,SetInfo>();
try
{
if(Constants.FLAG_NMSC==1){
List<SetInfo> setList = service.getDrivingSetInfo(Constants.DETEC_NMSC_STR);//获得checkType类型的所有监测设置
if(setList!=null && setList.size()>0){
List<NodeModel> nodeTmpList = new ArrayList<NodeModel>();
for (Iterator setIte = setList.iterator(); setIte.hasNext();) {
SetInfo setInfo = (SetInfo) setIte.next();
//如果首次监测时间没到,则不用查询节点
//- 计算启动后第一次检测时间 默认即时启动
long initialDelay = 0l;
if(setInfo.getPlanCheckTime()!=null){
initialDelay = setInfo.getPlanCheckTime().longValue() - (new Date().getTime());
initialDelay = initialDelay > 0l ? initialDelay : 0l;
}
if(initialDelay<=0) {//到首次监测时间了,查询进行握手监测的节点
//节点可能存在重复的情况
nodeTmpList = service.getNodeModelListBySetInfo(setInfo);
nodeList.addAll(nodeTmpList);
}else {
logger.info("握手监测,未到首次监测时间,距离首次监测时间还有:"+initialDelay/1000/60+"分钟");
}
for(NodeModel node:nodeTmpList) {
nodeMap.put(node.getNodeIp(), setInfo);
}
}
logger.debug("本次服务器握手监测的节点数为:"+nodeMap.size());
}
}else {
logger.info("未开启握手监测标识");
}
} catch (Exception e)
{
logger.error("Obtaining a node exception for handshake monitoring", e);
}
return nodeMap;
}
public static void main(String[] args) throws Exception {
CommonDao dao = null;
ScheduledFuture<?> future = null;
Object rlt = null;
try
{
Thread.sleep(3000);
BoneCPPool.initPool();
Thread.sleep(3000);
// DataCollectManagerThread runThread = new DataCollectManagerThread();
// Thread thread = new Thread(runThread);
// thread.start();
dao = new CommonDao();
CommonService service = new CommonService(dao);
// 初始化自身信息(失败情况下会由Web唤醒)
if(!service.initServerParams()){
return;
}
future = Common.scheduled.scheduleWithFixedDelay(new NoDetectDataCollectManagerThread(), 0, 300, TimeUnit.SECONDS);
Common.registRunnable(Constants.DATA_COLLECT_MANAGER, future);
Thread.sleep(7000);
System.out.println(future==null?"null3":future.isDone());
System.out.println(future==null?"null4":future.isCancelled());
System.out.println("***************=====结束了?");
rlt = future.get();
Thread.sleep(5000);
// future.cancel(true);
//发生异常未捕捉后:
System.out.println("future="+future);
System.out.println(future==null?"null55":future.isDone());
System.out.println(future==null?"null55":future.isCancelled());
System.out.println("==============结束了55");
System.out.println("rlt="+rlt);
} catch (Exception e)
{
System.out.println("catch*******************");
System.out.println("eeeeeeeefuture="+future);
System.out.println(future==null?"eeeeeeeeenull55":future.isDone());
System.out.println(future==null?"eeeeeeeeeenull55":future.isCancelled());
System.out.println("eeeeeeeeee==============结束了55");
System.out.println("eeeeeeeerlt="+rlt);
System.out.println("数据收集线程是否注册-catch-done"+Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER).isDone());
System.out.println("数据收集线程是否注册-catch-cancel"+Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER).isCancelled());
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(dao!=null){
dao.close();
dao=null;
}
System.out.println("finally**********************************");
// Common.scheduled.shutdown();//关闭线程池
// System.out.println(Common.scheduled.isTerminated());//?????????
// System.out.println(Common.scheduled.isShutdown());
System.out.println("数据收集线程是否注册-catch-done"+Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER).isDone());
System.out.println("数据收集线程是否注册-catch-cancel"+Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER).isCancelled());
// System.out.println("关闭线程池");
}
}
}

View File

@@ -0,0 +1,107 @@
package com.nms.server.thread.dataCollect;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.CommonService;
import com.nms.server.util.ExceptionPrintUtils;
//主动收集任务(执行完成,但无结果的任务)结果管理线程
public class NonRltTaskResultCollectManagerThread implements Runnable{
private Logger logger = Logger.getLogger(NonRltTaskResultCollectManagerThread.class);
public void run() {
CommonDao dao = null;
try {
// Thread.currentThread().setName("数据(无结果任务的结果数据)收集管理线程");
Thread.currentThread().setName("Data (No result task result data) To Collect Management Thread");
dao = new CommonDao();
CommonService service = new CommonService(dao);
//- 非升级操作判断
if(Common.SERVER_UN_UPGRADE_FLAG){//---起什么作用?
/**
* 向表MISSION_STATE_TABLE中查询MISSION_TYPE任务类型1,4,6IS_LOOP是否为周期任务1是0不是
* 一个任务会有多个节点ip执行任务结果表中一个任务id会有多条seq_id不同什么时候任务结果表里会有对应任务id的结果信息所以从表MISSION_STATE_TABLE开始查
* 按任务类型来:
*/
//需要收集任务结果的列表ip<任务id,>
Map<String,Map<String,String[]>> ipTaskIdsMap = service.getNonRltIpTaskMap();
Iterator ite = ipTaskIdsMap.entrySet().iterator();
int j=0;
String key = "";
while(ite.hasNext()) {
Entry en = (Entry)ite.next();
String ip = en.getKey().toString();
if(ip!=null&&!"".equals(ip.trim())) {
//- 检查线程运行状态 运行中无操作
key = Constants.NONRLTTASK_RESULT_COLLECT+":"+ip;
Future<?> future = Common.getFutureMap().get(key);
if(future != null && !future.isCancelled() && !future.isDone()){ //运行中
logger.info(""+ip+"的任务结果(对于该有结果,而无结果的任务)收集执行线程 运行中 不再启动新收集线程");
continue;
}
Map<String,String[]> taskInfoMap = (Map<String,String[]>)en.getValue();//当前ip上执行成功的任务id
// future = Common.service.submit(new NonRltTaskResultCollectThread("任务结果(对于该有结果,而无结果的任务)收集执行线程",ip,Constants.SSL_CLIENT_PORT,taskInfoMap));
future = Common.service.submit(new NonRltTaskResultCollectThread("Task Result(For tasks that should have results,but not results) Collect Execution Thread",ip,Constants.SSL_CLIENT_PORT,taskInfoMap));
//注册
Common.getFutureMap().put(key, future);
j++;
}
}
logger.info("*******************************************共"+ipTaskIdsMap.size()+"个节点,任务结果(对于该有结果,而无结果的任务)收集执行线程启动个数:"+j);
}
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
} finally{
if(dao!=null){
dao.close();
dao=null;
}
logger.debug("执行结束");
}
}
public static void main(String[] args) {
try
{
// new InitServerThread().initCommonInfo(new CommonDao());
// NonRltTaskResultCollectManagerThread runThread = new NonRltTaskResultCollectManagerThread();
// Thread thread = new Thread(runThread);
// thread.start();
//
// Thread.sleep(10000);
//
// MissionResultThread mrt = new MissionResultThread("rlt");
// mrt.run();
// Map<String,String> m = new HashMap<String,String>();
//// String key = "";
// for(int i=0;i<6;i++) {
// String key="i="+i;
// m.put(key, ":"+i);
// }
//
// Iterator i = m.keySet().iterator();
// while(i.hasNext()) {
// String e = (String)i.next();
// System.out.println("key="+e.toString()+",value="+m.get(e).toString());
// }
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,156 @@
package com.nms.server.thread.dataCollect;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.MissionResult2;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.thread.socket.SocketCMD;
import com.nms.server.util.DateUtil;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.socket.SSLSocketCallable;
/**
* 任务(对于该有结果,而无结果的任务)结果收集线程
* DC发送要收集的命令
* Agent端发送任务结果
*
* @author hyx
*
*/
public class NonRltTaskResultCollectThread extends SSLSocketCallable {
Logger logger = Logger.getLogger(NonRltTaskResultCollectThread.class);
private String name; // 自定义Thread Name
private Map<String,String[]> taskInfoMap;//需要收集结果的任务id
public NonRltTaskResultCollectThread(String name,String ip,Integer port,Map<String,String[]> taskInfoMap) throws Exception {
super(ip,port);
this.name = name;
this.taskInfoMap = taskInfoMap;
}
/**与Client端进行通信SSLSocketCallable已经握手过了
* 收集监测数据、任务结果、回传文件
*/
@Override
protected Object toDo() throws Exception
{
// 为当前线程命名 ,用与开发阶段友好输出。
Thread.currentThread().setName(name);
// int zipTaskResult = 0;
// int objTaskResult = 0;
try {
// //设置超时时间
socket.setSoTimeout(100*1000);//如果放到String msg0 = receiveMessage();下面会报错socket closed
//进行通信:SSLSocketCallable已经建立握手了
sendMessage(SocketCMD.REQ_NONRLTTASK_RESULT_COLLECT);//DC要进行任务结果收集
String msg0 = receiveMessage();
logger.info("任务对于该有结果而无结果的任务结果收集client端"+this.ip+"回应信息:"+msg0);
if(SUCCESS.equalsIgnoreCase(msg0)) {
Iterator taskInfoIte = taskInfoMap.entrySet().iterator();
while(taskInfoIte.hasNext()) {
Entry enTask = (Entry)taskInfoIte.next();
if(enTask!=null && enTask.getKey()!=null) {
String taskId = enTask.getKey().toString();
String[] taskInfo = (String[])enTask.getValue();
if(StringUtils.isNotBlank(taskInfo[2])) {
logger.info("startTime="+taskInfo[2]);
Long timeTmp=null;
if(NumberUtils.isDigits(taskInfo[2])){
timeTmp = Long.parseLong(taskInfo[2]);
}else{
timeTmp = DateUtil.toLongTime(taskInfo[2]);
}
taskInfo[2] = timeTmp==null?null:timeTmp.toString();
}
if(StringUtils.isNotBlank(taskInfo[3])) {
logger.info("endTime="+taskInfo[3]);
Long timeTmp3=null;
if(NumberUtils.isDigits(taskInfo[2])){
timeTmp3 = Long.parseLong(taskInfo[2]);
}else{
timeTmp3 = DateUtil.toLongTime(taskInfo[2]);
}
taskInfo[3] = timeTmp3==null?null:timeTmp3.toString();
}
String taskInfoStr = taskId+Constants.COMMON_DATA_POINT+
taskInfo[0]+Constants.COMMON_DATA_POINT+
taskInfo[1]+Constants.COMMON_DATA_POINT+
(taskInfo[2]==null?"":taskInfo[2])+Constants.COMMON_DATA_POINT+//与NC协商好的用""
(taskInfo[3]==null?"":taskInfo[3]);
// System.out.println("向NC端发送的任务信息"+taskInfoStr);
logger.info("DC向NC("+this.ip+")端发送的任务信息:"+taskInfoStr);
this.sendMessage(taskInfoStr);
msg0 = receiveMessage();
if(StringUtils.isNotBlank(msg0)) {
// System.out.println("NC端发送的结果信息"+msg0);
logger.info("NC("+this.ip+")向DC端发送的结果信息:"+msg0);
String [] result = msg0.split(Constants.COMMON_DATA_SPLIT);
// logger.info("参数个数:"+result.length);
// logger.info("结果:"+result[0]);
if("1".equals(result[0])) {//如果失败,则将结果存入缓存列表,等待下次入库
MissionResult2 result2 = new MissionResult2();
result2.setMissionId(taskId==null?null:Long.parseLong(taskId));
result2.setResult(1l);//不属于人工判定失败
result2.setDescription(result[1]);
result2.setStartTime(taskInfo[2]==null?null:Long.parseLong(taskInfo[2]));
result2.setEndTime(taskInfo[3]==null?null:Long.parseLong(taskInfo[3]));
result2.setLoopFlag(taskInfo[1]==null?null:Long.parseLong(taskInfo[1]));
result2.setMissionType(taskInfo[0]==null?null:Long.parseLong(taskInfo[0]));
result2.setUuid(Common.getIpSeqIdMap().get(ip));
Common.addResultToResultList(result2);
logger.info("存入缓存一条失败结果NC("+this.ip+")端无任务"+taskId+"对应的结果,人工产生一条失败结果)");
}
}
}
}
sendMessage(SocketCMD.COMMUNICATION_END);
}
logger.info("任务结果收集执行线程与client端"+this.ip+"的通信结束");
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}
return null;
}
public static void main(String[] args) {
try
{
// new NonRltTaskResultCollectThread("数据收集执行线程","10.0.6.120",Constants.SSL_CLIENT_PORT,"1274605").call();
//只处理绝对路径
ResourceBundle log4jRb = ResourceBundle.getBundle("log4j");
String logFile = log4jRb.getString("log4j.appender.logfile.File");
File f = new File(logFile);
if(f!=null&&f.isAbsolute()) {
String logPath = f.getParent();
System.out.println(logPath);
}
// System.out.println(f.getParent());//1.null 2.\* 3*
// System.out.println(f.isAbsolute());//1.null 2.\* 3*
// System.out.println(f.getParentFile().isDirectory());//1.null 2.\* 3*
// System.out.println(f.getParentFile().getAbsolutePath());
// String webPathTmp = NonRl/buildPath(webPathTmp.substring(1,webPathTmp.length()-16));
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,38 @@
package com.nms.server.thread.deleteFiles;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.ExceptionPrintUtils;
//监测数据主动收集管理线程
public class DeleteFilesManagerThread implements Runnable{
private Logger logger = Logger.getLogger(DeleteFilesManagerThread.class);
public void run() {
try {
// Thread.currentThread().setName("定时删除文件(log、error->detect、download)管理线程");
Thread.currentThread().setName("Regularly Delete Files (log, error->detect, download) Management Thread");
Future<?> future = Common.getFutureMap().get(Constants.DELETE_TMP_FILES);
if(future != null && !future.isCancelled() && !future.isDone()){ //运行中
logger.info("定时删除文件(log、error->detect、download)执行线程 运行中 不再启动新删除线程");
return;
}
future = Common.service.submit(new DeleteFilesThread());
//注册
Common.getFutureMap().put(Constants.DELETE_TMP_FILES, future);
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}
}
public static void main(String[] args) {
}
}

View File

@@ -0,0 +1,148 @@
package com.nms.server.thread.deleteFiles;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.ResourceBundle;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.common.Constants;
import com.nms.server.util.FileUtils;
/**
* 定时删除指定文件
* 2013-3-14 hyx
*/
public class DeleteFilesThread implements Runnable{
private Logger logger = Logger.getLogger(DeleteFilesThread.class);
@Override
public void run() {
Thread.currentThread().setName("Regularly Delete Files (log, error->detect, download) Thread");
try {
//删除日志文件:只处理绝对路径
ResourceBundle log4jRb = ResourceBundle.getBundle("log4j");
String logFileStr = null;
try {
logFileStr = log4jRb.getString("log4j.appender.logfile.File");
} catch (Exception e) {
logger.info("未找到 旧格式日志文件路径 跳过旧格式日志删除");
}
if(StringUtils.isNotBlank(logFileStr)){
File logFile = new File(logFileStr);
if(logFile!=null&&logFile.isAbsolute()) {
String logPath = logFile.getParent();
File tmpFiles = new File(logPath);
if(tmpFiles!=null&&tmpFiles.isAbsolute()&&tmpFiles.isDirectory()) {
logger.info("删除日志文件开始");
int delLogFilesNum = deleteFilesFrom(logPath,"日志");
logger.info("删除日志文件结束,共删除"+delLogFilesNum+"个文件");
}
}
}
//删除download里的文件
String downloadPath = Constants.MISSION_FILE_DOWNLOAD_DIR;
if(StringUtils.isNotBlank(downloadPath)) {
logger.info("删除download文件开始");
int delDownloadFilesNum = deleteFilesFrom(downloadPath,"download");
logger.info("删除download文件结束共删除"+delDownloadFilesNum+"个文件");
}
//删除error里的detect里的文件按文件名进行删除
String detectPath = Constants.ERROR_DETEC_FILE_DIR;
if(StringUtils.isNotBlank(detectPath)) {
logger.info("删除detect文件开始");
int delDetectFilesNum = deleteFilesFromByFileName(detectPath,"detect");
logger.info("删除detect文件结束共删除"+delDetectFilesNum+"个文件夹");
}
} catch (Exception e) {
logger.error("Regularly delete files (log, error->detect, download) exceptions",e);
}
}
//pathNam要删除的文件所在的路径
private int deleteFilesFrom(String pathName,String tip) throws Exception{
File tmpFiles = new File(pathName);
int deleteFileNum = 0;
if(tmpFiles!=null&&tmpFiles.isAbsolute()&&tmpFiles.isDirectory()) {
logger.info(tip+"文件所在路径:"+pathName);
if(tmpFiles.exists()) {
// File[] filesTmp = FileUtils.listAllFilesEndWith(logFiles, "txt");
File[] filesTmp = tmpFiles.listFiles();
if(filesTmp!=null&&filesTmp.length>0) {
Date now = new Date();
Calendar nowCal = Calendar.getInstance();
nowCal.setTime(now);
nowCal.set(Calendar.HOUR, nowCal.get(Calendar.HOUR)-Constants.KEEP_FILE_DAYS*24);
// nowCal.set(Calendar.MINUTE, nowCal.get(Calendar.MINUTE)-1);//测试时使用
for(File f:filesTmp) {
Calendar lastModifyTime = FileUtils.getModifiedTime(f);
if(nowCal.compareTo(lastModifyTime)>0) {
// boolean isDel = f.delete();//删除文件夹时,文件夹必须是空的才可以
FileUtils.deleteAllFiles(f,true);
// if(isDel) {
deleteFileNum++;
// }
}
}
}
}
}
return deleteFileNum;
}
private int deleteFilesFromByFileName(String pathName,String tip) throws Exception{
File tmpFiles = new File(pathName);
int deleteFileNum = 0;
if(tmpFiles!=null&&tmpFiles.isAbsolute()&&tmpFiles.isDirectory()) {
logger.info(tip+"文件所在路径:"+pathName);
if(tmpFiles.exists()) {
// File[] filesTmp = FileUtils.listAllFilesEndWith(logFiles, "txt");
File[] filesTmp = tmpFiles.listFiles();
if(filesTmp!=null&&filesTmp.length>0) {
Date now = new Date();
Calendar nowCal = Calendar.getInstance();
nowCal.setTime(now);
nowCal.set(Calendar.HOUR, nowCal.get(Calendar.HOUR)-Constants.KEEP_FILE_DAYS*24);
// nowCal.set(Calendar.MINUTE, nowCal.get(Calendar.MINUTE)-5);//测试时使用
for(File f:filesTmp) {
// Calendar lastModifyTime = FileUtils.getModifiedTime(f);
String fileName = f.getName();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
try
{
Date date = format.parse(fileName);
Calendar lastModifyTime = Calendar.getInstance();
lastModifyTime.setTime(date);
if(nowCal.compareTo(lastModifyTime)>0) {
FileUtils.deleteAllFiles(f,true);//删除文件夹时,文件夹必须是空的才可以
deleteFileNum++;
}
} catch (ParseException e)
{
logger.info("删除 detect文件时解析"+pathName+"路径下的文件夹名称,转换为日期形式 异常");
}
}
}
}
}
return deleteFileNum;
}
public static void main(String [] args){
new Thread(new DeleteFilesThread()).start();
}
}

View File

@@ -0,0 +1,170 @@
package com.nms.server.thread.detecData;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.FileUtils;
public class DetecDataResoveManagerThread implements Runnable {
private Logger logger = Logger.getLogger(DetecDataResoveManagerThread.class);
private int testNum = 0;// 尝试运行线程Constants.DETEC_DATA_RESOVE的次数
public void run() {
// 将线程运行程序尽可能的catch捕获异常
// Thread.currentThread().setName("监测数据解析管理线程");
Thread.currentThread().setName("Monitoring Data Parsing Management Thread");
try {
// 如果内存中监测数据列表的数据超过指定值则将数据存入硬盘10万
int detectDataNum = Common.getAllDeteDataNum();
if (detectDataNum >= Constants.MAX_DETECT_DATA_RESOVE_LIMIT_NUM) {
logger.warn("Excesive monitoring data"+detectDataNum+"pieces data written to the hard disk");
saveDetectDataToDisk();
return;
}
// dc监测数据入库模式1由web 主控控制入库2自己主动入库3智能模式1和2结合4写入文件定时上传web端
if (Constants.DETECT_INSERT_MODE == 1) {
logger.debug("DETECT_INSERT_MODE = " + Constants.DETECT_INSERT_MODE + ",不启动监测数据入库线程");
return;
} else if (Constants.DETECT_INSERT_MODE == 2) {
// 2自己主动入库
logger.debug("DETECT_INSERT_MODE = " + Constants.DETECT_INSERT_MODE + ",主动入库");
modeTwo();
} else if (Constants.DETECT_INSERT_MODE == 3) {
// 3智能模式1和2结合
long last = Common.getLastWebHandshake();
long n = System.currentTimeMillis();
if((n-last)/Constants.WEB_NOTICE_INSERT_DETECT_OVER_TIMES > Constants.DETEC_DATA_RESOLVE_PERIOD*1000){
//超过两个监测周期都没有 web 握手信息
logger.debug("超过两个周期都没有web握手信息dc 主动入库,lastTime : " + new Date(last).toLocaleString());
modeTwo();
}else{
logger.debug("等待web 通知监测数据入库lastTime : " + new Date(last).toLocaleString());
}
} else if (Constants.DETECT_INSERT_MODE == 4) {
// 4写入文件定时上传web端暂不实现
}
} catch (Exception e) {
logger.error("", e);
} finally {
logger.debug("执行结束");
}
}
/**
* mode 2 自己主动入库,查询 数据库 server_table 表共多少有效 dc ,根据自己排序,监测入库周期时间,计算
* 在哪一个时间段入库
*/
public void modeTwo() {
// 测试数据库连接
boolean runFlag = Common.isDbConnected();
// - 检查线程运行状态 运行中无操作
Future<?> future = Common.getFutureMap().get(Constants.DETEC_DATA_RESOVE);
if (future != null && !future.isCancelled() && !future.isDone() && runFlag) { // 运行中
runFlag = false;
logger.info("监测数据解析执行线程 运行中 不再启动新解析线程");
}
/*
* 连续超过Constants.CHECK_WARNING_DATA_OVERRUN次数时将数据存入硬盘中 否则 正常执行数据解析线程
*/
if (!runFlag) { // 判断并结束线程
testNum = (testNum % Constants.CHECK_DETEC_DATA_OVERRUN);
testNum++;
if (testNum == Constants.CHECK_DETEC_DATA_OVERRUN) {
if (Constants.FLAG_DETECT_DATA_SAVE_DISK_RESOVE == 1) {
/*
* 连续多个周期仍未解析完成 说明list里存有大量的数据则先将当前未解析的数据列表存入硬盘
* 然后停掉解析线程,将正在解析的数据列表中的剩余数据存入硬盘
*/
logger.warn("Failed to create database connection,data written to hard disk");
saveDetectDataToDisk();
}
}
return;
} else { // 重置计数器 程序继续执行
testNum = 1;
}
// - 非升级操作判断
if (Common.SERVER_UN_UPGRADE_FLAG) {
// - 为空或空闲中 变更存储区 启动新解析线程
// Common.chengeDeteDataFlag(); //变更数据存放集合
// 2018年6月14日11:04:57 根据集合的大小自动切换取缓存数据最多的
LinkedList<byte[]> dsbList = Common.getDeteDataList(); // 获取非存放状态的数据集合
if (dsbList != null && dsbList.size() > 0) {
logger.info("监测数据解析执行线程 空闲中 启动新解析线程");
// -- 获取线程执行 需进行主动告警和邮件通知等相关操作,待考虑
future = Common.dataResoveService.submit(new NewDetecDataResoveThread("Monitoring Data Parse Perform Thread",dsbList));
// 注册
Common.getFutureMap().put(Constants.DETEC_DATA_RESOVE, future);
} else {
logger.info("获取到的集合中数据数量为0无需启动解析线程");
}
}
}
// 2013-2-19 hyx :当监测数据量过大时,将数据先存放到硬盘,再定时入库(由单独的定时线程实现)
public void saveDetectDataToDisk() {
LinkedList<byte[]> notResolvingDetectDataList = Common.getNotResovlingDeteDataList(); // 获取未在解析的监测数据集合
try {
// 终止正在解析监测数据的线程并将正在解析的list里未解析的数据存入硬盘
Future<?> future = Common.getFutureMap().get(Constants.DETEC_DATA_RESOVE);
if (future != null && !future.isCancelled() && !future.isDone()) { // 运行中
future.cancel(true);
}
LinkedList<byte[]> detectDataList = Common.getDeteDataList(); // 获取非存放状态的数据集合(正在解析的list)
saveByteToFile(detectDataList);
// 将未在解析的list存放到硬盘上
saveByteToFile(notResolvingDetectDataList);
} catch (IndexOutOfBoundsException e) {
logger.error("When there is too much monitoring data ,the data is stored on the hard disk exception",e);
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}
}
private void saveByteToFile(LinkedList<byte[]> dataList) {
String filePath = "";
int dataSize = dataList.size();// 如果不按此时的size来操作则list里的数据可能会一直在增加就会一直循环下去
logger.info("监测数据过多,共" + dataSize + "条监测数据,等待存入硬盘:" + Constants.OVERRUN_DETEC_FILE_DIR + "/"
+ Common.getDateDirName() + "/");
try {
for (int j = 0; j < dataSize; j++) {
if (dataList.size() > 0) {
byte[] data = dataList.get(0);// 因为每次循环都会dataList.remove(0);所以每次操作的都是第0条记录
filePath = Constants.OVERRUN_DETEC_FILE_DIR + "/" + Common.getDateDirName() + "/"
+ Calendar.getInstance().getTimeInMillis() + "_" + j + ".csv";
FileUtils.wirteBytesToFile(data, filePath);
dataList.remove(0);
}
}
} catch (Exception e) {
logger.error("When there is too much monitoring data ,the data is stored on the hard disk exception",e);
}
}
public static void main(String[] args) {
Common.scheduled.scheduleAtFixedRate(new DetecDataResoveManagerThread(), 0, 50, TimeUnit.SECONDS);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(0);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,51 @@
package com.nms.server.thread.detectDataHandler;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.LinkedBlockingDeque;
import org.apache.log4j.Logger;
import com.nms.server.bean.DetectInfo;
import com.nms.server.common.Common;
public class DataInsertManagerThread implements Runnable{
private static final Logger logger = Logger.getLogger(DataInsertManagerThread.class);
@Override
@SuppressWarnings("rawtypes")
public void run() {
Thread.currentThread().setName("DataInsertManagerThread");
try {
//遍历 监测数据等待入库 table
Hashtable<String, LinkedBlockingDeque> hb = Common.DETECT_QUEUE;
Set<Entry<String, LinkedBlockingDeque>> es = hb.entrySet();
Iterator<Entry<String, LinkedBlockingDeque>> ite = es.iterator();
while(ite.hasNext() && ! Common.isStop() && ! Thread.currentThread().isInterrupted() ){
Entry<String, LinkedBlockingDeque> next = ite.next();
String key = next.getKey();
if(DetectInfo.INFO_KEY.equalsIgnoreCase(key)){
//info 表的数据此线程不做解析
continue;
}
LinkedBlockingDeque<Map<String,String>> data = next.getValue();
List<Map<String,String>> list = new LinkedList<>();
int total = data.drainTo(list);
if(total > 0){
Common.dataResoveService.submit(new DetectDetailInsertThread(key, list));
logger.info(key +"->" + total);
}else{
logger.info(key + " 没有监测详细数据");
}
}
} catch (Exception e) {
logger.error("DataInsertManagerThread error",e);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,220 @@
package com.nms.server.thread.detectDataHandler;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.fang.U;
import com.fang.lang.Db;
import com.fang.lang.StopWatch;
import com.nms.server.bean.DetectInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.DateUtil;
/**
* 监测详细数据入库线程
* @author dell
*
*/
@SuppressWarnings("all")
public class DetectDetailInsertThread implements Runnable{
private static final Logger logger = Logger.getLogger(DetectDetailInsertThread.class);
private static Db db = Common.getDb();
private StopWatch sw = null;
private Connection conn = null;
private String key;
private List<Map<String,String>> data;
public DetectDetailInsertThread(String key,List<Map<String,String>> data) {
this.key = key;
this.data = data;
}
@Override
public void run() {
Thread.currentThread().setName("DetectDetailInsertThread-"+key);
logger.info("开始运行->" + key);
sw = U.StopWatch.newStopWacth();
sw.start();//开始计时
try {
conn = db.getConnection();
saveData(key,data);
//遍历 监测数据等待入库 table
/*Hashtable<String, Queue> hb = Common.DETECT_QUEUE;
Set<Entry<String, Queue>> es = hb.entrySet();
Iterator<Entry<String, Queue>> ite = es.iterator();
while(ite.hasNext() && ! Common.isStop() && ! Thread.currentThread().isInterrupted() ){
Entry<String, Queue> next = ite.next();
String key = next.getKey();
if(DetectInfo.INFO_KEY.equalsIgnoreCase(key)){
//info 表的数据此线程不做解析
continue;
}
Queue<Map<String,String>> data = next.getValue();
saveData(key,data);
}*/
sw.end();
} catch (Exception e) {
logger.error("",e);
} finally {
db.closeQuiet(conn);
}
logger.info(key+ " 监测数据详细信息解析入库,耗时: " + U.StopWatch.toString(sw.total()));
logger.info("结束运行->" + key);
sw = null;
}
/**
* 保存详细监测数据
* @param data
*/
public void saveData(String checkType ,List<Map<String,String>> data){
logger.info("监测类别:" + checkType +" 开始入库");
sw.tag(checkType + "-start");
int count = 0;
PreparedStatement stmt = null;
try {
Map<String,String> ele = null;
//详细信息对应的表名
String detailTableName = null;
if(DetectInfo.NET_STR_KEY.equalsIgnoreCase(checkType)){
//系统信息-网卡信息
detailTableName = "di_systeminfo_net";
}else if(DetectInfo.DISK_STR_KEY.equalsIgnoreCase(checkType)){
//系统信息-磁盘信息
detailTableName = "di_systeminfo_disk";
}else{
detailTableName = Common.getInsertTable().get(checkType) == null ? null : Common.getInsertTable().get(checkType).getTableName();
}
if(detailTableName == null){
logger.error(checkType + " the corresponding detailed table was not found and the data could not be stored");
return;
}
List<Object[]> params = new LinkedList<Object[]>();//等待批处理参数
List<String> fieldNames = new ArrayList<String>();//保存监测数据的字段
String sql = null;//insert sql
Iterator<Map<String, String>> ite = data.iterator();
while( ite.hasNext()){
ele = ite.next();
count ++;
if(sql == null){
sql = DetectInfo.createDetailSql(fieldNames, detailTableName, ele);
stmt = conn.prepareStatement(sql);
}
//计算 详细表的 外键 时间戳10 + seqId5+ setId (3),主要是为了使用 java 中long 类型
String checkTime = ele.get("DATA_CHECK_TIME_DIGITAL");
String setId = ele.get("DETECTION_SET_INFO_ID");
String seqId = ele.get("SEQ_ID");
String id = DetectInfo.computeId(checkTime, seqId, setId);
ele.put("DETECTION_INFO_ID", id);
Object[] detail = mapToArray(fieldNames, ele);
params.add(detail);
if(count % Constants.BATCH_RESOVE_COUNT == 0){
//保存到数据库
saveToDb(params, checkType, stmt);
params.clear();
}
}
if(params.size() > 0){
//保存到数据库
saveToDb(params, checkType, stmt);
params.clear();
}
} catch (Exception e) {
logger.error("save detect detail error ",e);
}finally {
db.closeQuiet(stmt);
}
sw.tag(checkType + "-end");
logger.info("监测类别: " + checkType + " , 耗时: " + U.StopWatch.toString(sw.between(checkType+"-end",checkType+"-start")) +" ,共 " + count +"");
}
/**
* 保存到数据库
* @param params
* @param checkType
* @param sql
*/
private void saveToDb(List<Object[]> params,String checkType,PreparedStatement stmt){
Object temp=null;
Object[] arrTemp=null;
long n = System.currentTimeMillis();
sw.tag(n+"start");
try {
if (params != null && params.size() >0) {
conn.setAutoCommit(false);
int count=0;
for(Object[] e : params){
arrTemp=e;
logger.debug(" params " + Arrays.toString(e)+"addToBatch "+ ++count);
for (int i = 0; i < e.length; i++) {
Object value = e[i];
temp=value;
if(DateUtil.isDate((String)value, Constants.COMMON_DATE_FORMAT)){
String str_format=(String)value;
Date parse = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT).parse(str_format);
long time = parse.getTime();
Timestamp timestamp = new Timestamp(time);
stmt.setTimestamp(i+1,timestamp);
// stmt.setTimestamp(i+1, new Timestamp(Common.getFormat().parse((String)value).getTime()));
}else{
stmt.setObject(i + 1, value);
}
}
stmt.addBatch();
}
stmt.executeBatch();
conn.commit();
stmt.clearBatch();
}
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e1) {
}
logger.error("",e);
}
sw.tag(n+"end");
logger.info("批量保存,类型 " + checkType + " , 共 " + params.size() +"" + " , 耗时: " + U.StopWatch.toString(sw.between(n+"end",n+"start")));
}
/**
* 将map组织成 数据方便executeBatch
* 下一步(可以直接在解析的时候将数据解析成数组)
* @param fieldNames
* @param data
* @return
*/
private Object[] mapToArray(List<String> fieldNames,Map<String,String> data){
int size = fieldNames.size();
Object[] result = new Object[size];
for(int i = 0;i<size;i++){
String name = fieldNames.get(i);
String value = data.get(name);
result[i] = value;
}
return result;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,49 @@
package com.nms.server.thread.email;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.CommonService;
import com.nms.server.util.BoneCPPool;
import com.nms.server.util.ExceptionPrintUtils;
//监测数据主动收集管理线程
public class RefreshEmailFlagThread implements Runnable{
private Logger logger = Logger.getLogger(RefreshEmailFlagThread.class);
public void run() {
// Thread.currentThread().setName("更新邮件功能是否启用标识 线程");
Thread.currentThread().setName("Updata The Mail Function To Enable Identity Thread ");
CommonDao dao = null;
try {
dao = new CommonDao();
CommonService service = new CommonService(dao);
Constants.flag_email = service.getFlagEmail();//定时的更新邮件发送是否启动标识
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
} finally{
if(dao!=null){
dao.close();
dao=null;
}
logger.debug("执行结束");
}
}
public static void main(String[] args) {
try
{
BoneCPPool.initPool();
Common.scheduled.scheduleWithFixedDelay(new RefreshEmailFlagThread(), 0, 5, TimeUnit.MINUTES);
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,162 @@
package com.nms.server.thread.errorinfo;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.nms.server.bean.NmsErrorInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.FileUtils;
public class ErrorInfoResoveManagerThread implements Runnable{
private Logger logger = Logger.getLogger(ErrorInfoResoveManagerThread.class);
private int testNum = 0;//尝试运行线程Constants.DETEC_DATA_RESOVE的次数
public void run() {
//将线程运行程序尽可能的catch捕获异常
// Thread.currentThread().setName("DC错误信息解析管理线程");
Thread.currentThread().setName("DC Error Message Parsing Management Threads");
try {
boolean runFlag = Common.isDbConnected();//测试数据库连接
//- 检查线程运行状态 运行中无操作
Future<?> future = Common.getFutureMap().get(Constants.ERROR_INFO_RESOVE);
if(future != null && !future.isCancelled() && !future.isDone() && runFlag){ //运行中
runFlag = false;
logger.info("DC错误信息解析执行线程 运行中 不再启动新解析线程");
}
/*
* 连续超过Constants.CHECK_WARNING_DATA_OVERRUN次数时将数据存入硬盘中
* 否则 正常执行数据解析线程
* */
if(!runFlag){ //判断并结束线程
testNum = (testNum%Constants.CHECK_WARNING_DATA_OVERRUN);
testNum++;
if(testNum==Constants.CHECK_WARNING_DATA_OVERRUN) {
if(Constants.FLAG_ERROR_DATA_SAVE_DISK_RESOVE==1) {
/*
* 连续多个周期仍未解析完成
* 说明list里存有大量的数据则先将当前未解析的数据列表存入硬盘
* 然后停掉解析线程,将正在解析的数据列表中的剩余数据存入硬盘
* */
logger.warn("Create a database connection failure and data stored to the hard disk");
saveErrorDataToDisk();
}
}
return;
}else{ //重置计数器 程序继续执行
testNum = 1;
}
//- 非升级操作判断
if(Common.SERVER_UN_UPGRADE_FLAG){
//- 为空或空闲中 变更存储区 启动新解析线程
Common.changeErrorInfoFlag(); //变更数据存放集合
LinkedList<NmsErrorInfo> dsbList = Common.getErrorInfoList(); // 获取非存放状态的数据集合
if(dsbList != null && dsbList.size()>0){
logger.info("DC错误信息解析执行线程 空闲中 启动新解析线程");
//-- 获取线程执行 需进行主动告警和邮件通知等相关操作,待考虑
future = Common.service.submit(new ErrorInfoResoveThread("DC错误信息解析执行线程",dsbList));
//注册
Common.getFutureMap().put(Constants.ERROR_INFO_RESOVE, future);
}else{
logger.info("获取到的集合中数据数量为0无需启动解析线程");
}
}
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}finally{
logger.debug("执行结束");
}
}
/**
* 数据库是否可连接判断
* @time Mar 7, 2013-2:22:42 PM
* @return
*/
public boolean dbTest() {
CommonDao dao = null;
try {
// if(!false)throw new Exception("强制异常");
dao = new CommonDao();
logger.debug("尝试获取数据库连接成功");
return true;
} catch (Exception e) {
logger.error("Try to get a database connection failure", e);
/* 告警 */
return false;
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
////2013-2-19 hyx :当监测数据量过大时,将数据先存放到硬盘,再定时入库(由单独的定时线程实现)
public void saveErrorDataToDisk() {
LinkedList<NmsErrorInfo> notResolvingErrorInfoList = Common.getNotResovlingErrorInfoList(); // 获取未在解析的监测数据集合
try {
//终止正在解析监测数据的线程并将正在解析的list里未解析的数据存入硬盘
Future<?> future = Common.getFutureMap().get(Constants.DETEC_DATA_RESOVE);
if(future != null && !future.isCancelled() && !future.isDone()){ //运行中
future.cancel(true);
}
LinkedList<NmsErrorInfo> detectDataList = Common.getErrorInfoList(); // 获取非存放状态的数据集合(正在解析的list)
saveByteToFile(detectDataList);
//将未在解析的list存放到硬盘上
saveByteToFile(notResolvingErrorInfoList);
}catch(IndexOutOfBoundsException e) {
logger.error("When monitoring data is too much, the data is stored in the hard disk exception",e);
}catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}
}
private void saveByteToFile(LinkedList<NmsErrorInfo> dataList) {
String filePath = "";
int dataSize = dataList.size();//如果不按此时的size来操作则list里的数据可能会一直在增加就会一直循环下去
logger.info("错误数据过多,共"+dataSize+"条错误数据,等待存入硬盘");
try {
for(int j=0;j<dataSize;j++) {
if(dataList.size()>0) {
NmsErrorInfo data= dataList.get(0);//因为每次循环都会dataList.remove(0);所以每次操作的都是第0条记录
filePath = Constants.OVERRUN_DETEC_FILE_DIR+"/"+Common.getDateDirName()+"/"+Calendar.getInstance().getTimeInMillis()+"_"+j+".csv";
// FileUtils.wirteBytesToFile(data, filePath);//此处暂时将错误信息抛弃
logger.info("被抛弃的DC ErrorInfo:"+data.getErrorCode()+"-"+data.getErrortDesc()+"="+data.getErrortGetip()+"="+data.getErrortIp()+"="+data.getErrorTime());
dataList.remove(0);
logger.info("监测数据过多,已保存至"+filePath);
}
}
}catch(Exception e) {
logger.error("When monitoring data is too much, the data is stored in the hard disk exception",e);
}
}
public static void main(String [] args) {
Common.scheduled.scheduleAtFixedRate(new ErrorInfoResoveManagerThread(),0,50,TimeUnit.SECONDS);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(0);
}
}

View File

@@ -0,0 +1,89 @@
package com.nms.server.thread.errorinfo;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import org.apache.log4j.Logger;
import com.nms.server.bean.NmsErrorInfo;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.CommonService;
/**
* CSV解析线程
*
* @author ZGGG3
*
*/
public class ErrorInfoResoveThread implements Callable<Object> {
Logger logger = Logger.getLogger(ErrorInfoResoveThread.class);
volatile boolean stop = false;//线程是否被取消标志
private String name; // 自定义Thread Name
private LinkedList<NmsErrorInfo> dsbList;
public ErrorInfoResoveThread(String name,LinkedList<NmsErrorInfo> dsbList) {
this.name = name;
this.dsbList = dsbList;
}
/*
* 线程操作
*
* 依次解析urlList中仍存在的Files
*
* 实现了依次解析Files由于后期实现多线程解析操作
*/
public Object call() {
// 为当前线程命名 ,用与开发阶段友好输出。
Thread.currentThread().setName(name);
logger.debug(" 本次解析错误信息数 "+(dsbList==null?"null":dsbList.size()));
CommonDao dao = null;
try {
dao = new CommonDao();
CommonService service = new CommonService(dao);
//-- 空数据集合 结束操作
if(dsbList == null || dsbList.size() == 0 ){
return null;
}
long sTime = System.currentTimeMillis();
logger.debug("错误信息数据 " + (dsbList.size())+ "条,保存开始");
//-- 执行数据解析
String id = service.resoveErrorInfo(dsbList);//入库到表detection_info和detection_info_new中。直接用返回的id若是systeminfo则入库第一行之后的行
dsbList.clear();
} catch (Exception e) {
logger.error("Running exception",e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
logger.debug("数据清理 解析完成");
}
return null;
}
// public static void main(String[] args) {
// try {
// LinkedList<NmsErrorInfo> neiList = new LinkedList<NmsErrorInfo>();
// neiList.add(new NmsErrorInfo(Constants.ERROR_CODE_CREATE_SOCKET,new Date(),Common.getLocalIp(),"10.0.6.113",Constants.ERROR_INFO_SATAE_ERROR,"描述"));
// Common.service.submit(new ErrorInfoResoveThread("xx",neiList));
// }catch(Exception e) {
// e.printStackTrace();
// }
// }
}

View File

@@ -0,0 +1,145 @@
package com.nms.server.thread.file;
import java.io.File;
import java.io.FileInputStream;
import java.util.Calendar;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.FileUtils;
/**
* XML解析线程
*
* @author ZGGG3
*
*/
public class DetectFileReaderThread implements Runnable {
Logger logger = Logger.getLogger(DetectFileReaderThread.class);
private String dir;
private String name; // 自定义Thread Name
public DetectFileReaderThread(String name, String url) {
this.dir = url;
this.name = name;
}
public void run() {
// 为当前线程命名,用与日志友好输出。
Thread.currentThread().setName(name);
try {
logger.info("文件夹路径 :>" + dir);
File driFile = new File(dir);
// 获取目录下的.csv文件集合
File[] files = FileUtils.sortByFileNameASC(FileUtils.listFilesEndWith(driFile, ".csv")); // 按文件名称 升序排序
// 解析文件数为0时终止该计划任务
if(files==null || files.length==0){
Common.cancelRunnableAtOnce(dir);
return;
}
logger.debug("文件夹路径 :>" + driFile.getAbsolutePath() + "" + files.length + "个文件,解析开始");
long l = Calendar.getInstance().getTimeInMillis();
if (files != null && files.length > 0) {
for (File file : files) {
if(file.length()>0){
try {
FileInputStream fis = new FileInputStream(file);
int fileLength = (int) file.length(); //大小
int len = 0;
byte[] buff = new byte[fileLength];
if(fileLength>0){
len = fis.read(buff);
}
if(buff.length==0){continue;}
Common.addDeteData(buff);
fis.close();
} catch (Exception e) {
FileUtils.copyFile(file, new File(Constants.ERROR_DETEC_FILE_DIR+"/"+file.getName()));
logger.error("Monitoring data file reading errors"+Constants.ERROR_DETEC_FILE_DIR+"/"+file.getName(),e);
}
}
file.delete();
}
}
logger.debug(driFile.getAbsolutePath()+" 解析完成耗时:>"+(Calendar.getInstance().getTimeInMillis()-l));
//清理文件
files = FileUtils.sortByFileNameASC(FileUtils.listFilesEndWith(driFile, ".tp")); // 按文件名称 升序排序
if(files!=null && files.length>0){
for(File file : files){
file.delete();
}
}
logger.debug("临时文件清理完成");
} catch (Exception e) {
logger.error("",e);
}
}
/*
public static void main(String[] args) {
CommonDao dao = null;
try {
BoneCPPool.initPool();
dao = new CommonDao();
new InitServerThread().initCommonInfo(dao);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally{
dao.close();
}
long l = Calendar.getInstance().getTimeInMillis();
Future<?> future = Common.service.submit(new DetectFileReaderThread("解析 监测数据文件","D:\\NMS\\nmsdata\\dc_zip\\resove\\detect"));
try {
future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Calendar.getInstance().getTimeInMillis()-l);
future = Common.service.submit(new DetecDataResoveThread("解析 监测数据文件",Common.getDeteDataList()));
try {
future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Common.chengeDeteDataFlag();
future = Common.service.submit(new DetecDataResoveThread("解析 监测数据文件",Common.getDeteDataList()));
try {
future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}

View File

@@ -0,0 +1,105 @@
package com.nms.server.thread.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.Calendar;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.MissionResult2;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.FileUtils;
import com.nms.server.util.UnicodeReader;
/**
* XML解析线程
*
* @author ZGGG3
*
*/
public class ResultFileReaderThread implements Runnable {
Logger logger = Logger.getLogger(ResultFileReaderThread.class);
private String dir;
private String name; // 自定义Thread Name
public ResultFileReaderThread(String name, String url) {
this.dir = url;
this.name = name;
}
public void run() {
// 为当前线程命名 ,用与开发阶段友好输出。
Thread.currentThread().setName(name+" "+dir);
try {
logger.info("文件夹路径 :>" + dir);
File driFile = new File(dir);
//获取目录下的.result文件集合
File[] files = FileUtils.sortByFileNameASC(FileUtils.listFilesEndWith(driFile, ".result")); // 按文件名称 升序排序
// 解析文件数为0时终止该计划任务
if(files==null || files.length==0){
Common.cancelRunnableAtOnce(dir);
return;
}
logger.debug("文件夹路径 :>" + driFile.getAbsolutePath() + "" + files.length + "个文件,解析开始");
long l = Calendar.getInstance().getTimeInMillis();
if (files != null && files.length > 0) {
for (File file : files) {
if(file.length()>0){
try {
BufferedReader reader = new BufferedReader(new UnicodeReader(new FileInputStream(file), Charset.defaultCharset().name()));
String data = StringUtils.trim(reader.readLine());
String [] result = StringUtils.isEmpty(data)?null:data.split(Constants.COMMON_DATA_SPLIT);
if(result != null){
MissionResult2 result2 = Common.resoveMissionResult(result);
Common.addResultToResultList(result2);
}
reader.close();
} catch (Exception e) {
logger.error("",e);
}
}
file.delete();
}
}
logger.debug(driFile.getAbsolutePath()+" 解析完成耗时:>"+(Calendar.getInstance().getTimeInMillis()-l));
//清理
files = FileUtils.sortByFileNameASC(FileUtils.listFilesEndWith(driFile, ".tp")); // 按文件名称 升序排序
if(files!=null && files.length>0){
for(File file : files){
file.delete();
}
}
logger.debug("清理临时文件完成");
} catch (Exception e) {
logger.error("",e);
}
}
/* public static void main(String[] args) {
long l = Calendar.getInstance().getTimeInMillis();
Future<?> future = Common.service.submit(new FileReaderThread("文件解析线程", "D:\\cvs\\10.0.6.10"));
try {
future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Calendar.getInstance().getTimeInMillis()-l);
}*/
}

View File

@@ -0,0 +1,155 @@
package com.nms.server.thread.file;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.MissionResult2;
import com.nms.server.bean.ReturnFilePO;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.FileUtils;
import com.nms.server.util.UnicodeReader;
/**
* XML解析线程
*
* @author ZGGG3
*
*/
public class ReturnFileReaderThread implements Runnable {
Logger logger = Logger.getLogger(ReturnFileReaderThread.class);
private String dir;
private String name; // 自定义Thread Name
public ReturnFileReaderThread(String name, String url) {
this.dir = url;
this.name = name;
}
public void run() {
// 为当前线程命名 ,用与开发阶段友好输出。
Thread.currentThread().setName(name);
try {
File root = new File(dir);
File[] dirFiles = FileUtils.listFilesForDirectory(root);
// 解析文件数为0时终止该计划任务
if(dirFiles==null || dirFiles.length==0){
Common.cancelRunnableAtOnce(dir);
return;
}
for(File driFile : dirFiles){
logger.info("文件夹路径 :>" + driFile.getAbsolutePath());
//获取目录下的.return文件集合
File[] files = FileUtils.sortByFileNameASC(FileUtils.listFilesEndWith(driFile, ".return")); // 按文件名称 升序排序
// 解析文件数为0时终止该计划任务
if(files==null || files.length==0){
FileUtils.deleteDirectory(driFile);
continue;
}
logger.debug("文件夹路径 " + files.length + "个文件,解析开始");
long l = Calendar.getInstance().getTimeInMillis();
if (files != null && files.length > 0) {
for (File file : files) {
if(file.length()>0){
BufferedReader reader = new BufferedReader(new UnicodeReader(new FileInputStream(file), Charset.defaultCharset().name()));
String data = StringUtils.trim(reader.readLine());
if(StringUtils.isNotEmpty(data)){
ReturnFilePO returnFilePO = (ReturnFilePO) JSONObject.toBean(JSONObject.fromObject(data), ReturnFilePO.class);
String fnInfo = "";
if(StringUtils.isEmpty(returnFilePO.getReturnFileName())){
fnInfo= "";
}else{
// fnInfo= " 回传成功";
// fnInfo= " Success comes back";
fnInfo= " i18n_server.ReturnFileReaderThread.fnInfo_n81i";
}
MissionResult2 result2 = new MissionResult2(
returnFilePO.getTaskId(),
returnFilePO.getTaskType(),
returnFilePO.getUuid(),
returnFilePO.getStartTime().getTime(),
returnFilePO.getEndTime().getTime(),
null,
returnFilePO.getState(),
returnFilePO.getResDesc()+ fnInfo,
null,
returnFilePO.getIsLoop()
);
if(StringUtils.isNotEmpty(returnFilePO.getReturnFileName())){
String rFilePath = file.getParentFile().getAbsolutePath()+File.separator+returnFilePO.getReturnFileName();
File rFile = new File(rFilePath);
if(rFile.exists()){ //回传文件存在
System.out.println("回传文件存在");
result2.setFileInfo(returnFilePO.getReturnFileName());
FileUtils.copyFile(rFile, new File(Constants.MISSION_FILE_UPLOAD_DIR+returnFilePO.getReturnFileName()));
rFile.delete();
}else{
System.out.println("回传文件不存在");
result2.setDescription(result2.getDescription()+"\n"+returnFilePO.getReturnFileName()+"不存在");
}
}
Common.addResultToResultList(result2);
}
reader.close();
}
file.delete();
}
}
logger.debug(driFile.getAbsolutePath()+" 解析完成耗时:>"+(Calendar.getInstance().getTimeInMillis()-l));
//清理
files = FileUtils.sortByFileNameASC(FileUtils.listFilesEndWith(driFile, ".tp")); // 按文件名称 升序排序
if(files!=null && files.length>0){
for(File file : files){
file.delete();
}
}
//删除当前目录
driFile.delete();
}
logger.debug("临时文件清理完成");
} catch (Exception e) {
logger.error("",e);
}finally{
}
}
public static void main(String[] args) {
long l = Calendar.getInstance().getTimeInMillis();
Future<?> future = Common.service.submit(new ReturnFileReaderThread("文件解析线程", "D:\\ControllerData\\dc_zip\\resove\\return"));
try {
future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Calendar.getInstance().getTimeInMillis()-l);
}
}

View File

@@ -0,0 +1,63 @@
package com.nms.server.thread.file;
import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.FileUtils;
public class UnZipManagerThread implements Runnable{
Logger logger = Logger.getLogger(UnZipManagerThread.class);
public void run() {
// Thread.currentThread().setName("UnZip管理线程");
Thread.currentThread().setName("UnZip Management Thread");
// 将线程运行程序尽可能的catch捕获异常
try {
// 待解压文件 集合
List<File> zipFiles = new LinkedList<File>();
zipFiles.addAll(Arrays.asList(FileUtils.listFilesEndWith(new File(Constants.ZIP_FILE_DETECT_DATA_DIR), ".zip")));
zipFiles.addAll(Arrays.asList(FileUtils.listFilesEndWith(new File(Constants.ZIP_FILE_TASK_RESULT_DIR), ".zip")));
zipFiles.addAll(Arrays.asList(FileUtils.listFilesEndWith(new File(Constants.ZIP_FILE_TASK_RETURN_DIR), ".zip")));
// 无可解压的文件时 结束该周期任务
if(zipFiles.size()==0){
logger.info("已无可解压文件 周期任务终止");
Common.cancelRunnableAtOnce(Constants.UNZIP_FILE_MANAGER);
return;
}
// 校验解析线程是否存在 不存在时创建 并执行
Future<?> future = Common.getFutureMap().get(Constants.UNZIP_FILE);
if(future != null && !future.isCancelled() && !future.isDone()){
//运行中
logger.info("UnZip线程 运行中 不再重复启动");
return;
}else{
//为空或空闲中
logger.info("UnZip线程 空闲中 启动新线程");
future = Common.service.submit(new UnZipThread("UnZip线程", zipFiles));
//注册
Common.getFutureMap().put(Constants.UNZIP_FILE, future);
}
} catch (Exception e) {
logger.error("",e);
}
}
public static void main(String[] args) {
Common.service.submit(new UnZipManagerThread());
}
}

View File

@@ -0,0 +1,124 @@
package com.nms.server.thread.file;
import java.io.File;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.FileUtils;
import com.nms.server.util.ZipUtil;
/**
* XML解析线程
*
* @author ZGGG3
*
*/
public class UnZipThread implements Callable<Object> {
Logger logger = Logger.getLogger(UnZipThread.class);
private List<File> zipFileList;
private String name; // 自定义Thread Name
public UnZipThread(String name ,List<File> zipFileList) {
this.zipFileList = zipFileList;
this.name = name;
}
public Object call() {
// 为当前线程命名,用与开发阶段友好输出。
Thread.currentThread().setName(name);
try {
//筛选文件目录下的子目录
File[] files = FileUtils.sortByFileNameASC(zipFileList.toArray(new File[0])); // 按文件名称 升序排序
if (files != null && files.length > 0) {
long l = Calendar.getInstance().getTimeInMillis();
String resoveDirPath = null;
int fileType = -1; // 1detect 2result 3Return
for (File file : files) {
logger.debug("解压文件 :>" + file.getAbsolutePath());
try {
// 监测数据
if(file.getAbsolutePath().startsWith(new File(Constants.ZIP_FILE_DETECT_DATA_DIR).getAbsolutePath())){
resoveDirPath = Constants.ZIP_RESOVE_DETECT_DATA_DIR;
fileType = 1;
}
// 任务结果
else if(file.getAbsolutePath().startsWith(new File(Constants.ZIP_FILE_TASK_RESULT_DIR).getAbsolutePath())){
resoveDirPath = Constants.ZIP_RESOVE_TASK_RESULT_DIR;
fileType = 2;
}
// 回传文件
else if(file.getAbsolutePath().startsWith(new File(Constants.ZIP_FILE_TASK_RETURN_DIR).getAbsolutePath())){
resoveDirPath = Constants.ZIP_RESOVE_TASK_RETURN_DIR;
fileType = 3;
}
// 容错处理 删除无效文件
else{
file.delete();
return null;
}
//解压zip操作
if(fileType == 3){
ZipUtil.unZip(file.getAbsolutePath(), resoveDirPath+file.getName());
}else{
ZipUtil.unZip(file.getAbsolutePath(), resoveDirPath);
}
//删除已解压文件
file.delete();
Future<?> future = Common.getFutureMap().get(resoveDirPath);
//线程不存在 创建和注册
if(future == null){
switch (fileType) {
case 1: //监测数据 20160909 hyx 为了避免因长时间未收集数据导致一次性收集大量的数据nc端默认1000csv打包zip所以如果监测数据打包发送表明数据较多,如果全部进行解析入库会导致内存溢出所以存入dc_overrun等待之后慢慢解析
// future = Common.scheduled.scheduleWithFixedDelay(new DetectFileReaderThread("解析 监测数据文件",resoveDirPath), 0, 10, TimeUnit.SECONDS);
break;
case 2: //任务结果
future = Common.scheduled.scheduleWithFixedDelay(new ResultFileReaderThread("解析 任务结果文件",resoveDirPath), 0, 10, TimeUnit.SECONDS);
break;
case 3: //回传文件
future = Common.scheduled.scheduleWithFixedDelay(new ReturnFileReaderThread("解析 回传文件文件",resoveDirPath), 0, 10, TimeUnit.SECONDS);
break;
default:
break;
}
Common.registRunnable(resoveDirPath, future);
}
} catch (Exception e) {
logger.error("Unzip file abnormality "+file.getAbsolutePath(),e);
}
}
logger.debug(zipFileList.size()+"个zip文件 解压完成 共耗时:>"+(Calendar.getInstance().getTimeInMillis()-l));
}
} catch (Exception e) {
logger.error("",e);
}
return null;
}
/* public static void main(String[] args) {
List<File> zipFiles = new LinkedList<File>();
zipFiles.addAll(Arrays.asList(FileUtils.listFilesEndWith(new File(Constants.ZIP_FILE_TASK_RETURN_DIR), ".zip")));
Common.service.submit(new UnZipThread("解压线程", zipFiles));
}*/
}

View File

@@ -0,0 +1,131 @@
package com.nms.server.thread.file.upload;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.UpgradeService;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.FileUtils;
public class FileUploadManagerThread implements Runnable{
Logger logger = Logger.getLogger(FileUploadManagerThread.class);
public void run() {
//将线程运行程序尽可能的catch捕获异常
try {
// Thread.currentThread().setName("文件上传管理线程");
Thread.currentThread().setName("File Upload Management Thread");
String rootDir = Constants.MISSION_FILE_UPLOAD_DIR;
File rootFile = new File(rootDir);
if(FileUtils.listFilesEndWithout(rootFile, ".tp").length==0){
logger.info("根目录:> " + rootDir+" 无新文件");
return ;
}
//任务回传文件归类 增加任务ID解析
Map<Long,List<File>> missionFileMaps = new HashMap<Long, List<File>>();
File [] files = FileUtils.listFilesEndWithout(rootFile, ".tp");
logger.info("根目录:> " + rootDir+" 新文件数:"+files.length);
CommonDao dao = null;
UpgradeService service = null;
try {
for(File taskFile : files){
try {
Long mid = resoveMissionIdByFileName(taskFile.getName());
List<File> fileNameList = missionFileMaps.get(mid);
if(fileNameList == null){
fileNameList = new LinkedList<File>();
missionFileMaps.put(mid, fileNameList);
}
fileNameList.add(taskFile);
String hostIp = Common.getWebIPByMissionId(mid);
if(hostIp==null){
if(dao == null){
dao = new CommonDao();
service = new UpgradeService(dao);
}
hostIp = service.getHostIpByMissionId(mid);
Common.addMissionIdWebIPMap(mid,hostIp);
}
}catch (NumberFormatException e) {
logger.error("Getting the task ID error from the file name["+taskFile.getName()+"]",e);
FileUtils.copyFile(taskFile, new File(taskFile.getAbsoluteFile()+".Error.tp"));
taskFile.delete();
}catch (Exception e) {
logger.error("File"+taskFile.getName(),e);
FileUtils.copyFile(taskFile, new File(taskFile.getAbsoluteFile()+".Error.tp"));
taskFile.delete();
}
}
} catch (Exception e) {
logger.error("",e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
if(missionFileMaps.size()>0){
Iterator<Entry<Long,List<File>>> ite = missionFileMaps.entrySet().iterator();
while (ite.hasNext()) {
Entry<Long,List<File>> endtry = ite.next();
Future<?> future = Common.getFutureMap().get(rootFile.getAbsolutePath()+endtry.getKey());
if(future != null && !future.isCancelled() && !future.isDone()){ //运行中
logger.info(rootFile.getAbsolutePath()+" 上传文件线程 运行中 不再启动新线程");
}else{ //为空或空闲中
logger.info(rootFile.getAbsolutePath()+" 上传文件线程 空闲中 启动新线程");
String hostIp = Common.getWebIPByMissionId(endtry.getKey());
if(hostIp==null){
hostIp = Constants.WEB_SOCKET_IP;
}
future = Common.service.submit(new FileUploadThread3("Upload File Thread",hostIp,endtry.getValue().toArray(new File[0])));
//注册
Common.getFutureMap().put(rootFile.getAbsolutePath()+endtry.getKey(), future);
}
}
}
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}finally{
logger.info("操作结束");
}
}
public static Long resoveMissionIdByFileName(String fileName) {
Long missionId = null;
if(fileName.lastIndexOf("_T")!=-1){
// System.out.println(fileName.lastIndexOf("_T"));
// System.out.println(fileName.lastIndexOf("_"));
// System.out.println(fileName.indexOf("_",fileName.lastIndexOf("_T")+1));
String mid = fileName.substring(fileName.lastIndexOf("_T")+2,fileName.indexOf("_",fileName.lastIndexOf("_T")+1));
missionId = Long.parseLong(mid);
}else{
String fileName0 = fileName.substring(0,fileName.lastIndexOf("_"));
String mid = fileName0.substring(fileName0.lastIndexOf("_")+1,fileName0.length());
missionId = Long.parseLong(mid);
}
return missionId;
}
public static void main(String [] args) {
// System.out.println("mid "+resoveMissionIdByFileName("tasklist_0_T176_1322424525354"));
// System.out.println("mid "+resoveMissionIdByFileName("test_script_T1778_1363762154602994_relative.tar.gz"));
// System.out.println("mid "+resoveMissionIdByFileName("tasklist_0__176_1322424525354.txt"));
Common.service.submit(new FileUploadManagerThread());
}
}

View File

@@ -0,0 +1,87 @@
package com.nms.server.thread.file.upload;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import org.apache.log4j.Logger;
import com.nms.server.common.Constants;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.socket.SSLSocketCallable;
/**
* XML解析线程
*
* @author ZGGG3
*
*/
public class FileUploadThread3 extends SSLSocketCallable {
Logger logger = Logger.getLogger(FileUploadThread3.class);
private static Integer port = Constants.WEB_SOCKET_PORT;
private String name; // 自定义Thread Name
private File[] files;
public FileUploadThread3(String name,String ip,File[] files) throws Exception {
super(ip, port);
this.name = name;
this.files = files;
}
/*
* 线程操作
*
* 依次解析urlList中仍存在的Files
*
* 实现了依次解析Files由于后期实现多线程解析操作
*/
protected Object toDo() throws Exception {
// 为当前线程命名 ,用与开发阶段友好输出。
Thread.currentThread().setName(name);
try {
//循环遍历目录子文件
logger.debug("上传文件数量:> " + files.length + "个文件");
long l = Calendar.getInstance().getTimeInMillis();
if (files != null && files.length > 0) {
sendMessage("byte:bpUploadFiles");
String msg = receiveMessage();
bpSendFileByBath(Arrays.asList(files), null);
String params = this.receiveMessage(); //接收需要上传的文件列表
System.out.println("bpSendFileByBath "+params);
}
for(File file :files){
file.delete();
logger.debug(file.getAbsoluteFile()+"上传完成,已删除!");
}
logger.debug("上传文件 "+files.length+"个 上传耗时:"+(Calendar.getInstance().getTimeInMillis()-l)+" ms");
logger.info("上传完毕!");
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}
finally{
// dao.close();
}
return null;
}
// public static void main(String[] args) {
// long l = Calendar.getInstance().getTimeInMillis();
// try {
// Future<?> future = Common.service.submit(new FileUploadThread3("文件上传线程", Constants.MISSION_FILE_UPLOAD_DIR));
// future.get();
// System.exit(0);
// } catch (Exception e) {
// e.printStackTrace();
// }
// System.out.println(Calendar.getInstance().getTimeInMillis()-l);
// }
}

View File

@@ -0,0 +1,285 @@
package com.nms.server.thread.mission;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.nms.server.bean.MissionResult;
import com.nms.server.bean.MissionResult2;
import com.nms.server.bean.MissionStateTable;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.common.MissionConstants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.EmailService;
import com.nms.server.service.UpgradeService;
import com.nms.server.thread.socket.NMSWebBPDownload;
import com.socket.utils.FileComment;
/**
* 任务加载管理线程
* 每两分钟执行一次,或接收激活
* @date Nov 9, 2011 3:28:45 PM
* @author ZhangGang
*
*/
public class InitRunningMissionThread implements Runnable{
/* 线程基本属性 */
private Logger logger = Logger.getLogger(InitRunningMissionThread.class);
volatile boolean stop = false; //线程中断标示
/* 业务操作属性 */
private CommonDao dao = null; //数据库链接
private UpgradeService service = null; //
private EmailService emailService = null; //
private String missIds = null;
public InitRunningMissionThread(String missIdsTmp){
missIds = missIdsTmp;
}
@Override
public void run(){
// Thread.currentThread().setName("任务载入线程");
Thread.currentThread().setName("Task Loading Thread");
try {
/* 任务加载错开并发时间 等待 0-20秒 */
/* int waitTime = (int)(Math.random()*20000);
Thread.sleep(waitTime);
logger.debug("任务加载时间ms"+waitTime);*/
dao = new CommonDao(); //数据库链接
service = new UpgradeService(dao); //专属Service
emailService = new EmailService(dao);
List<MissionStateTable> missionList = service.getStartMessionList(missIds);
//- 任务校验及加载处理业务
if(missionList != null && missionList.size()>0){
// ml:for(MissionStateTable mission : missionList){
ml:for(int i=0;i<missionList.size() && !stop;i++){ //!stop 判断线程是否中断退出
MissionStateTable mission = missionList.get(i);
logger.debug("Mission_Run 开始执行任务Id:>"+mission.getMissionId()+" "+mission.getMissionState());
if(mission.getMissionState()==null){ //后续可增加任务告警
continue;
}
/* 任务状态为3、4、7 无需执行 不会出现 */
// if(mission.getMissionState().intValue() == 3
// ||mission.getMissionState().intValue() == 4
// ||mission.getMissionState().intValue() == 7 ){
// logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+" 3、4、7状态 执行结束");
// continue;
// }
/* 判断当前DC是否需要执行 */
List<MissionResult> mrList = null;
if(mission.getLoopFlag()!=null && mission.getLoopFlag().longValue()==1l){ //周期任务
//- 任务时间的有效性校验
if(mission.getEndTime()==null || mission.getEndTime().getTime() < System.currentTimeMillis() ){
if(mission.getMissionState().longValue() ==2l){
SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
// service.clearTimeoutLoopMisssion(mission.getMissionId());//2013-10-30 hyx 以下修改主任务表的状态未修改结果表和loop表的状态
// service.updateMissionState(mission.getMissionId(), 3,format.format(System.currentTimeMillis())+" 已超过任务结束时间 任务执行结束");
// emailService.sendEmailForMission(mission.getMissionId(),"任务执行失败"," 已超过任务结束时间 任务执行结束");
// logger.warn("已超过任务结束时间 任务执行结束");
// service.updateMissionState(mission.getMissionId(), 3,format.format(System.currentTimeMillis())+" The task has exceeded the end time and the task execution has ended");
// emailService.sendEmailForMission(mission.getMissionId(),"Task execution failure"," The task has exceeded the end time and the task execution has ended");
service.updateMissionState(mission.getMissionId(), 3,format.format(System.currentTimeMillis())+" i18n_server.InitRunningMissionThread.outEndTime_n81i");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.InitRunningMissionThread.missionFail_n81i"," i18n_server.InitRunningMissionThread.outEndTime_n81i");
logger.warn("The task has exceeded the end time and the task execution has ended");
}
/***告警功能****/
continue ;
}
if(mission.getMissionState() == 2l){
mrList = service.getMissionResultsForLoopTask(mission.getMissionId(), mission.getMissionType().intValue(),3);
}else if(mission.getMissionState() ==6l){
mrList = service.getMissionResultsForLoopTask(mission.getMissionId(), mission.getMissionType().intValue(),5);
}
}else{
mrList = service.getMissionResultsForTask(mission.getMissionId(), mission.getMissionType().intValue());
}
if(mrList == null || mrList.size() ==0){ //当前DC无需执行执行
continue;
}
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+((mrList == null || mrList.size() ==0)?"当前DC不执行":"当前DC执行下发"));
/* 校验并下载附件 */
List<FileComment> missionFileList = null ;
if(mission.getMissionType().intValue() == 1
||mission.getMissionType().intValue() == 6){
missionFileList = service.getMissionFileInformations(mission.getMissionId());
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+("当前DC有附件 数量:"+missionFileList.size()));
}else{
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+("当前DC无附件 "));
Common.assignMssion(mission);
continue;
}
String hostIp = service.getHostIpBySystemId(mission.getSystemId());
Integer port = Constants.WEB_SOCKET_PORT;
if(missionFileList != null && missionFileList.size()>0){
// ServerTable serverTable = Common.getServerTable();
// if(hostIp.equals(serverTable.getServerIp())){ // 同IP机器尝试本地复制
// try {
// for(FileComment fileComment: missionFileList){
// fileComment.
// FileUtils.copyFile(srcFile, destFile);
// }
// } catch (Exception e) {
// logger.equals("文件复制失败");
// }
// }
//断点续传下载fileList 的线程结果
Future<Object> bpf = Common.getBpDownMissionFilesMap().get(mission.getMissionId());
//-- MD5校验在NMSWebBPDownload中
//-- 未创建下载
if(bpf == null){
bpf = createDownload(mission.getMissionId(),hostIp,port,missionFileList);
if(bpf == null){
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+(" 附件下载失败 3分后再执行"));
Common.scheduled.schedule(new LoadNewMissionThread(mission.getMissionId()),3,TimeUnit.MINUTES);
continue ml;
}
}
//-- 下载线程未终止 继续下载中 无操作
if(!bpf.isDone()){
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+(" 附件下载未完成 3分后再执行"));
Common.scheduled.schedule(new LoadNewMissionThread(mission.getMissionId()),3,TimeUnit.MINUTES);
continue ml;
}
//-- dff.getBpDownFuture().isDone() == true 已存在下载结果
int result = (Integer)bpf.get(1,TimeUnit.SECONDS);
//-- MD5校验在NMSWebBPDownload中
//-- 下载失败 则重试 0 成功 -1 -2 重试 -3 失败
if(result == -1 || result == -2){
bpf = createDownload(mission.getMissionId(),hostIp,port,missionFileList);
if(bpf == null || !bpf.isDone()){
Common.scheduled.schedule(new LoadNewMissionThread(mission.getMissionId()),3,TimeUnit.MINUTES);
continue ml;
}
}
//-- 下载成功
boolean missionDFFlag = true; //任务下所有文件 下载完成标识 false未完成 true已完成
String errorFileName = null;
mfl:for(FileComment fileInfo : missionFileList){
File file = new File(Constants.MISSION_FILE_DOWNLOAD_DIR+fileInfo.getFileName());
if(!file.exists()){ // 文件不存在,下载失败
missionDFFlag =false;
errorFileName = fileInfo.getFileName();
break mfl;
}
}
if(!missionDFFlag){
// List<MissionResult2> mr2List = new ArrayList<MissionResult2>();
//nodeList
for( MissionResult mr : mrList){
MissionResult2 result2 = new MissionResult2();
//- 任务Id long
result2.setMissionId(mr.getMissionId());
//-- 任务类型 long
result2.setMissionType(mission.getMissionType());
//- UUID long
result2.setUuid(mr.getUuid());
//- 周期标识 long
result2.setLoopFlag(mission.getLoopFlag());
//- 开始执行时间 long
result2.setStartTime(null);
//- 结束时间 long
result2.setEndTime(null);
//- 配置截取文本 string
result2.setText(null);
//- 结果状态 long
result2.setResult(1l);
//- 结果描述 string
result2.setDescription(errorFileName+" "+MissionConstants.ERROR_RESULT_FILE_DOWNLOAD_FAIL);
// mr2List.add(result2);
Common.addResultToResultList(result2);//DC下载文件失败
}
// service.updateMissionResult2ByBatch(mission.getMissionType().intValue(),mr2List);
}
//清理缓存 和废弃文件
if(!missionDFFlag){
for(FileComment fileInfo : missionFileList){
File file = new File(Constants.MISSION_FILE_DOWNLOAD_DIR+fileInfo.getFileName());
if(file.exists()){
file.delete();
logger.debug(file.getAbsolutePath()+"已删除!");
}else {
logger.debug(file.getAbsolutePath()+"不存在");
}
}
}else{
//--该任务 已无文件可下载, 执行文件下发操作
Common.assignMssion(mission);
continue;
}
}else{
//--该任务 已无文件可下载, 执行文件下发操作
Common.assignMssion(mission);
continue;
}
}
}
}catch (InterruptedException e) {
logger.warn("Thread interrupt operation, execute exit",e);
}
catch (Exception e) {
logger.error("loadNewMission error ",e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
/**
* 创建下载线程
* @time Mar 20, 2012-4:12:42 PM
* @param missionFileList
* @return
*/
private Future<Object> createDownload(Long missionId ,String ip,Integer port,List<FileComment> missionFileList){
try {
Future<Object> bpf = Common.service.submit(new NMSWebBPDownload(ip,port,missionFileList,Constants.MISSION_FILE_DOWNLOAD_DIR,NMSWebBPDownload.TYPE_MISSION));
bpf.get(Constants.MISSION_FILE_DOWNLOAD_DELAY, TimeUnit.SECONDS);
if(!bpf.isDone()){
Common.getBpDownMissionFilesMap().put(missionId, bpf);
}
return bpf;
} catch (Exception e) {
logger.error("Failure to create a download thread ",e);
return null;
}
}
public static void main(String [] args) {
Common.service.submit(new InitRunningMissionThread(null));
}
}

View File

@@ -0,0 +1,660 @@
package com.nms.server.thread.mission;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.LoopMissionRoundInfo;
import com.nms.server.bean.MissionResult;
import com.nms.server.bean.MissionResult2;
import com.nms.server.bean.MissionStateTable;
import com.nms.server.bean.Task1;
import com.nms.server.bean.Task4;
import com.nms.server.bean.Task6;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.common.MissionConstants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.EmailService;
import com.nms.server.service.UpgradeService;
import com.nms.server.thread.socket.NMSWebBPDownload;
import com.socket.utils.FileComment;
/**
* 任务加载管理线程
* 每两分钟执行一次,或接收激活
* 可加载 指定任务 或 者所有符合条件的任务
* @date Nov 9, 2011 3:28:45 PM
* @author ZhangGang
*
*/
public class LoadNewMissionThread implements Runnable{
/* 线程基本属性 */
private Logger logger = Logger.getLogger(LoadNewMissionThread.class);
volatile boolean stop = false; //线程中断标示
/* 业务操作属性 */
private CommonDao dao = null; //数据库链接
private UpgradeService service = null; //
private EmailService emailService = null; //
private Long missionId = null;
SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
public LoadNewMissionThread(Long missionId){
this.missionId = missionId;
}
@Override
public void run(){
if(missionId!=null){
// Thread.currentThread().setName("新任务载入线程 Id:>"+missionId);
Thread.currentThread().setName("The New Task Is Loaded With Thread Id:>"+missionId);
}else{
// Thread.currentThread().setName("新任务载入线程");
Thread.currentThread().setName("The New Task Load Thead");
}
try {
/* 任务加载错开并发时间 等待 0-20秒 */
int waitTime = (int)(Math.random()*20000);
Thread.sleep(waitTime);
logger.debug("任务加载时间(ms)"+waitTime);
dao = new CommonDao();
service = new UpgradeService(dao);
emailService = new EmailService(dao);
List<MissionStateTable> missionList = service.getNewMessionList(missionId);//mission_state_table的状态为1或者5且未过时针对周期任务的任务
logger.debug("Mission_Run 新任务数量:>"+missionList.size());
//遍历任务集合
if(missionList != null && missionList.size()>0){
ml:for(int i=0;i<missionList.size() && !stop;i++){ //!stop 判断线程是否中断退出
/* 任务校验及初始化业务 Begin */
MissionStateTable mission = missionList.get(i);
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId());
if(mission.getMissionState()==null){ //后续可增加任务告警
continue;
}
//任务状态为3、4、7 无需执行
// if(mission.getMissionState().intValue() == 3
// ||mission.getMissionState().intValue() == 4
// ||mission.getMissionState().intValue() == 7 ){
// logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+" 3、4、7状态 执行结束");
// continue;
// }else
//任务状态为1 或 5 :任务参数校验和初始化任务
if(mission.getMissionState().intValue() == 1 || mission.getMissionState().intValue() == 5){
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+" 执行任务初始化");
//初始化任务信息
if(!checkAndInitMission(mission)){ //校验并初始化任务---第一步---会改变任务的状态
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+"初始化失败 执行结束");
continue;
}
}
/* 判断当前DC是否需要执行 --第二步*/
List<MissionResult> mrList = null;
if(mission.getLoopFlag()!=null && mission.getLoopFlag().longValue()==1l){ //周期任务
if(mission.getMissionState() == 2l){
mrList = service.getMissionResultsForLoopTask(mission.getMissionId(), mission.getMissionType().intValue(),3);
}else if(mission.getMissionState() ==6l){
mrList = service.getMissionResultsForLoopTask(mission.getMissionId(), mission.getMissionType().intValue(),5);
}
}else{ //非周期任务
mrList = service.getMissionResultsForTask(mission.getMissionId(), mission.getMissionType().intValue());
}
if(mrList == null || mrList.size() ==0){ //当前DC无需执行----------->>>??
continue;
}
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+((mrList == null || mrList.size() ==0)?"当前DC不执行":"当前DC执行下发"));
//校验并下载附件--第三步
List<FileComment> missionFileList = null ;
if(mission.getMissionType().intValue() == 1
||mission.getMissionType().intValue() == 6){
missionFileList = service.getMissionFileInformations(mission.getMissionId());
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+("当前DC有附件 数量:"+missionFileList.size()));
}else{
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+("当前DC无附件 "));
Common.assignMssion(mission);
continue;
}
String hostIp = service.getHostIpBySystemId(mission.getSystemId());
Integer port = Constants.WEB_SOCKET_PORT;
if(missionFileList != null && missionFileList.size()>0){
// ServerTable serverTable = Common.getServerTable();
// if(hostIp.equals(serverTable.getServerIp())){ // 同IP机器尝试本地复制
// try {
// for(FileComment fileComment: missionFileList){
// fileComment.
// FileUtils.copyFile(srcFile, destFile);
// }
// } catch (Exception e) {
// logger.equals("文件复制失败");
// }
// }
//断点续传下载fileList 的线程结果
Future<Object> bpf = Common.getBpDownMissionFilesMap().get(mission.getMissionId());
//-- MD5校验在NMSWebBPDownload中
//-- 未创建下载
if(bpf == null){
bpf = createDownload(mission.getMissionId(),hostIp,port,missionFileList);
if(bpf == null){
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+(" 附件下载失败 3分后再执行"));
Common.scheduled.schedule(new LoadNewMissionThread(missionId),3,TimeUnit.MINUTES);
continue ml;
}
}
//-- 下载线程未终止 继续下载中 无操作
if(!bpf.isDone()){
logger.debug("Mission_Run 任务Id:>"+mission.getMissionId()+(" 附件下载未完成 3分后再执行"));
Common.scheduled.schedule(new LoadNewMissionThread(missionId),3,TimeUnit.MINUTES);
continue ml;
}
//-- dff.getBpDownFuture().isDone() == true 已存在下载结果
int result = (Integer)bpf.get(1,TimeUnit.SECONDS);
//-- MD5校验在NMSWebBPDownload中
//-- 下载失败 则重试 0 成功 -1 -2 重试 -3 失败
if(result == -1 || result == -2){
bpf = createDownload(mission.getMissionId(),hostIp,port,missionFileList);
if(bpf == null || !bpf.isDone()){
Common.scheduled.schedule(new LoadNewMissionThread(missionId),3,TimeUnit.MINUTES);
continue ml;
}
}
//-- 下载成功
boolean missionDFFlag = true; //任务下所有文件 下载完成标识 false未完成 true已完成
String errorFileName = null;
mfl:for(FileComment fileInfo : missionFileList){
File file = new File(Constants.MISSION_FILE_DOWNLOAD_DIR+fileInfo.getFileName());
logger.debug("DC下载文件的路径"+Constants.MISSION_FILE_DOWNLOAD_DIR+fileInfo.getFileName());
if(!file.exists()){ // 文件不存在,下载失败
missionDFFlag =false;
errorFileName = fileInfo.getFileName();
break mfl;
}
}
if(!missionDFFlag){//下载失败所以将结果表示置为失败1
// List<MissionResult2> mr2List = new ArrayList<MissionResult2>();
//nodeList
for( MissionResult mr : mrList){
MissionResult2 result2 = new MissionResult2();
//- 任务Id long
result2.setMissionId(mr.getMissionId());
//-- 任务类型 long
result2.setMissionType(mission.getMissionType());
//- UUID long
result2.setUuid(mr.getUuid());
//- 周期标识 long
result2.setLoopFlag(mission.getLoopFlag());
//- 开始执行时间 long
result2.setStartTime(null);
//- 结束时间 long
result2.setEndTime(null);
//- 配置截取文本 string
result2.setText(null);
//- 结果状态 long
result2.setResult(1l);
//- 结果描述 string
result2.setDescription(errorFileName+" "+MissionConstants.ERROR_RESULT_FILE_DOWNLOAD_FAIL);
// mr2List.add(result2);
Common.addResultToResultList(result2);//DC下载文件失败-2013-3-13 hyx 为了更新任务的状态及描述
}
// service.updateMissionResult2ByBatch(mission.getMissionType().intValue(),mr2List);
}
//清理缓存 和废弃文件
if(!missionDFFlag){
for(FileComment fileInfo : missionFileList){
File file = new File(Constants.MISSION_FILE_DOWNLOAD_DIR+fileInfo.getFileName());
if(file.exists()){
file.delete();
logger.debug(file.getAbsolutePath()+"已删除!");
}else {
logger.debug(file.getAbsolutePath()+"不存在");
}
}
}else{
//--该任务 已无文件可下载, 执行文件下发操作
Common.assignMssion(mission);
continue;
}
}else{
//--该任务 已无文件可下载, 执行文件下发操作
Common.assignMssion(mission);
continue;
}
/* 线程中断判断判断 */
if(Thread.currentThread().isInterrupted()){
stop = true;
}
}
//初始化任务结束后,需要统计更新任务的状态-2013-3-13 hyx--增加的原因初始化的时候可能会插入结果1失败但是又未统计mission_state_table表中的state此处进行统计
service.updateCommonMissionComplete();//非周期任务任务状态成功31、部分成功32、全部失败30
service.updateLoopMissionComplete();//周期任务
}
}catch (InterruptedException e) {
logger.warn("Thread interrupt operation, execute exit",e);
}catch (Exception e) {
logger.error("loadNewMission error ",e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
/**
* 校验并初始化参数
* @time Nov 15, 2011-6:21:52 PM
* @param missionId
*/
public boolean checkAndInitMission(MissionStateTable mission) {
if(mission == null){
return false;
}
boolean taskFlag = true;
/* 根据任务类型校验参数 */
switch (mission.getMissionType().intValue()) {
case 1:
taskFlag = checkAndInitTask1(mission);
break;
case 4:
if(mission.getLoopFlag()!=null && mission.getLoopFlag().longValue()==1l){ //周期任务
taskFlag = checkAndInitLoopTask4(mission);
// taskFlag = false;
}else{ //非周期任务
taskFlag = checkAndInitTask4(mission);
}
break;
case 6:
taskFlag = checkAndInitTask6(mission);
break;
default:
taskFlag = false;
break;
}
//更新任务状态描述-2013-3-13 hyx--增加的原因初始化的时候可能会插入结果1失败但是又未添加描述此处添加任务状态描述
String missType = mission.getMissionType()==null?"":mission.getMissionType().toString();
String isLoop = mission.getLoopFlag()==null?null:mission.getLoopFlag().toString();
String missId = mission.getMissionId()==null?"":mission.getMissionId().toString();
if ("4".equals(missType)&&"1".equals(isLoop)){//周期任务
service.updateLoopMissionStateDesc(missId);//周期任务type=4
}else {
service.updateCommonMissionStateDesc(Integer.parseInt(missType),missId);//非周期任务
}
return taskFlag;
}
/**
* 校验任务类型1文件推送可执行和初始化任务信息
* 1、校验参数完整
* 2、校验存在附件
* 3、初始化任务信息校验任务下发节点有效、非服务器和管理范围外Node 结果判定失败)
* 4、判断当前DC是否可执行该任务
*
* @time Feb 23, 2013-6:06:24 PM
* @param mission
* @return
*/
@SuppressWarnings("finally")
public boolean checkAndInitTask1(MissionStateTable mission){
boolean taskFlag = true;
StringBuffer errorInfo = new StringBuffer();
//查询参数信息和附件信息
Task1 task1 = service.getTask1ById(mission.getMissionId()); //查询任务具体信息
List<FileComment> fileCommentsList = null ;
/* 任务可执行校验 */
//第一步:任务参数完整
if(task1 == null || StringUtils.isEmpty(task1.getTaskParam())){
errorInfo.append(MissionConstants.ERROR_TASK_PARAMS);
taskFlag = false;
}
//第二步:附件信息校验
if(taskFlag){
fileCommentsList = service.getMissionFileInformations(mission.getMissionId());
if((fileCommentsList == null || fileCommentsList.size()==0)){
errorInfo.append(MissionConstants.ERROR_TASK_NO_FILE);
taskFlag= false;
}
}
try {
//第三步:初始化任务
if(taskFlag){
logger.debug("missionId:> "+mission.getMissionId()+" 初始化信息");
//先走1全部初始化不作节点类型和节点管理范围外判断 后续确认优化信息
service.initMissionResults2(mission.getMissionId(),task1.getNodeGroupsId(),task1.getNodeIpsId(),mission.getMissionType().intValue());
// emailService.sendEmailForMission(mission.getMissionId(),"任务下发通知","任务下发开始");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionLssue_n81i","i18n_server.LoadNewMissionThread.missionLssueStart_n81i");
mission.setMissionState(2l);//为了使内存中的数据和数据库中的数据一致因为service.initMissionResults2()方法修改了missionState状态为2
}else{//任务失败
logger.error("missionId:> "+mission.getMissionId()+" init info>"+errorInfo);
service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" "+errorInfo);//hyx 修改:第二个参数传递错误
// emailService.sendEmailForMission(mission.getMissionId(),"任务初始化失败",errorInfo+"");
// emailService.sendEmailForMission(mission.getMissionId(),"Task initialization failed",errorInfo+"");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionInitFail_n81i",errorInfo+"");
}
return taskFlag;
} catch (Exception e) {
//添加告警
logger.error("Initialization failed",e);
taskFlag = false;
}finally{
return taskFlag;
}
}
@SuppressWarnings("finally")
public boolean checkAndInitTask4(MissionStateTable mission){
boolean taskFlag = true;
StringBuffer errorInfo = new StringBuffer();
//查询参数信息和附件信息
Task4 task4 = service.getTask4ById(mission.getMissionId()); //查询任务具体信息
/* 任务可执行校验 */
//第一步:任务参数完整
if(task4 == null || StringUtils.isEmpty(task4.getCommandName())|| task4.getCommandType() == 0 ){
// errorInfo.append("命令执行任务参数为空,任务无法执行");
// errorInfo.append("The command execution task parameter is empty, and the task cannot be executed");
errorInfo.append("i18n_server.LoadNewMissionThread.errorInfo1_n81i");
taskFlag = false ;
}
//第二步:初始化任务
try {
if(taskFlag){
logger.debug("missionId:> "+mission.getMissionId()+" 初始化信息");
//先走1全部初始化不作节点类型和节点管理范围外判断 后续确认优化信息
// service.initMissionResults(mission.getMissionId(),task1.getNodeGroupsId(),task1.getNodeIpsId(),mission.getMissionType().intValue());
service.initMissionResults2(mission.getMissionId(),task4.getNodeGroupsId(),task4.getNodeIpsId(),mission.getMissionType().intValue());
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionLssue_n81i","i18n_server.LoadNewMissionThread.missionLssueStart_n81i");
// mission.setMissionState(2l);
mission.setMissionState(2l);
}else{//任务失败
logger.error("missionId:> "+mission.getMissionId()+" init info>"+errorInfo);
service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" "+errorInfo);//hyx 修改:第二个参数传递错误
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionExecFail_n81i",errorInfo+"");
}
return taskFlag;
} catch (Exception e) {
//添加告警
logger.error("Initialization failed",e);
taskFlag = false;
}finally{
return taskFlag;
}
}
@SuppressWarnings("finally")
public boolean checkAndInitLoopTask4(MissionStateTable mission){
boolean taskFlag = true;
StringBuffer errorInfo = new StringBuffer();
//查询参数信息和附件信息
Task4 task4 = service.getTask4ById(mission.getMissionId()); //查询任务具体信息
/* 任务可执行校验 */
//第一步:任务参数完整
if(task4 == null || StringUtils.isEmpty(task4.getCommandName())|| task4.getCommandType() == 0 ){
// errorInfo.append("命令执行任务参数为空,任务无法执行");
// errorInfo.append("The command execution task parameter is empty, and the task cannot be executed");
errorInfo.append("i18n_server.LoadNewMissionThread.errorInfo1_n81i");
taskFlag = false ;
}
//- 任务时间的有效性校验
if(mission.getEndTime()==null || mission.getEndTime().getTime() < System.currentTimeMillis() ){
// errorInfo.append("已超过任务结束时间 任务未能执行");
// errorInfo.append("The task has exceeded the end time ,and the task execution has ended");
errorInfo.append("i18n_server.LoadNewMissionThread.errorInfo2_n81i");
taskFlag = false ;
}
SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
try {
//初始化任务 任务状态 1 或 5
logger.debug(mission.getMissionId()+" 周期任务状态"+" "+mission.getMissionState());
mission.setNodeGroupsId(task4.getNodeGroupsId()); //保存节点组信息
mission.setNodeIpsId(task4.getNodeIpsId()); //保存节点信息
//-- 整理并初始化周期任务信息
service.checkAndInitMissionCycle(mission);// 轮次校验和初始化
//-- 获取当前周期轮次
LoopMissionRoundInfo roundInfo = null;
List<LoopMissionRoundInfo> roundInfoList = Common.getLoopMissionRoundInfoList().get(mission.getMissionId());
if(roundInfoList !=null && roundInfoList.size()>0){
//-- 获取当前周期轮次
for (Iterator<LoopMissionRoundInfo> roundIte = roundInfoList.iterator(); roundIte.hasNext();) {
roundInfo = roundIte.next();
if(roundInfo.getEndTime().getTime() > System.currentTimeMillis()){
break;
}
}
}
if(roundInfo == null){
// errorInfo.append("周期任务轮次初始化异常,任务无法执行");
// errorInfo.append("Periodic task initialization is abnormal and cannot be performed");
errorInfo.append("i18n_server.LoadNewMissionThread.errorInfo3_n81i");
taskFlag = false ;
}
if(taskFlag && mission.getMissionState()!= null && mission.getMissionState().intValue()==1){ //创建初始化
logger.info("该周期任务 按正常业务执行");
//-- 预置状态的轮次,初始化当前轮次的结果数据
if(roundInfo!=null && roundInfo.getMissionState()!=null && roundInfo.getMissionState().longValue()==0l || roundInfo.getMissionState().longValue()==1l){ //0 预置状态,未初始化当前轮次的任务结果信息
logger.info("周期任务 轮次信息初始化");
service.initLoopMissionResults2(roundInfo.getCurMissionId(), task4.getNodeGroupsId(),task4.getNodeIpsId(),3);//初始化可下发的结果信息 3 未下发
roundInfo.setMissionState(2l); //更新缓存中的任务轮次信息状态
}
//- 变更任务状态 1以创建 -> 2正在执行
// service.updateMissionState(mission.getMissionId(), 2,format.format(System.currentTimeMillis())+" 任务执行开始");
service.updateMissionState(mission.getMissionId(), 2,format.format(System.currentTimeMillis())+" i18n_server.LoadNewMissionThread.missionStart_n81i");
mission.setMissionState(2l);
// emailService.sendEmailForMission(mission.getMissionId(),"任务下发通知","任务开始执行");
// emailService.sendEmailForMission(mission.getMissionId(),"Notification of send task","Start the task");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionLssue_n81i","i18n_server.LoadNewMissionThread.missionStart_n81i");
}else if(taskFlag && mission.getMissionState()!= null && mission.getMissionState().intValue()==5){ //撤销初始化
//撤销任务下发操作 (获取当前操作周期或最后一个非初始化周期的轮次信息)
logger.debug("该周期任务 按撤销业务执行");
//-- 旧轮次信息状态记录
int oldRoundState = roundInfo.getMissionState()==null?0:roundInfo.getMissionState().intValue();
//-- 将当前周期状态 变更为撤销准备周期
service.updateLoopMissionState(roundInfo.getCurMissionId(),5);
//-- 删除预置周期
service.deleteLoopMissionPreset(mission.getMissionId(),roundInfo.getCurMissionId());
//-- 更新缓存轮次信息(上面已更新完成)
// service.updateLoopMissionRoundInfo(Common.getLoopMissionRoundInfoList(), mission.getMissionId());
//-- 将撤销周期的结果数据进行状态初始化
if(oldRoundState == 0){ //预置周期无结果
service.initLoopMissionResults2(roundInfo.getCurMissionId(), task4.getNodeGroupsId(),task4.getNodeIpsId(),5);//初始化可下发的结果信息 5 撤销未下发
}else if(oldRoundState>0){ //存在结果的周期 及2或3
service.updateMissionResultsResult(roundInfo.getCurMissionId(), 4, 5);
service.updateLoopMissionState(roundInfo.getCurMissionId(), 6); //更新 任务轮次信息状态
}
roundInfo.setMissionState(6l); //更新缓存中的任务轮次信息状态
//- 变更任务状态 5准备撤销 -> 6撤销执行
service.updateMissionState(mission.getMissionId(), 6,format.format(System.currentTimeMillis())+" Task revocation start execute");
mission.setMissionState(6l);
// emailService.sendEmailForMission(mission.getMissionId(),"任务撤销通知","任务撤销开始执行");
// emailService.sendEmailForMission(mission.getMissionId(),"Task cancellation notice","Task revocation start execute");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionRevoke_n81i","i18n_server.LoadNewMissionThread.missionRevokeStart_n81i");
}
//第三步:初始化任务
if(!taskFlag){
// service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" 任务执行失败");
service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" Task execution failure");
// emailService.sendEmailForMission(mission.getMissionId(),"任务执行失败",errorInfo+"");
// emailService.sendEmailForMission(mission.getMissionId(),"Task execution failure",errorInfo+"");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionExecFail_n81i",errorInfo+"");
}
return taskFlag;
} catch (Exception e) {
logger.error("Initialization failed",e);
taskFlag = true;
}finally{
return taskFlag;
}
}
/**
* 校验任务类型1文件推送可执行和初始化任务信息
* 1、校验参数完整
* 2、校验存在附件
* 3、初始化任务信息校验任务下发节点有效、非服务器和管理范围外Node 结果判定失败)
* 4、判断当前DC是否可执行该任务
*
* @time Feb 23, 2013-6:06:24 PM
* @param mission
* @return
*/
@SuppressWarnings("finally")
public boolean checkAndInitTask6(MissionStateTable mission){
boolean taskFlag = true;
StringBuffer errorInfo = new StringBuffer();
//查询参数信息和附件信息
Task6 task6 = service.getTask6ById(mission.getMissionId()); //查询任务具体信息
List<FileComment> fileCommentsList = null ;
/* 任务可执行校验 */
//第一步:任务参数完整
if(task6 == null || StringUtils.isEmpty(task6.getCommandName())|| task6.getCommandType() == 0 ){
// errorInfo.append("升级部署任务参数为空,任务无法执行");
// errorInfo.append("The upgrade deployment task parameter is empty, and the task cannot be executed");
errorInfo.append("i18n_server.LoadNewMissionThread.errorInfo4_n81i");
taskFlag = false;
}
//第二步:附件信息校验
if(taskFlag){
fileCommentsList = service.getMissionFileInformations(mission.getMissionId());
/** 逆向任务 无附件其判断标示为OldTaskId 不为空 **/
if(task6.getVersion()==null && task6.getOldTaskId()==null && (fileCommentsList == null || fileCommentsList.size()==0)){
errorInfo.append(MissionConstants.ERROR_TASK_NO_FILE);
taskFlag= false;
}
}
try {
//第三步:初始化任务
if(taskFlag){
logger.debug("missionId:> "+mission.getMissionId()+" 初始化信息");
//先走1全部初始化不作节点类型和节点管理范围外判断 后续确认优化信息
service.initMissionResults2(mission.getMissionId(),task6.getNodeGroupsId(),task6.getNodeIpsId(),mission.getMissionType().intValue());
// emailService.sendEmailForMission(mission.getMissionId(),"任务下发通知","任务下发开始");
// emailService.sendEmailForMission(mission.getMissionId(),"Notification of send task","Start task");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionLssue_n81i","i18n_server.LoadNewMissionThread.missionLssueStart_n81i");
mission.setMissionState(2l);
}else{//任务失败
logger.error("missionId:> "+mission.getMissionId()+" init info>"+errorInfo);
service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" "+errorInfo);//hyx 修改:第二个参数传递错误
// emailService.sendEmailForMission(mission.getMissionId(),"任务执行失败",errorInfo+"");
// emailService.sendEmailForMission(mission.getMissionId(),"Task execution failure",errorInfo+"");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.LoadNewMissionThread.missionExecFail_n81i",errorInfo+"");
}
return taskFlag;
} catch (Exception e) {
//添加告警
logger.error("Initialization failed",e);
taskFlag = false;
}finally{
return taskFlag;
}
}
/**
* 创建下载线程
* @time Mar 20, 2012-4:12:42 PM
* @param missionFileList
* @return
*/
private Future<Object> createDownload(Long missionId ,String ip,Integer port,List<FileComment> missionFileList){
try {
Future<Object> bpf = Common.service.submit(new NMSWebBPDownload(ip,port,missionFileList,Constants.MISSION_FILE_DOWNLOAD_DIR,NMSWebBPDownload.TYPE_MISSION));
bpf.get(Constants.MISSION_FILE_DOWNLOAD_DELAY, TimeUnit.SECONDS);
if(!bpf.isDone()){
Common.getBpDownMissionFilesMap().put(missionId, bpf);
}
return bpf;
} catch (Exception e) {
logger.error("Failure to create a download thread ",e);
return null;
}
}
public static void main(String [] args) {
// Common.service.submit(new LoadNewMissionThread(1343l));
Common.service.submit(new LoadNewMissionThread(4125l));
}
}

View File

@@ -0,0 +1,456 @@
package com.nms.server.thread.mission;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.LoopMissionRoundInfo;
import com.nms.server.bean.MissionResult;
import com.nms.server.bean.MissionStateTable;
import com.nms.server.bean.Task1;
import com.nms.server.bean.Task4;
import com.nms.server.bean.Task6;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.EmailService;
import com.nms.server.service.UpgradeService;
import com.nms.server.util.ExceptionPrintUtils;
import com.socket.utils.FileComment;
public class MissionPollingThread implements Runnable{
private final Logger logger = Logger.getLogger(MissionPollingThread.class);
private List<MissionStateTable> missionList = null;
private List<MissionStateTable> missionList2 = new ArrayList<MissionStateTable>();
private String threadName;
private Integer testNum = 1;
/**
* 线程单例
* @time Nov 15, 2011-7:15:34 PM
* @return
*/
public MissionPollingThread (String threadName,final Integer testNum,final List<MissionStateTable> missionList) {
this.missionList = missionList;
this.testNum = testNum;
this.threadName = threadName;
}
public void run() {
Thread.currentThread().setName(threadName);
//-- 结束无意义操作
if(testNum==null || missionList == null || missionList.size()==0){
logger.warn("The task queue is empty and does not need to be executed");
return;
}
//-- 循环下发任务
try {
while(missionList.size()>0){
MissionStateTable mission = missionList.get(0);
Thread.currentThread().setName(threadName+" Id:>"+mission.getMissionId());
switch (mission.getMissionType().intValue()) {
case 1:
forTask1(mission);
break;
case 4:
if(mission.getLoopFlag()!=null && mission.getLoopFlag().longValue()==1l){ //周期任务
forLoopMission(mission);
}else{ //非周期任务
forTask4(mission);
}
break;
case 6:
forTask6(mission);
break;
default:
break;
}
missionList2.add(mission);
missionList.remove(0);
}
//-- 创建下一次任务轮询
if(testNum.intValue() < Constants.MISSION_RELEASE_TIMES.intValue()){
logger.info("开始第“"+(testNum+1)+"”次任务轮询");
Common.scheduled.schedule(new MissionPollingThread("第“"+(testNum+1)+"”次轮询线程",(testNum+1),missionList2), Constants.MISSION_RELEASE_PERIOD, TimeUnit.SECONDS);
missionList2 = new ArrayList<MissionStateTable>();
}else{
missionList2.clear();
}
}catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}
}
/**
* 文件推送任务执行
* @time Nov 11, 2011-6:55:33 PM
* @param mission
*/
public void forTask1(MissionStateTable mission) {
CommonDao dao = null; //数据库链接
try {
dao = new CommonDao();
UpgradeService service = new UpgradeService(dao); //专属Service
//-- 任务结果查询和推送文件
Task1 task1 = service.getTask1ById(mission.getMissionId()); //查询任务具体信息
List<FileComment> fileCommentsList = service.getMissionFileInformations(mission.getMissionId());
ArrayList<MissionResult> mrList = service.getMissionResultsForTask(mission.getMissionId(),mission.getMissionType().intValue());
//-- 遍历节点结果集合
for (MissionResult result : mrList) {
//-- 针对节点 进行文件推送
Common.sendMissionInfo(mission,new NMSClientTask1(result.getNodeIp(),Constants.SSL_CLIENT_PORT,mission,task1,fileCommentsList),result.getUuid(), testNum,null,null);
}
} catch (Exception e) {
logger.error("Task Id:>"+mission.getMissionId()+" task execution failure", e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
//public static void main(String [] args) {
// List<MissionStateTable> missionList = new LinkedList<MissionStateTable>();
// CommonDao dao = new CommonDao(); //数据库链接
// UpgradeService service = new UpgradeService(dao); //专属Service
// missionList.add(service.getMessionById(501l));
// MissionPollingThread thread = new MissionPollingThread ("1",1,missionList);
// thread.run();
//}
/**
* 命令执行任务执行
* @time Nov 11, 2011-6:55:33 PM
* @param mission
*/
public void forTask4(MissionStateTable mission) {
CommonDao dao = null; //数据库链接
try {
dao = new CommonDao();
UpgradeService service = new UpgradeService(dao); //专属Service
//-- 任务结果查询和推送文件
Task4 task4 = service.getTask4ById(mission.getMissionId()); //查询任务具体信息
ArrayList<MissionResult> mrList = service.getMissionResultsForTask(mission.getMissionId(),mission.getMissionType().intValue());
//-- 遍历节点结果集合
for (MissionResult result : mrList) {
//-- 针对节点 进行文件推送
Common.sendMissionInfo(mission,new NMSClientTask4(result.getNodeIp(),Constants.SSL_CLIENT_PORT,mission,task4,result),result.getUuid(), testNum,null,null);
}
} catch (Exception e) {
logger.error("Task Id:>"+mission.getMissionId()+" task execution failure", e);
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
/**周期任务代码*/
/**
* 业务梳理:
* 周期任务操作 执行操作状态为0、1 撤消操作状态为5完成状态时3 此项无需考虑)
* 执行状态时:
* 检查并初始化周期任务的轮次(有效轮次 即 轮次起始时间 大于 当前系统时间 的轮次信息条数 <=10
* 对 当前系统时间 所在的轮次的任务结果初始化
* 对 当前系统时间 所在的轮次的任务结果指定的结果节点进行下发
* 撤销状态时:
* 对 当前系统时间 所在的轮次的任务结果指定的节点,通知取消周期任务
* */
private void forLoopMission(MissionStateTable mission){
/**方法执行 参数校验*/
if(mission == null || mission.getMissionState() == null){
return ;
}
CommonDao dao = null;
SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
try {
dao = new CommonDao();
UpgradeService service = new UpgradeService(dao);
EmailService emailService = new EmailService(dao);
//- 任务参数的有效性校验
Task4 task4 = service.getTask4ById(mission.getMissionId()); //查询任务具体信息
if(task4 == null || StringUtils.isEmpty(task4.getCommandName())|| task4.getCommandType() == 0 ){
// service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" 任务参数为空,任务无法执行");
// emailService.sendEmailForMission(mission.getMissionId(),"任务执行失败"," 任务参数为空,任务无法执行");
// service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" The task parameter is empty and the task cannot be executed");
service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" i18n_server.MissionPollingThread.noParam_n81i");
// emailService.sendEmailForMission(mission.getMissionId(),"Task execution failure","The task parameter is empty and the task cannot be executed");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.MissionPollingThread.missionFail_n81i","i18n_server.MissionPollingThread.noParam_n81i");
logger.warn("The task parameter is empty and the task cannot be executed");
/***告警功能****/
return ;
}
//- 任务时间的有效性校验
if(mission.getEndTime()==null || mission.getEndTime().getTime() < System.currentTimeMillis() ){
if(mission.getMissionState().longValue() ==2l){
// service.updateMissionState(mission.getMissionId(), 3,format.format(System.currentTimeMillis())+" 已超过任务结束时间 任务已完成");
// service.updateMissionState(mission.getMissionId(), 3,format.format(System.currentTimeMillis())+" The task has exceeded the end time ,and the task execution has ended");
service.updateMissionState(mission.getMissionId(), 3,format.format(System.currentTimeMillis())+"i18n_server.MissionPollingThread.outEndTime_n81i");
// emailService.sendEmailForMission(mission.getMissionId(),"任务执行失败"," 已超过任务结束时间 任务已完成");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.MissionPollingThread.missionFail_n81i","i18n_server.MissionPollingThread.outEndTime_n81i");
logger.warn("The task has exceeded the end time ,and the task execution has ended");
}
/***告警功能****/
return ;
}
//- 任务下发 准备操作
LoopMissionRoundInfo roundInfo = null;
ArrayList<MissionResult> mrList = null;
//- 任务状态判断 已创建1 执行中2 准备撤销5 撤销中6
logger.debug(mission.getMissionId()+" 周期任务状态"+" "+mission.getMissionState());
mission.setNodeGroupsId(task4.getNodeGroupsId()); //保存节点组信息
mission.setNodeIpsId(task4.getNodeIpsId()); //保存节点信息
//-- 已创建操作1
if (mission.getMissionState().longValue() == 1l){ //新任务(已创建)的任务下发操作
service.checkAndInitMissionCycle(mission);// 轮次校验和初始化
List<LoopMissionRoundInfo> roundInfoList = Common.getLoopMissionRoundInfoList().get(mission.getMissionId());
//-- 获取当前轮次信息并初始化当前轮次的任务结果信息
if(roundInfoList !=null && roundInfoList.size()>0){
//-- 获取当前周期轮次
for (Iterator<LoopMissionRoundInfo> roundIte = roundInfoList.iterator(); roundIte.hasNext();) {
roundInfo = roundIte.next();
if(roundInfo.getEndTime().getTime() > System.currentTimeMillis()){
break;
}
}
//-- 预置状态的轮次,初始化当前轮次的结果数据
if(roundInfo!=null && roundInfo.getMissionState()!=null && roundInfo.getMissionState().longValue()==0l){ //0 预置状态,未初始化当前轮次的任务结果信息
service.initLoopMissionResults2(roundInfo.getCurMissionId(), task4.getNodeGroupsId(),task4.getNodeIpsId(),3);//初始化可下发的结果信息 3 未下发
// service.updateLoopMissionState(roundInfo.getCurMissionId(), 2); //更新 任务轮次信息状态
roundInfo.setMissionState(2l); //更新缓存中的任务轮次信息状态
mrList = service.getMissionResultsForTask(roundInfo.getCurMissionId(),mission.getMissionType().intValue());
}else{
}
}
//任务状态变更
// if(mrList== null || mrList.size()==0){ //未初始化到当前轮次的结果信息
//
// //- 变更任务状态 1以创建 -> 4未能执行
// service.updateMissionState(mission.getMissionId(), 4,format.format(System.currentTimeMillis())+" 未初始化到可下发节点的结果信息,任务无法执行");
// mission.setMissionState(4l);
// return;
// }else{
// }
//- 变更任务状态 1以创建 -> 2正在执行
// service.updateMissionState(mission.getMissionId(), 2,format.format(System.currentTimeMillis())+" 任务执行开始");
service.updateMissionState(mission.getMissionId(), 2,format.format(System.currentTimeMillis())+" i18n_server.MissionPollingThread.missionExec_n81i");
// emailService.sendEmailForMission(mission.getMissionId(),"任务执行通知"," 任务执行开始");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.MissionPollingThread.missionExecNotice_n81i"," i18n_server.MissionPollingThread.missionExec_n81i");
mission.setMissionState(2l);
Common.getLoopMissionInfoMap().put(mission.getMissionId(), mission);
}
//-- 执行中操作2
else if (mission.getMissionState().longValue() == 2l){ //未完成任务下发操作
//-- 获取未下发的节点信息
mrList = service.getMissionResultsForLoopTask(mission.getMissionId(),mission.getMissionType().intValue(),3);
if(mrList == null || mrList.size() == 0){
return ;
}
}
//-- 准备撤销5
else if (mission.getMissionState().longValue() == 5l){ //撤销任务下发操作 (获取当前操作周期或最后一个非初始化周期的轮次信息)
logger.debug("周期任务 撤销操作");
//-- 整理周期任务信息
service.checkAndInitMissionCycle(mission);// 轮次校验和初始化
List<LoopMissionRoundInfo> roundInfoList = Common.getLoopMissionRoundInfoList().get(mission.getMissionId());
//-- 获取当前轮次信息并初始化当前轮次的任务结果信息
if(roundInfoList !=null && roundInfoList.size()>0){
//-- 获取当前周期轮次
for (Iterator<LoopMissionRoundInfo> roundIte = roundInfoList.iterator(); roundIte.hasNext();) {
roundInfo = roundIte.next();
if(roundInfo.getEndTime().getTime() > System.currentTimeMillis()){
break;
}
}
//-- 旧轮次信息状态记录
int oldRoundState = roundInfo.getMissionState()==null?0:roundInfo.getMissionState().intValue();
//-- 将当前周期状态 变更为撤销准备周期
service.updateLoopMissionState(roundInfo.getCurMissionId(),5);
//-- 删除预置周期
service.deleteLoopMissionPreset(mission.getMissionId(),roundInfo.getCurMissionId());
//-- 更新缓存轮次信息
service.updateLoopMissionRoundInfo(Common.getLoopMissionRoundInfoList(), mission.getMissionId());
//-- 将撤销周期的结果数据进行状态初始化
if(oldRoundState == 0){ //预置周期无结果
service.initLoopMissionResults2(roundInfo.getCurMissionId(), task4.getNodeGroupsId(),task4.getNodeIpsId(),5);//初始化可下发的结果信息 5 撤销未下发
}else if(oldRoundState>0){ //存在结果的周期 及2或3
service.updateMissionResultsResult(roundInfo.getCurMissionId(), 4, 5);
}
}
//-- 获取未下发的节点信息
mrList = service.getMissionResultsForLoopTask(mission.getMissionId(),mission.getMissionType().intValue(),5);
if(mrList == null || mrList.size() == 0){
//-- 将周期状态变更为7 完成
service.updateLoopMissionState(roundInfo.getCurMissionId(), 7); //完成 任务轮次信息状态
roundInfo.setMissionState(7l); //更新缓存中的任务轮次信息状态
return ;
}else{
//-- 将周期状态变更为6 开始执行
service.updateLoopMissionState(roundInfo.getCurMissionId(), 6); //更新 任务轮次信息状态
roundInfo.setMissionState(6l); //更新缓存中的任务轮次信息状态
}
//- 变更任务状态 5准备撤销 -> 6撤销执行
// service.updateMissionState(mission.getMissionId(), 6,format.format(System.currentTimeMillis())+" 任务撤销开始");
// service.updateMissionState(mission.getMissionId(), 6,format.format(System.currentTimeMillis())+" Task revocation start");
service.updateMissionState(mission.getMissionId(), 6,format.format(System.currentTimeMillis())+" i18n_server.MissionPollingThread.missionRevoke_n81i");
mission.setMissionState(6l);
// emailService.sendEmailForMission(mission.getMissionId(),"任务执行通知"," 任务撤销开始");
// emailService.sendEmailForMission(mission.getMissionId(),"Task execution notice"," Task revocation start");
emailService.sendEmailForMission(mission.getMissionId(),"i18n_server.MissionPollingThread.missionExecNotice_n81i"," i18n_server.MissionPollingThread.missionRevoke_n81i");
}
//-- 撤销中操作6
else if (mission.getMissionState().longValue() == 6l){ //未完成任务下发操作
//-- 获取未下发的节点信息
mrList = service.getMissionResultsForLoopTask(mission.getMissionId(),mission.getMissionType().intValue(),5);
if(mrList == null || mrList.size() == 0){
service.updateLoopMissionComplete();
return ;
}
}else{
return;
}
//-- 将任务信息存入Map
Common.getLoopMissionInfoMap().put(mission.getMissionId(), mission);
task4.setNodeGroupsId(null); //抹掉 节点组 信息
LoopMissionRoundInfo roundInfo0 = null;
if(mrList==null){
return;
}
for (MissionResult result : mrList) {
//-- 执行成功的结果 不再重复下发,跳过执行
if(result.getResult() != null && result.getResult().longValue() == 0l){
continue;
}
roundInfo0 = service.getRoundInfoFromCommonListByID(mission.getMissionId(), result.getMissionId());
//从数据库中获取roundInfo
if(roundInfo0 == null){
roundInfo0 = service.getRoundInfoFromDBByID(result.getMissionId());
//将roundInfo0保存到list中
if(roundInfo0 != null){
List<LoopMissionRoundInfo> list0 = Common.getLoopMissionRoundInfoList().get(mission.getMissionId());
if(list0== null){
list0 = new LinkedList<LoopMissionRoundInfo>();
Common.getLoopMissionRoundInfoList().put(mission.getMissionId(),list0);
}
list0.add(0,roundInfo0);
}else{
continue;
}
}
//-- 针对节点 进行文件推送
if(mission.getMissionState().longValue() == 6l){
Common.sendMissionInfo(mission,new NMSClientTask4Cancel(result.getNodeIp(),Constants.SSL_CLIENT_PORT,mission.getMissionId()),result.getUuid(), testNum,roundInfo0.getStartTime().getTime(),roundInfo0.getEndTime().getTime());
}else if(mission.getMissionState().longValue() == 2l){
Common.sendMissionInfo(mission, new NMSClientTask4(result.getNodeIp(),Constants.SSL_CLIENT_PORT,mission,task4,result),result.getUuid(), testNum,roundInfo0.getStartTime().getTime(),roundInfo0.getEndTime().getTime());
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
/**
* 升级任务任务执行
* @time Nov 11, 2011-6:55:33 PM
* @param mission
*/
public void forTask6(MissionStateTable mission) {
CommonDao dao = null; //数据库链接
try {
dao = new CommonDao();
UpgradeService service = new UpgradeService(dao); //专属Service
//-- 任务结果查询和推送文件
Task6 task6 = service.getTask6ById(mission.getMissionId()); //查询任务具体信息
List<FileComment> fileCommentsList = service.getMissionFileInformations(mission.getMissionId());
task6.setNodeGroupsId(null); //抹掉 节点组 信息
ArrayList<MissionResult> mrList = service.getMissionResultsForTask(mission.getMissionId(),mission.getMissionType().intValue());
//-- 遍历节点结果集合
if(task6.getVersion()!=null && task6.getVersion().longValue()!=0){ //逆向任务下发
for (MissionResult result : mrList) {
Common.sendMissionInfo(mission, new NMSClientTask6Cover(result.getNodeIp(),Constants.SSL_CLIENT_PORT,mission,task6,result,fileCommentsList),result.getUuid(), testNum,null , null);
}
}else{ //升级部署任务
for (MissionResult result : mrList) {
Common.sendMissionInfo(mission, new NMSClientTask6(result.getNodeIp(),Constants.SSL_CLIENT_PORT,mission,task6,result,fileCommentsList),result.getUuid(), testNum,null , null);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
}

View File

@@ -0,0 +1,208 @@
package com.nms.server.thread.mission;
import java.io.File;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.concurrent.Future;
import org.apache.log4j.Logger;
import com.nms.server.bean.MissionResult2;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.FileUtils;
public class MissionResultManagerThread implements Runnable{
private Logger logger = Logger.getLogger(MissionResultManagerThread.class);
private int testNum = 0;//尝试运行线程Constants.ALARM_DATA_RESOVE的次数
@Override
public void run() {
//将线程运行程序尽可能的catch捕获异常
try {
// Thread.currentThread().setName("任务结果入库管理线程");
Thread.currentThread().setName("Task Result Library Management Thread");
boolean runFlag = true;
//- 检查线程运行状态 运行中无操作
Future<?> future = Common.getFutureMap().get(Constants.MISSION_RESULT_RESOVE);
if(future != null && !future.isCancelled() && !future.isDone()){ //运行中
runFlag = false;
logger.info("任务结果入库线程 运行中 不再启动新线程");
}
//测试数据库连接
runFlag = Common.isDbConnected();
/*
* 连续超过Constants.CHECK_WARNING_DATA_OVERRUN次数时将数据存入硬盘中
* 否则 正常执行数据解析线程
* */
if(!runFlag){ //判断并结束线程
testNum = (testNum%Constants.CHECK_RESULT_DATA_OVERRUN);
testNum++;
if(testNum==Constants.CHECK_RESULT_DATA_OVERRUN) {
if(Constants.FLAG_TASK_RLT_SAVE_DISK_RESOVE==1) {
/*
* 连续多个周期仍未解析完成
* 说明list里存有大量的数据则先将当前未解析的数据列表存入硬盘
* 然后停掉解析线程,将正在解析的数据列表中的剩余数据存入硬盘
* */
logger.warn("Create a database connection failure data to write to the hard disk");
saveResultDataToDisk();
}
}
return;
}else{ //重置计数器 程序继续执行
testNum = 1;
}
//- 非升级操作判断
if(Common.SERVER_UN_UPGRADE_FLAG){
logger.info("任务结果入库线程 空闲中 启动新解析线程");
//-- 获取线程执行 需进行主动告警和邮件通知等相关操作,待考虑
// future = Common.service.submit(new MissionResultThread("任务结果入库线程"));
future = Common.service.submit(new MissionResultThread("Task Result Database Thread"));
//注册
Common.getFutureMap().put(Constants.MISSION_RESULT_RESOVE, future);
}
logger.info("执行结束");
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}
}
/**
* 数据库是否可连接判断
* @time Mar 7, 2013-2:22:42 PM
* @return
*/
public boolean dbTest() {
/*
* 数据库是否可连接判断
* 是:进行数据解析
* 否:否进行数据处理解析
* */
CommonDao dao = null;
try {
// if(!false)throw new Exception("强制异常");
dao = new CommonDao();
logger.debug("尝试获取数据库连接成功");
return true;
} catch (Exception e) {
logger.error("Try to get a database connection failure", e);
/* 告警 */
return false;
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
//2013-2-19 hyx :当任务结果数据量过大时,将数据先存放到硬盘,再定时入库(由单独的定时线程实现)
public void saveResultDataToDisk() {
try {
//终止正在解析告警数据的线程并将正在解析的list里未解析的数据存入硬盘
Future<?> future = Common.getFutureMap().get(Constants.MISSION_RESULT_RESOVE);
if(future != null && !future.isCancelled() && !future.isDone()){ //运行中
future.cancel(true);//停解析任务结果数据入库线程
}
for(int i=1 ;i<=6 ; i++){
//-- 获取结果集合
LinkedList<MissionResult2> result = Common.getResultListClone(i);
//-- 集合不为空则进行解析 存在removeList情况 ,优化方式可参考 监测数据解析的实现方式
if(result!=null && result.size()>0){
//将未在解析的list存放到硬盘上
saveMissObjToFile(result,i);
result.clear(); //清除mr2List
}
}
}catch(IndexOutOfBoundsException e) {
logger.error("When the result data is too much, the data is stored in the hard disk exception",e);
}catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}
}
//写一个任务对象到一个文件后,清除列表里的这个任务对象
public void saveMissObjToFile(LinkedList<MissionResult2> missObjList,int missionType) {
String filePath = "";
int missObjSize = missObjList.size();//如果不按此时的size来操作则list里的数据可能会一直在增加就会一直循环下去
try {
String parPath = Constants.OVERRUN_RESULT_FILE_DIR.substring(0,Constants.OVERRUN_RESULT_FILE_DIR.length()-1);
LinkedList<MissionResult2> tmpList = new LinkedList<MissionResult2>();
for(int j=0;j<missObjSize;j++) {
MissionResult2 result= missObjList.get(j);
filePath = parPath+"/missionResult"+missionType+"/"+Common.getDateDirName()+"/"+Calendar.getInstance().getTimeInMillis()+"_"+j+".result";
File file = new File(filePath);
FileUtils.writeObjToFile(result, file);
//在Common中删除掉已保存到硬盘的任务结果(其实就一个任务结果对象)
tmpList.add(result);
Common.removeResultsFormList(missionType, tmpList);
tmpList.clear();
logger.info("任务结果数据过多,已保存至"+filePath);
}
}catch(Exception e) {
logger.error("When the result data is too much, the data is stored in the hard disk exception",e);
}
}
public static void main(String[] args) {
LinkedList<MissionResult2> ml = new LinkedList<MissionResult2>();
MissionResult2 m1 = new MissionResult2();
m1.setUuid(1l);
// m1.setDescription("描述1-desc");
// m1.setDescription("Description 1-desc");
m1.setDescription("i18n_server.MissionResultManagerThread.desc_n81i 1-desc");
m1.setMissionType(1l);
MissionResult2 m2 = new MissionResult2();
m2.setUuid(2l);
// m2.setDescription("描述2-desc");
// m2.setDescription("Description 2-desc");
m2.setDescription("i18n_server.MissionResultManagerThread.desc_n81i 2-desc");
m2.setMissionType(1l);
MissionResult2 m3 = new MissionResult2();
m3.setUuid(3l);
// m3.setDescription("描述3-desc");
// m3.setDescription("Description 3-desc");
m3.setDescription("i18n_server.MissionResultManagerThread.desc_n81i 3-desc");
m3.setMissionType(1l);
// ml.add(m1);
// ml.add(m2);
// ml.add(m3);
// new MissionResultManagerThread().saveMissObjToFile(result,1);
Common.addResultToResultList(m1);
Common.addResultToResultList(m2);
Common.addResultToResultList(m3);
LinkedList<MissionResult2> result = Common.getResultListClone(1);
//-- 集合不为空则进行解析 存在removeList情况 ,优化方式可参考 监测数据解析的实现方式
if(result!=null && result.size()>0){
//将未在解析的list存放到硬盘上
new MissionResultManagerThread().saveMissObjToFile(result,1);
// Common.removeResultsFormList(1, result); //在Common中删除掉已保存到硬盘的任务结果
result.clear(); //清除mr2List
}
}
}

View File

@@ -0,0 +1,228 @@
package com.nms.server.thread.mission;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.MissionResult2;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.UpgradeService;
import com.nms.server.util.BoneCPPool;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.StringUtil;
/**
* 任务结果处理线程
* @date Nov 16, 2011 1:25:26 PM
* @author ZhangGang
*
*/
public class MissionResultThread implements Runnable{
private Logger logger = Logger.getLogger(MissionResultThread.class);
private String name;
volatile boolean stop = false;//线程是否被取消标志
public MissionResultThread (String name){
this.name= name;
}
public void run() {
Thread.currentThread().setName(name);
boolean upFlag = false;
boolean loopFlag = false;
CommonDao dao = null; //数据库链接
try {
dao = new CommonDao();
UpgradeService service = new UpgradeService(dao); //专属Service
//-- 获取1-6 五种任务类型的结果集合,批量入库保存
for(int i=1 ;i<=6&&!stop ; i++){
try {
//-- 获取结果集合
LinkedList<MissionResult2> mr2List = Common.getResultListClone(i);
//-- 集合不为空则进行解析 存在removeList情况 ,优化方式可参考 监测数据解析的实现方式
if(mr2List!=null && mr2List.size()>0){
upFlag = true; // 开启任务是否完成的检查操作
service.updateMissionResult2ByBatch(i,mr2List); //保存mr2List中的数据
Common.removeResultsFormList(i, mr2List); //在Common中删除掉已保存的任务结果
//更新mission_state_table表里的mission_state_desc字段只对新录入结果的任务更新没录入任务结果的任务不需要更新
service.updateCommonMissionStateDesc(i,mr2List);//i代表任务类型1,4,6-非周期任务
if (i==4){
loopFlag = true; // 开启周期任务是否完成的检查操作
service.updateLoopMissionStateDesc(mr2List);//更新任务类型4的周期任务的状态描述
}
dao.commit();
mr2List.clear(); //清除mr2List
}
}catch (InterruptedException e) {
logger.error("Task result data parsing thread is interrupted",e);
stop = true;
}catch (Exception e1) {
logger.error("The task result data parsing thread ,which is abnormal when task type "+i+" is parsed ,ends the entry of the result of this type of task,and continues to enter the result of the next type of task",e1);
}
//判断当前线程是否被中断
if (Thread.currentThread().isInterrupted()) {
// 线程中断状态,不会改变中断状态的值
logger.info("任务结果数据解析线程 被中断");
stop = true;
}
}
//-- 任务执行进度校验,并更新已完成任务
if(upFlag){
// service.checkAndUpdateMissionComplete();//任务状态完成3
service.updateCommonMissionComplete();//任务状态成功31、部分成功32、全部失败30
if(loopFlag){
// service.checkAndUpdateLoopMissionComplete();--此方法有问题
service.updateLoopMissionComplete();
}
}
/**
* 针对过期未完成的【周期】任务进行清理非周期任务不需要清理因为没有结束时间endTime所以不会超时
* 1.会不会重复添加过期任务呢?-不会因为此处将结果加入缓存后会先执行上面的结果录入和任务状态的改变再执行过期任务清理时之前的过期任务的状态已修改为3或者7不会被统计
* 2.清理时将超时的任务mission_state_table表中state=2或者6的且endTime小于当前时间的的结果存入缓存(Common.addResultToResultList)
* 3.对于过期的周期任务:
* 除了修改周期结果的状态3->1
* 还需要修改loopmission_state_table表的状态(2->3或者6->7,对于状态为0的不需要修改因为界面不会显示更新状态时也不会统计)
* 及mission_state_table的状态(2->3或者6->7对于1的情况在初始化任务时已经做过超时检查了初始化后任务的状态变为2了就所以此处不用对1的做超时检查)
* 注将过期周期任务结果存入缓存后上面进行统计时就会根据结果的状态统计loop表的状态及mission_state_table表的状态所以步骤3的3个修改我们只需要做第一步将结果存入缓存
*
*/
service.checkTimeoutLoopMisssionAndAddResult();
// SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
// Date date = format.parse(Constants.MISSION_LOOP_FINISHING_DAILY);
// System.out.println(format.format(new Date()));
// if(loopFinishingFlag && ){
// service.checkAndUpdateLoopMissionComplete();
// }else{
//
// }
/**
* 对于执行任务节点网络都不通的情况,第一周期之后就不会有结果入库,所以要定期的执行,不能加有周期结果入库的条件才操作
* 将下发失败的节点再次下发(包括部分不通及全部不通的所有任务)
*/
List<String> missIds = service.checkLoopMissAssignFail();//统计周期任务中,执行节点全都不通的情况
if(missIds!=null && missIds.size()>0) {
Common.addAllAssignFailMissionIds(missIds);
}
String[] idsTmp = new String[0];
idsTmp = Common.getAssignFailMissIds().toArray(idsTmp);
String assignFailMissionIds = StringUtil.linkToString(idsTmp, ",", "");
if(StringUtils.isNotBlank(assignFailMissionIds)) {
//下发的时候会过滤只下发result=3的
Common.scheduled.schedule(new InitRunningMissionThread(assignFailMissionIds),Constants.MISSION_FIRST_START, TimeUnit.SECONDS);
Common.removeAllAssignFailMissionIds();
}
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
try {
if(dao!=null)dao.rollback();
} catch (Exception e1) {
logger.error(ExceptionPrintUtils.printExceptionStack(e1));
}
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
}
public static void main(String[] args) {
// LinkedList<String> lks = new LinkedList<String>();
// lks.add("1");
// lks.add("2");
// lks.add("3");
//
// LinkedList<String> lks2 = null;
// lks2 = (LinkedList<String>)lks.clone();
// for(String s:lks2) {
// System.out.println(s);
// }
//
// lks.add("4");
// lks.set(0, "00");
//
// lks2.remove(0);
// for(String s:lks2) {
// System.out.println(s);
// }
//
// for(String s:lks) {
// System.out.println(s);
// }
String data = "2695$@$4$@$58$@$0$@$1365574748735$@$1365574761781$@$$@$1$@$执行失败,详细信息如下:执行“/home/xian/hello.sh”失败结果文件“/home/xian/3.txt”不存在;";
CommonDao dao = null; //数据库链接
try {
// String [] result = data.split(Constants.COMMON_DATA_SPLIT);
// MissionResult2 result2 = Common.resoveMissionResult(result);
// Common.addResultToResultList(result2);
//
// Common.service.submit(new MissionResultThread("test"));
BoneCPPool.initPool();
dao = new CommonDao();
UpgradeService service = new UpgradeService(dao); //专属Service
// service.checkTimeoutLoopMisssionAndAddResult();
List<String> missIds = service.checkLoopMissAssignFail();//统计周期任务中,执行节点全都不通的情况
if(missIds!=null && missIds.size()>0) {
Common.addAllAssignFailMissionIds(missIds);
}
Common.addAssignFailMissionIds("5122");
String[] idsTmp = new String[0];
idsTmp = Common.getAssignFailMissIds().toArray(idsTmp);
String assignFailMissionIds = StringUtil.linkToString(idsTmp, ",", "");
if(StringUtils.isNotBlank(assignFailMissionIds)) {
//下发的时候会过滤只下发result=3的
Common.scheduled.schedule(new InitRunningMissionThread(assignFailMissionIds),Constants.MISSION_FIRST_START, TimeUnit.SECONDS);
Common.getAssignFailMissIds().clear();
}
} catch (Exception e) {
e.printStackTrace();
}
//
// Future<?> future2 = Common.service.submit(new MissionResultThread("任务结果入库线程"));
// Common.getFutureMap().put(Constants.MISSION_RESULT_RESOVE, future2);
//
// System.out.println("启动ok。。。");
//
// Future<?> future = Common.getFutureMap().get(Constants.MISSION_RESULT_RESOVE);
// System.out.println(future.isCancelled());
// System.out.println(future.isDone());
// try
// {
//// Thread.sleep(1000);
// if(future!=null&&!future.isCancelled()&&!future.isDone()) {
// System.out.println("开始中断。。。");
// Thread.sleep(536);//这个时间是经过多次测试出来的
// // Thread.sleep(100);
// future.cancel(true);//停解析任务结果数据入库线程
// }
// Thread.sleep(3000);
// Common.service.shutdownNow();
// System.out.println(future.isCancelled());
// System.out.println(future.isDone());
// } catch (InterruptedException e)
// {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
}
}

View File

@@ -0,0 +1,74 @@
package com.nms.server.thread.mission;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.MissionStateTable;
import com.nms.server.bean.Task1;
import com.nms.server.common.Constants;
import com.nms.server.util.socket.SSLSocketCallable;
import com.socket.utils.FileComment;
public class NMSClientTask1 extends SSLSocketCallable{
private final Logger logger = Logger.getLogger(NMSClientTask1.class);
private Task1 task1 ;
private MissionStateTable mission;
private List<FileComment> fileCommentsList;
public NMSClientTask1(String ip,int port,MissionStateTable mission,Task1 object,List<FileComment> fileCommentsList) throws Exception{
super(ip,port);
this.task1 = object;
this.mission = mission;
this.fileCommentsList = fileCommentsList;
}
@Override
protected String toDo() throws Exception {
try {
Thread.currentThread().setName("Task:> "+mission.getMissionId()+" IP:> "+this.socket.getRemoteSocketAddress());
task1.setTaskId(mission.getMissionId());
task1.setTaskType(mission.getMissionType());
StringBuffer warnInfo = new StringBuffer("");
int trueFileSize = 0;
List<FileComment> clone = new LinkedList<FileComment>();
for(FileComment strs :fileCommentsList){
FileComment cloneStrs = new FileComment();
BeanUtils.copyProperties(cloneStrs,strs);
cloneStrs.setFileName(Constants.MISSION_FILE_DOWNLOAD_DIR+File.separator+cloneStrs.getFileName());
File file = new File(cloneStrs.getFileName());
if(!file.exists()){
trueFileSize++;
warnInfo.append((file.getAbsolutePath())+" 文件不存在\n");
logger.warn("File does not exist "+(file.getAbsolutePath()));
}
clone.add(cloneStrs);
}
if(trueFileSize!=0){
return "1:"+warnInfo;
}
JSONObject object = new JSONObject();
object.put("typeInfo", mission.getMissionType());
object.put("taskInfo", task1);
logger.debug("JSONObject "+object.toString());
this.sendMessage("byte:filePush");
this.receiveMessage();
this.sendMessage(object.toString());
this.receiveMessage();
this.bpSendFileByBathMD5(clone);
String string = this.receiveMessage();
logger.debug("文件推送结果数据 "+string);
this.sendMessage(SUCCESS);
return string;
} catch (Exception e) {
logger.error("File push failed",e);
return null;
}
}
}

View File

@@ -0,0 +1,72 @@
package com.nms.server.thread.mission;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import com.nms.server.bean.MissionResult;
import com.nms.server.bean.MissionStateTable;
import com.nms.server.bean.Task4;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.socket.SSLSocketCallable;
public class NMSClientTask4 extends SSLSocketCallable{
private final Logger logger = Logger.getLogger(NMSClientTask4.class);
private Task4 task4 ;
private MissionStateTable mission;
private MissionResult result;
public NMSClientTask4(String ip,int port,MissionStateTable mission,Task4 object, MissionResult result) throws Exception{
super(ip,port);
this.task4 = object;
this.mission = mission;
this.result = result;
}
@Override
protected String toDo() throws Exception {
Thread.currentThread().setName("Task 4:> "+mission.getMissionId()+" IP:> "+this.socket.getRemoteSocketAddress());
try {
//任务正常下发
task4.setTaskId(mission.getMissionId());
task4.setTaskType(mission.getMissionType());
task4.setStartTime(mission.getStartTime()==null?null:mission.getStartTime().getTime());
task4.setEndTime(mission.getEndTime()==null?null:mission.getEndTime().getTime());
task4.setState(result.getResult());
task4.setIsLoop(mission.getLoopFlag());
task4.setLoopDelay(mission.getLoopDelay());
task4.setMissionState(mission.getMissionState());
JSONObject object = new JSONObject();
object.put("typeInfo", mission.getMissionType());
object.put("taskInfo", task4);
logger.debug("JSONObject "+object.toString());
this.sendMessage("char:task");
this.receiveMessage();
this.sendMessage(object.toString());
String string = this.receiveMessage();
logger.debug("任务执行下发结果是 "+string);
this.sendMessage(SUCCESS);
return string;
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
return null;
}
}
/*
public static void main(String []args){
CommonDao dao = new CommonDao(); //数据库链接
UpgradeService service = new UpgradeService(dao); //专属Service
try {
Task4 task4 = service.getTask4ById(1274540l); //查询任务具体信息
MissionStateTable table = service.getMessionById(1274540l);
List<MissionResult> list = service.getMissionResultsForTask(1274540l, 4);
MissionResult result = list.get(0);
result.setResult(3l);
Common.service.submit(new NMSClientTask4("10.0.6.242",60701,table,task4, result));
}catch (Exception e) {
e.printStackTrace();
}
}*/
}

View File

@@ -0,0 +1,35 @@
package com.nms.server.thread.mission;
import org.apache.log4j.Logger;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.socket.SSLSocketCallable;
public class NMSClientTask4Cancel extends SSLSocketCallable{
private final Logger logger = Logger.getLogger(NMSClientTask4Cancel.class);
private long missionId;
public NMSClientTask4Cancel(String ip,int port,long missionId) throws Exception{
super(ip,port);
this.missionId = missionId;
}
@Override
protected String toDo() throws Exception {
Thread.currentThread().setName("Task 4:> "+missionId+" IP:> "+this.socket.getRemoteSocketAddress());
try {
//撤销任务
this.sendMessage("char:taskCancel");
this.receiveMessage();
this.sendMessage(missionId+"");
String string = this.receiveMessage();
logger.debug("任务执行下发结果是 "+string);
this.sendMessage(SUCCESS);
return string;
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
return null;
}
}
}

View File

@@ -0,0 +1,82 @@
package com.nms.server.thread.mission;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.MissionResult;
import com.nms.server.bean.MissionStateTable;
import com.nms.server.bean.Task6;
import com.nms.server.common.Constants;
import com.nms.server.util.socket.SSLSocketCallable;
import com.socket.utils.FileComment;
public class NMSClientTask6 extends SSLSocketCallable{
private final Logger logger = Logger.getLogger(NMSClientTask6.class);
private Task6 task6 ;
private MissionStateTable mission;
private MissionResult result;
private String ip;
private List<FileComment> fileCommentsList;
public NMSClientTask6(String ip,int port,MissionStateTable mission,Task6 object, MissionResult result,List<FileComment> fileCommentsList) throws Exception{
super(ip,port);
this.ip = ip;
this.task6 = object;
this.mission = mission;
this.result = result;
this.fileCommentsList = fileCommentsList;
}
@Override
protected String toDo() throws Exception {
Thread.currentThread().setName("Task 6 id:> "+mission.getMissionId()+" IP:> "+this.socket.getRemoteSocketAddress());
try {
//-- 补全任务信息
task6.setTaskId(mission.getMissionId());
task6.setTaskType(mission.getMissionType());
task6.setState(result.getResult());
//-- 任务信息整理
StringBuffer warnInfo = new StringBuffer("");
int trueFileSize = 0;
List<FileComment> clone = new LinkedList<FileComment>();
if(fileCommentsList !=null && fileCommentsList.size()>0){
for(FileComment strs :fileCommentsList){
FileComment cloneStrs = new FileComment();
BeanUtils.copyProperties(cloneStrs,strs);
cloneStrs.setFileName(Constants.MISSION_FILE_DOWNLOAD_DIR+File.separator+cloneStrs.getFileName());
File file = new File(cloneStrs.getFileName());
if(!file.exists()){
trueFileSize++;
warnInfo.append((file.getAbsolutePath())+" 文件不存在\n");
logger.warn("File does not exist "+(file.getAbsolutePath()));
}
clone.add(cloneStrs);
}
}
if(trueFileSize!=0){
return "1:"+warnInfo;
}
JSONObject object = new JSONObject();
object.put("typeInfo", mission.getMissionType());
object.put("taskInfo", task6);
logger.debug("JSONObject "+object.toString());
this.sendMessage("byte:upgrade");
this.receiveMessage();
this.sendMessage(object.toString());
this.receiveMessage();
this.bpSendFileByBathMD5(clone);
String string = this.receiveMessage();
logger.debug("升级部署之文件推送结果 "+string);
this.sendMessage(SUCCESS);
return string;
} catch (Exception e) {
logger.error("Upgrade deployment failure",e);
return null;
}
}
}

View File

@@ -0,0 +1,57 @@
package com.nms.server.thread.mission;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import com.nms.server.bean.MissionResult;
import com.nms.server.bean.MissionStateTable;
import com.nms.server.bean.Task6;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.socket.SSLSocketCallable;
import com.socket.utils.FileComment;
public class NMSClientTask6Cover extends SSLSocketCallable{
private final Logger logger = Logger.getLogger(NMSClientTask6Cover.class);
private Task6 task6 ;
private MissionStateTable mission;
private MissionResult result;
private String ip;
private List<FileComment> fileCommentsList;
public NMSClientTask6Cover(String ip,int port,MissionStateTable mission,Task6 object, MissionResult result,List<FileComment> fileCommentsList) throws Exception{
super(ip,port);
this.ip = ip;
this.task6 = object;
this.mission = mission;
this.result = result;
this.fileCommentsList = fileCommentsList;
}
@Override
protected String toDo() throws Exception {
Thread.currentThread().setName("Task 6 id:> "+mission.getMissionId()+" IP:> "+this.socket.getRemoteSocketAddress());
try {
//-- 补全任务信息
task6.setTaskId(mission.getMissionId());
task6.setTaskType(mission.getMissionType());
task6.setState(result.getResult());
JSONObject object = new JSONObject();
object.put("typeInfo", mission.getMissionType());
object.put("taskInfo", task6);
logger.debug("JSONObject "+object.toString());
this.sendMessage("char:task");
this.receiveMessage();
this.sendMessage(object.toString());
String string = this.receiveMessage();
logger.debug("升级部署之文件推送结果 "+string);
this.sendMessage(SUCCESS);
return string;
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
return null;
}
}
}

View File

@@ -0,0 +1,190 @@
package com.nms.server.thread.monitor;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import com.nms.server.bean.NodeModel;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;
import com.nms.server.service.CommonService;
import com.nms.server.service.ThreadService;
import com.nms.server.thread.InitServerThread;
import com.nms.server.util.BoneCPPool;
public class MonitorManagerThread implements Runnable{
private Logger logger = Logger.getLogger(MonitorManagerThread.class);
private String name;
private final int socketPort = Constants.SSL_CLIENT_PORT;
private long startTime = Calendar.getInstance().getTimeInMillis();
private SetInfo setInfo = null;
public MonitorManagerThread(String name,SetInfo setInfo) {
this.name = name;
this.setInfo = setInfo;
}
public static void main(String[] args) {
//把所有的监测都插入一遍只是没有初始化本DC的IP管理范围
CommonDao dao = null;
try {
BoneCPPool.initPool();
dao = new CommonDao();
CommonService commonService = new CommonService(dao);
ThreadService service = new ThreadService();
new InitServerThread().initCommonInfo(dao);
//--获取switchPort 监测配置并启动监测任务
List<SetInfo> setList = commonService.getDrivingSetInfo(Constants.DETEC_SYSTEMDATE_STR);//时钟同步
//-- Ping 监测任务启动 和 客户端启动监测任务启动
if(setList!=null && setList.size()>0){
for (Iterator setIte = setList.iterator(); setIte.hasNext();) {
SetInfo si = (SetInfo) setIte.next();
// if(si.getCheckTypeName().equalsIgnoreCase("checktype422")){
// si.setCheckTypeName("system");
// MonitorManagerThread thread = new MonitorManagerThread(si.getCheckTypeName()+"_"+si.getProcessIden(),si);
// Common.service.submit(thread);
// }
//- 创建线程
Runnable runnable = new MonitorManagerThread(si.getCheckTypeName()+"_"+si.getProcessIden(),si);
//- 添加到 定时线程池
ScheduledFuture<?> future = Common.scheduled.scheduleAtFixedRate(runnable, 0, 2, TimeUnit.MINUTES);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
// ScheduledFuture<?> fcFuture = Common.scheduled.scheduleWithFixedDelay(new DetecDataResoveManagerThread(), 15, Constants.DETEC_DATA_RESOLVE_PERIOD, TimeUnit.SECONDS);
//注册 管理线程
}
@Override
public void run() {
Thread.currentThread().setName("Monitor:"+name+"");
List<NodeModel> nodeList = null;
CommonDao dao = null;
try {
dao = new CommonDao();
CommonService service = new CommonService(dao);
nodeList = service.getNodeModelListBySetInfo(setInfo);
/*nodeList.clear();
nodeList.add(new NodeModel("10.0.9.183",0l));*/
logger.info("本次监测节点数:"+nodeList.size());
} catch (Exception e) {
logger.error("Initializing query monitoring node failure", e);
return;
}finally{
if(dao!=null){
dao.close();
dao=null;
}
}
try {
//- 将设置加入计划任务
if(Constants.DETEC_PING_STR.equalsIgnoreCase(setInfo.getCheckTypeName())){ //Ping 监测线程创建
if(nodeList!= null && nodeList.size()>0){
for(NodeModel model: nodeList){
Common.runMonitorRunnable(new PingThread(name,model.getNodeIp(),setInfo,startTime));
}
}
}else if(Constants.DETEC_NMSC_STR.equalsIgnoreCase(setInfo.getCheckTypeName())){ //NMSC 监测线程创建
if(nodeList!= null && nodeList.size()>0){
if(Constants.NETTY_SERVER_FLAG == 1 ){ //当启用 nc 主动上传 监测及 任务文件时开启
//NMSC
Common.runMonitorRunnable(new ServerNMSCThread(name,setInfo,startTime,nodeList));
}
for(NodeModel model: nodeList){
if(model.getNodeType() != null && model.getNodeType().longValue() == 1l){//非服务器节点
//SNMP校验监测
Common.runMonitorRunnable(new NMSClientForSNMPThread(name,model.getNodeIp(),setInfo,startTime));
}
}
}
}else if(Constants.DETEC_SYSTEMDATE_STR.equalsIgnoreCase(setInfo.getCheckTypeName())){ //系统时间
if(nodeList!= null && nodeList.size()>0){
if(Constants.NETTY_SERVER_FLAG == 1 ){ //当启用 nc 主动上传 监测及 任务文件时开启,根据心跳计算时间同步
Common.runMonitorRunnable(new ServerDateThread(name, setInfo, nodeList, startTime));
}else{
for(NodeModel model: nodeList){
//NMSClient 校验修正 针对于计算机 进行NMSClient校验失败后进行PING校验
// 针对于非计算机 进行SNMP监测是否启动校验
if(model.getNodeType() != null && model.getNodeType().longValue() == 0l){ //服务器节点
//NMSC
Common.runMonitorRunnable(new SystemDateThread(name,model.getNodeIp(),socketPort,setInfo,startTime));
}else{ //非服务器节点
logger.info("监测目标:"+model.getNodeIp()+" 是非服务器节点,不进行"+Constants.DETEC_SYSTEMDATE_STR+"监测");
}
}
}
}
}else if(Constants.DETEC_SWITCH_STR.equalsIgnoreCase(setInfo.getCheckTypeName())){ //SWITCH 监测线程创建
if(nodeList!= null && nodeList.size()>0){
for(NodeModel model: nodeList){
if(model.getNodeType() != null && model.getNodeType().longValue() == 1l){//交换机节点
// if(!model.getNodeIp() .equals("10.0.6.254")){
// continue;
// }
//交换机类型节点监测 SNMP校验监测
Common.runMonitorRunnable(new SwitchPortThread(name,model.getNodeIp(),setInfo,startTime));
}else{ //计算机类型校验
logger.info("监测目标:"+model.getNodeIp()+" 不是交换机,无法进行监测");
}
}
}
}else if(Constants.DETEC_SYSTEM_STR.equalsIgnoreCase(setInfo.getCheckTypeName())){ //system 监测线程创建--预置的属于snmp监测
if(nodeList!= null && nodeList.size()>0){
for(NodeModel model: nodeList){
if(model.getNodeType() != null && model.getNodeType().longValue() != 0l){ //非服务器节点
Common.runMonitorRunnable(new SNMP4JThread(name,model.getNodeIp(),setInfo,startTime));
}else{ //计算机类型校验
logger.info("监测目标:"+model.getNodeIp()+" 是服务器节点,不进行该类监测");
}
}
}
}
else if(setInfo.getIsSNMP()!= null && setInfo.getIsSNMP().longValue()==1){ //SNMP4j 监测线程创建--针对的是非预置的监测
if(nodeList!= null && nodeList.size()>0){
for(NodeModel model: nodeList){
Common.runMonitorRunnable(new SNMP4JThread(name,model.getNodeIp(),setInfo,startTime));
}
}
}
else if(setInfo.getIsSNMP()!= null && setInfo.getIsSNMP().longValue()==0){ //ObjectSNMP 监测线程创建
if(nodeList!= null && nodeList.size()>0){
for(NodeModel model: nodeList){
Common.runMonitorRunnable(new SNMP4JThread(name,model.getNodeIp(),setInfo,startTime));
}
}
}
} catch (Exception e) {
logger.error("", e);
}
}
}

View File

@@ -0,0 +1,439 @@
package com.nms.server.thread.monitor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.Socket;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.snmp4j.Target;
import org.snmp4j.mp.SnmpConstants;
import com.nms.server.bean.AlarmInfo;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.CSVUtils;
import com.nms.server.util.DateUtil;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.SNMP4JUtils;
/**
* 监测数据
* 监测NMSClient端是否执行执行线程
* @author ZhangGang
*
*/
public class NMSClientForSNMPThread implements Runnable{
private Logger logger = Logger.getLogger(NMSClientForSNMPThread.class);
private SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
private String name;
private String ip;
private int port = Constants.SNMP_CLIENT_PORT;
private String checkTypeName = null;
private Long startTime = null;
private Long sitInfoId = null;
private long outTime = 2;
private long maxTimes = 3;
private long gap = 0 ;
protected Socket socket = null; //Socket
private String processIden = null;
private CountDownLatch downLatch = null;
/**
* 构造方法
* @param name 线程名称
* @param ip 被监测端IP
* @param port socket通信端口
* @param info
*/
public NMSClientForSNMPThread(String name,String ip,SetInfo info,Long startTime,CountDownLatch downLatch) {
this.name = name;
this.ip = ip;
this.sitInfoId = info.getId();
this.checkTypeName = info.getCheckTypeName();
this.startTime = startTime;
this.outTime = info.getCheckOutTime();
this.maxTimes = info.getCheckMaxTimes();
this.processIden = info.getProcessIden()==null ? "" : info.getProcessIden();
this.downLatch = downLatch;
}
public NMSClientForSNMPThread(String name,String ip,SetInfo info,Long startTime) {
this.name = name;
this.ip = ip;
this.sitInfoId = info.getId();
this.checkTypeName = info.getCheckTypeName();
this.startTime = startTime;
this.outTime = info.getCheckOutTime();
this.maxTimes = info.getCheckMaxTimes();
this.processIden = info.getProcessIden()==null ? "" : info.getProcessIden();
this.downLatch = downLatch;
}
@Override
public void run() {
Thread.currentThread().setName(name+" "+ip);
try {
Calendar checkTime = Calendar.getInstance();
Calendar nextTime = Calendar.getInstance();
nextTime.add(Calendar.MINUTE, Long.valueOf(gap).intValue());
List<String> datas = new ArrayList<String>(); //拼写数据格式 已安全进入公共数据解析入口
//--初始部分数据整理
datas.add(Common.getIpSeqIdMap().get(ip)+"");//IP
datas.add(sitInfoId+"");//监测设置ID
datas.add(checkTypeName);//监测类别,
datas.add(processIden);//进程名称(检查类别设置名称),
String stateInfo ="";
int state = -1;
String[] datas2 = new String[6];
int a = 0;
String msgArr = "";
boolean isSuccess = false;
datas2[3] = Calendar.getInstance().getTimeInMillis()+"";
isSuccess = this.sockeHandshake(msgArr);
datas2[4] = Calendar.getInstance().getTimeInMillis()+"";
datas2[0] = "snmp:"+"1.3.6.1.2.1.1.5.0";
datas2[1] = msgArr;
// stateInfo += "开始"+format.format(new Date(Long.parseLong(datas2[3])))+ " SNMP握手";
// stateInfo += "Start"+format.format(new Date(Long.parseLong(datas2[3])))+ " SNMP Shakehand";
stateInfo += "i18n_server.NMSClientForSNMPThread.begin_n81i"+format.format(new Date(Long.parseLong(datas2[3])))+ " i18n_server.NMSClientForSNMPThread.snmpShake_n81i";
datas.add(startTime+"");//监测服务启动时间,
if(isSuccess){ //成功
// stateInfo += format.format(new Date(Long.parseLong(datas2[4]))) + " 成功 ";
stateInfo += format.format(new Date(Long.parseLong(datas2[4]))) + " i18n_server.NMSClientForSNMPThread.success_n81i ";
datas2[2] = "0";
}else{ //失败
// stateInfo += format.format(new Date(Long.parseLong(datas2[4]))) + " 失败 ";
stateInfo += format.format(new Date(Long.parseLong(datas2[4]))) + " i18n_server.NMSClientForSNMPThread.fail_n81i ";
datas2[2] = "1";
String [] pingData = pingHandshake();
if ((StringUtils.isEmpty(pingData[1]) || "0".equals(pingData[1])) ) {
// stateInfo = "网络异常";
stateInfo = "i18n_server.NMSClientForSNMPThread.netErr_n81i";
} else {
// stateInfo = "请检查目标主机NMSClient是否启动";
}
}
datas2[5] = DateUtil.getSecondsFromBeinToEnd(new Date(Long
.parseLong(datas2[3].toString())).getTime(), new Date(Long
.parseLong(datas2[4].toString())).getTime())
+ "";
state = 0;
datas.add("0");//检测时延(秒)
datas.add(checkTime.getTimeInMillis()+"");//本次检测时间,
if(state!=-1){
datas.add(a+"");// 尝试次数,+"/"+maxTimes
datas.add(nextTime.getTimeInMillis()+"");// 下次计划监测时间,
String [] pArray = getAlarmState(Common.getAlarmInfoMap().get(sitInfoId.longValue()+""), datas2);
if(isSuccess){
datas.add("1"); // 执行状态
datas.add(""); // 告警列序号,
datas.add(""); // 告警级别,
datas.add(""); // 告警值,
}else {
datas.add("0"); // 执行状态
datas.add(pArray==null?"":pArray[0]); // 告警列序号,
datas.add(pArray==null?"":pArray[1]); // 告警级别,
datas.add(pArray==null?"":pArray[2]); // 告警值,
}
datas.add(stateInfo); // 状态信息(描述信息),
datas.add(stateInfo); // 性能数据,
datas.addAll(Arrays.asList(datas2));//监测具体数据信息(每个字段一列)
} else {
datas.add(a+"");// 尝试次数,+"/"+maxTimes
datas.add(nextTime.getTimeInMillis()+"");// 下次计划监测时间,
datas.add("-1"); // 执行状态
datas.add("3"); // 告警列序号,(丢包数 列 序号 为3)
datas.add("1"); // 告警级别,
datas.add("1"); // 告警值,
datas.add(stateInfo); // 状态信息(描述信息),
datas.add(stateInfo); // 性能数据,
}
datas.add(checkTime.getTimeInMillis()+"");//本次检测时间,
//- 存入缓存
try {
logger.debug("data"+Arrays.toString(datas.toArray()));
Common.addDeteData(CSVUtils.csvBytesPrinter(datas, Constants.COMMON_TEXT_CODING));
logger.debug("监测数据以 CSV格式 保存完成");
} catch (Exception e) {
logger.error("Monitoring data to save exceptions in CSV format", e);
}
} catch (Exception ex) {
logger.error(ExceptionPrintUtils.printExceptionStack(ex));
String[] alarm = Common.alarmExceptionInfo(sitInfoId, ip, Constants.DETEC_NMSC_STR, processIden, startTime, 1,Constants.DETECTION_INFO_ALARM_WRONG, ex.getMessage());
Common.addAlarmData(alarm);
}finally{
if(downLatch != null){
downLatch.countDown();
}
}
}
private void datasHeader(List<String> pubDatas){
logger.debug("监测数据头拼写开始");
// --初始部分数据整理
pubDatas.add(Common.getIpSeqIdMap().get(ip)+"");// uuid
pubDatas.add(sitInfoId + "");// 监测设置ID
pubDatas.add(checkTypeName);// 监测类别,
pubDatas.add("");// 进程名称(检查类别设置名称),
pubDatas.add(startTime + "");// 监测服务启动时间,
pubDatas.add("0");// 检测时延(秒)
}
private boolean sockeHandshake(String value){
//- 通过 CloumnsMap 获取 oids
String [] oidArray = new String []{"1.3.6.1.2.1.1.5.0"};
//- 监测数据集合
List<String> pubDatas = new ArrayList<String>(); // 拼写数据格式
//- DetecDatas 拼写 Header
datasHeader(pubDatas);
int version = Common.getSnmpVerByUUID(Common.getIpSeqIdMap().get(ip));
// int version = SnmpConstants.version2c;
//-- 执行和解析 即获取详细数据
int state = -1;
Map<String, String> snmpDatas = new HashMap<String, String>() ;
StringBuffer stateInfo = new StringBuffer();
try {
Target target= null;
if(version == SnmpConstants.version3){
target = SNMP4JUtils.createUserTarget(ip, port+"", (int)maxTimes, (int)outTime*1000);
}else{
target = SNMP4JUtils.createCommunityTarget(ip, port+"", Constants.SNMP_COMMUNITY, (int)maxTimes, (int)outTime*1000, SnmpConstants.version2c);
}
SNMP4JUtils.snmpGet(snmpDatas, oidArray, target);
state = 1;
} catch (Exception e) {
state = -1;
stateInfo.append(e.getMessage());
logger.error((version == SnmpConstants.version3?"version3":"version2c")+" GET失败", e);
}
//- DetecDatas 拼写 Body
if(state==1 && snmpDatas.size()>0 && StringUtils.isNotBlank(snmpDatas.get(oidArray[0]))){
value = snmpDatas.get(oidArray[0]);
logger.debug((version == SnmpConstants.version3?"version3":"version2c")+" GET"+oidArray[0]+" "+snmpDatas.get(oidArray[0]));
return true;
}else{
return false;
}
}
private String[] pingHandshake(){
String command = ""; // 命令语句
int minTime = Integer.MAX_VALUE, maxTime = 0, totalTime = 0, curTime; // 最短时间,最长时间,总时间,时间变量
int snum = 0, fnum = 0; // 发包成功和失败数
// 判断系统类型 win or Linux
String system = (String) (System.getProperty("os.name")).toLowerCase();
if (system.indexOf("win") != -1) {
command += "ping -n 4 -w 4000 " + ip;
} else if (system.indexOf("linux") != -1) {
command += "ping -c 4 -w 4000 " + ip;
} else {
command += "ping " + ip;
}
String stateInfo = "";
String[] datas2 = new String[7];
Process process = null;
BufferedReader in = null; // 读取 Ping命令返回的信息
StringBuffer buffer = new StringBuffer();
try {
process = Runtime.getRuntime().exec(command);
in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
long count = maxTimes + 10;
int index;
// 最多多读10行
while ((line = in.readLine()) != null && count != 0) {
if ("".equals(line)) {
continue;
} // 空串跳过
buffer.append(line + "\n");
line = line.toLowerCase();
logger.debug("line:"+line);
if (line.indexOf("ttl") > 0) { // 获得成功响应的数据
count--; // 计数器自减1
// 截取time 值
if ((index = line.lastIndexOf("ms")) != -1) {
byte[] buf = line.getBytes();
int start = 0, end = buf.length, i, j;
// 下标末点
for (i = index; i >= 0; i--) {
if (Character.isDigit((char) buf[i])) {
end = i;
break;
}
}
if (i == 0)
continue;
// 下标起点
for (j = end; j >= 0; j--) {
if (!Character.isDigit((char) buf[j])) {
start = j + 1;
break;
}
}
// 时间值截取
curTime = Integer.parseInt(new String(buf, start,
end + 1 - start));
snum++; // 成功接收次数加1
totalTime += curTime; // 计算总时间
if (curTime < minTime) {
minTime = curTime;
} // 最小时间
if (curTime > maxTime) {
maxTime = curTime;
} // 最大时间
}
} else if (line.split(" ").length < 4) {
count--; // 计数器自减1
fnum++; // 失败接收次数加1
} else {
stateInfo += line + "\n";
}
}
if (totalTime == 0) {
minTime = 0;
}
// 已发送包数
datas2[0] = "" + (snum + fnum);
datas2[1] = "" + snum;
datas2[2] = "" + fnum;
BigDecimal fnum0 = new BigDecimal(fnum);
BigDecimal tnum0 = new BigDecimal(snum + fnum);
DecimalFormat df = new DecimalFormat("####0.00");
datas2[3] = ""
+ ((new BigDecimal(df.format(fnum0.divide(tnum0))))
.multiply(new BigDecimal(100)));
datas2[4] = "" + minTime;
datas2[5] = "" + maxTime;
datas2[6] = "" + (snum == 0 ? 0 : (totalTime / snum));
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}finally{
if(in!=null){try {
in.close();
} catch (IOException e) {
logger.error("",e);
}}
if(process!= null)process.destroy();
process = null;
}
/*if(state==-1){
isSuccess = false;
}else{
isSuccess = true;
}*/
return datas2;
}
//获得当前的报警设置信息,与相应字段值比较
private String[] getAlarmState(List<AlarmInfo> alarmInfos, String[] sysData){
String[] strs = null;
if(alarmInfos!=null){
strs = new String[]{"", "", ""};
for(AlarmInfo alarm : alarmInfos){
if(sysData.length>=alarm.getShowNum()){
Double data = Math.abs(Double.parseDouble(sysData[alarm.getShowNum()-1]));
if("equal".equals(alarm.getPoliceSysmbols())){
if((data+"").equals(alarm.getPoliceValue())){
strs[0] += alarm.getShowNum() + "|";// 告警序列号
strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
strs[2] += alarm.getPoliceValue() + "|"; //告警值
}
}
else if("include".equals(alarm.getPoliceSysmbols())){
if((data+"").indexOf(alarm.getPoliceValue())!=-1){
strs[0] += alarm.getShowNum() + "|";// 告警序列号
strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
strs[2] += alarm.getPoliceValue() + "|"; //告警值
}
}
else if("exclude".equals(alarm.getPoliceSysmbols())){
if((data+"").indexOf(alarm.getPoliceValue())==-1){
strs[0] += alarm.getShowNum() + "|";// 告警序列号
strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
strs[2] += alarm.getPoliceValue() + "|"; //告警值
}
}
else{
double result = data - Double.parseDouble(alarm.getPoliceValue());
if ((">".equals(alarm.getPoliceSysmbols()) && result > 0)
|| ("<".equals(alarm.getPoliceSysmbols()) && result < 0)
|| ("=".equals(alarm.getPoliceSysmbols()) && result == 0)
|| (">=".equals(alarm.getPoliceSysmbols()) && result >= 0)
|| ("<=".equals(alarm.getPoliceSysmbols()) && result <=0) ) {
strs[0] += alarm.getShowNum() + "|";// 告警序列号
strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
strs[2] += alarm.getPoliceValue() + "|"; //告警值
}
}
}
}
for(int i=0; i<strs.length; i++){
if(strs[i].length()>0){
strs[i] = strs[i].substring(0, strs[i].length()-1);
}
}
}
if(strs!=null && "".equals(strs[0])){
strs = null;
}
return strs;
}
public NMSClientForSNMPThread(String name,Long sitInfoId,String socketIp,long gap,long outTime,long maxTimes) {
this.name = name;
this.ip = socketIp;
this.sitInfoId = sitInfoId;
this.outTime = outTime;
this.maxTimes = maxTimes;
this.gap = gap;
}
/*public static void main(String [] args) {
Thread thread = new Thread(new NMSClientForSNMPThread("NMSC Thread",10l,"10.0.6.254",2,100,3));
// String name,Long sitInfoId,String socketIp,int socketPort,long gap,long outTime,long maxTimes
thread.start();
}*/
}

View File

@@ -0,0 +1,757 @@
package com.nms.server.thread.monitor;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.nms.server.bean.AlarmInfo;
import com.nms.server.bean.DetectInfo;
import com.nms.server.bean.MissionResult2;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.thread.file.UnZipManagerThread;
import com.nms.server.thread.monitor.util.MonitorUtil;
import com.nms.server.thread.socket.SocketCMD;
import com.nms.server.util.CSVUtils;
import com.nms.server.util.DateUtil;
import com.nms.server.util.ExceptionPrintUtils;
import com.nms.server.util.socket.SocketUtils;
import com.nms.server.util.socket.limiter.InputStreamLimiter;
import com.nms.server.util.socket.limiter.OutputStreamLimiter;
/**
* 监测数据
* 监测NMSClient端是否执行执行线程
* @author ZhangGang
*
*/
public class NMSClientForSocketThread extends SocketUtils implements Runnable{
private Logger logger = Logger.getLogger(NMSClientForSocketThread.class);
private SimpleDateFormat format = new SimpleDateFormat(Constants.COMMON_DATE_FORMAT);
private String name;
private String checkTypeName = null;
private Long startTime = null;
private Long sitInfoId = null;
private long outTime = 2;
private long maxTimes = 3;
private long gap = 0 ;
// private String cmd = SocketCMD.CLIENT_REQ_HAND_SHAKE;
private String processIden = null;
// protected Socket socket = null; //Socket
private CountDownLatch downLatch;
private SetInfo info;
/**
* 构造方法
* @param name 线程名称
* @param ip 被监测端IP
* @param port socket通信端口
* @param info
*/
public NMSClientForSocketThread(String name,String ip,int port,SetInfo info,Long startTime,CountDownLatch downLatch) {
super(ip, port);
this.name = name;
this.sitInfoId = info.getId();
this.checkTypeName = info.getCheckTypeName();
this.startTime = startTime;
this.outTime = info.getCheckOutTime();
this.maxTimes = info.getCheckMaxTimes();
this.processIden = info.getProcessIden()==null ? "" : info.getProcessIden();
this.downLatch = downLatch;
this.info = info;
}
public NMSClientForSocketThread(String name,String ip,int port,SetInfo info,Long startTime) {
super(ip, port);
this.name = name;
this.sitInfoId = info.getId();
this.checkTypeName = info.getCheckTypeName();
this.startTime = startTime;
this.outTime = info.getCheckOutTime();
this.maxTimes = info.getCheckMaxTimes();
this.processIden = info.getProcessIden()==null ? "" : info.getProcessIden();
this.downLatch = downLatch;
this.info = info;
}
@Override
public void run() {
Thread.currentThread().setName(name+" "+ip);
try {
/**
*
* ping不通时无握手监测详细数据
* 握手失败时,有握手监测详细数据
* 握手成功时,有握手监测详细数据
*
*/
Long checkTime = System.currentTimeMillis();
int a = 0;
DetectInfo detectInfo = null;
String failStartTime = "";
String failEndTime = "";
loop:
for(; a < maxTimes ;){
failStartTime = Calendar.getInstance().getTimeInMillis()+"";
detectInfo = this.getNMSClientBysocket();
failEndTime = Calendar.getInstance().getTimeInMillis()+"";
a++;
if(detectInfo != null){ //成功,如果第一次就成功的话那么尝试次数为1
break loop;
}else{ //失败
continue loop;
}
}
if(detectInfo == null){//握手失败
detectInfo = new DetectInfo();
String stateInfo = "";
String [] pingData = pingHandshake();
if ((StringUtils.isEmpty(pingData[1]) || "0".equals(pingData[1])) ) {//ping不通无握手监测详细数据
// stateInfo = "网络异常";
// stateInfo = "Network Exception";
stateInfo = "i18n_server.NMSClientForSNMPThread.netErr_n81i";
} else {//如果可以ping通但是握手失败则有详细握手监测数据
// stateInfo = "开始"+format.format(new Date(checkTime))+ " NMSClient握手" +
// format.format(new Date()) + " 失败 ";
// stateInfo = "Start"+format.format(new Date(checkTime))+ " NMSClient Shakehand" +
// format.format(new Date()) + " failed ";
stateInfo = "i18n_server.NMSClientForSNMPThread.begin_n81i"+format.format(new Date(checkTime))+ " i18n_server.NMSClientForSocketThread.nmsShake_n81i" +
format.format(new Date()) + " i18n_server.NMSClientForSNMPThread.fail_n81i ";
StringBuffer detailInfo = new StringBuffer();
detailInfo.append(SocketCMD.CLIENT_REQ_HAND_SHAKE);//发送信息
detailInfo.append(MonitorUtil.SEPARATOR);//分隔符
detailInfo.append("");//返回信息
detailInfo.append(MonitorUtil.SEPARATOR);//分隔符
detailInfo.append("1");//是否可达,0:可达1不可达
detailInfo.append(MonitorUtil.SEPARATOR);//分隔符
detailInfo.append(failStartTime);//发送时间
detailInfo.append(MonitorUtil.SEPARATOR);//分隔符
detailInfo.append(failEndTime);//返回时间
detailInfo.append(MonitorUtil.SEPARATOR);//分隔符
detailInfo.append(DateUtil.getSecondsFromBeinToEnd(new Date(Long
.parseLong(failStartTime)).getTime(), new Date(Long
.parseLong(failEndTime)).getTime())
+ "");//延迟时间
detectInfo.getDetailDatas().add(detailInfo.toString());
}
detectInfo.setDescInfo(stateInfo);
logger.info(""+ip+" 的握手监测 异常:"+stateInfo);
} else {//握手成功,则进行监测数据的收集??
logger.info(""+ip+" 的握手监测 正常,开始收集数据");
// Thread.currentThread().setName("数据收集:>"+ip);
Thread.currentThread().setName("Data Collection:>"+ip);
collectDatas();//收集数据
Thread.currentThread().setName(name+" "+ip);
}
detectInfo.setTestTimes(a);//尝试次数
detectInfo.setCheckTime(checkTime);//监测时间
//-- 生成监测数据
MonitorUtil.createMonitorData(ip, info, startTime, Common.getAlarmInfoMap().get(info.getId()+ ""), detectInfo);
} catch (Exception ex) {
logger.error(ExceptionPrintUtils.printExceptionStack(ex));
String[] alarm = Common.alarmExceptionInfo(sitInfoId, ip, Constants.DETEC_NMSC_STR, processIden, startTime, 1,Constants.DETECTION_INFO_ALARM_WRONG, ex.getMessage());
Common.addAlarmData(alarm);
}finally{
if(downLatch!=null){
downLatch.countDown();
}
}
}
private DetectInfo getNMSClientBysocket(){
DetectInfo detectInfo = null;
//set up a connection
try {
//-- 创建通讯
this.createClientSocket();
//-- 发送握手命令
String sendTime = Calendar.getInstance().getTimeInMillis()+"";
sendMessage(SocketCMD.CLIENT_REQ_HAND_SHAKE);
String msg = receiveMessage();//收到回复的信息后,说明握手成功了
String backTime = Calendar.getInstance().getTimeInMillis()+"";
//-- 信息保存到监测信息对象中
detectInfo = new DetectInfo();
StringBuffer nmsClientDetailDetectInfo = new StringBuffer();
nmsClientDetailDetectInfo.append(SocketCMD.CLIENT_REQ_HAND_SHAKE);//发送信息
nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);//分隔符
nmsClientDetailDetectInfo.append(msg);//返回信息
nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);//分隔符
nmsClientDetailDetectInfo.append("0");//是否可达,0:可达1不可达
nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);//分隔符
nmsClientDetailDetectInfo.append(sendTime);//发送时间
nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);//分隔符
nmsClientDetailDetectInfo.append(backTime);//返回时间
nmsClientDetailDetectInfo.append(MonitorUtil.SEPARATOR);//分隔符
nmsClientDetailDetectInfo.append(DateUtil.getSecondsFromBeinToEnd(new Date(Long
.parseLong(sendTime)).getTime(), new Date(Long
.parseLong(backTime)).getTime())
+ "");//延迟时间
detectInfo.getDetailDatas().add(nmsClientDetailDetectInfo.toString());
// detectInfo.setDescInfo("开始"+format.format(new Date(Long.parseLong(sendTime)))+ " NMSClient握手" +
// format.format(new Date(Long.parseLong(backTime))) + " 成功 ");
// detectInfo.setDescInfo("Start"+format.format(new Date(Long.parseLong(sendTime)))+ " NMSClient Shakehand" +
// format.format(new Date(Long.parseLong(backTime))) + "success ");
detectInfo.setDescInfo("i18n_server.NMSClientForSNMPThread.begin_n81i"+format.format(new Date(Long.parseLong(sendTime)))+ " i18n_server.NMSClientForSocketThread.nmsShake_n81i" +
format.format(new Date(Long.parseLong(backTime))) + "i18n_server.NMSClientForSNMPThread.success_n81i ");
} catch (Exception e) {
logger.error("Failure to shake hands with"+ip+e.getMessage());
}finally{
close();
}
return detectInfo;
}
public static long getMinutesFromBeginToEnd(long begin, long end) {
return (end - begin) / (60 * 1000);
}
private String[] pingHandshake(){
String command = ""; // 命令语句
int minTime = Integer.MAX_VALUE, maxTime = 0, totalTime = 0, curTime; // 最短时间,最长时间,总时间,时间变量
int snum = 0, fnum = 0; // 发包成功和失败数
// 判断系统类型 win or Linux
String system = (String) (System.getProperty("os.name")).toLowerCase();
if (system.toLowerCase().indexOf("win") != -1) {
command += "ping -n 4 " + ip;//尝试次数 -n
} else if (system.toLowerCase().indexOf("linux") != -1) {
command += "ping -c 4 " + ip;
} else {
command += "ping -w 4 " + ip;
}
String stateInfo = "";
String[] datas2 = new String[7];
Process process = null;
BufferedReader in = null; // 读取 Ping命令返回的信息
StringBuffer buffer = new StringBuffer();
try {
logger.debug("ping command:"+command);
process = Runtime.getRuntime().exec(command);
in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
long count = maxTimes + 10;
int index;
// 最多多读10行
while ((line = in.readLine()) != null && count != 0) {
if ("".equals(line)) {
count--;
continue;
} // 空串跳过
buffer.append(line + "\n");
line = line.toLowerCase();
logger.debug("line:"+line);
if (line.indexOf("ttl") > 0) { // 获得成功响应的数据
count--; // 计数器自减1
// 截取time 值
if ((index = line.lastIndexOf("ms")) != -1) {
byte[] buf = line.getBytes();
int start = 0, end = buf.length, i, j;
// 下标末点
for (i = index; i >= 0; i--) {
if (Character.isDigit((char) buf[i])) {
end = i;
break;
}
}
if (i == 0)
continue;
// 下标起点
for (j = end; j >= 0; j--) {
if (!Character.isDigit((char) buf[j])) {
start = j + 1;
break;
}
}
// 时间值截取
curTime = Integer.parseInt(new String(buf, start,
end + 1 - start));
snum++; // 成功接收次数加1
totalTime += curTime; // 计算总时间
if (curTime < minTime) {
minTime = curTime;
} // 最小时间
if (curTime > maxTime) {
maxTime = curTime;
} // 最大时间
}
} else if (line.split(" ").length < 4) {
count--; // 计数器自减1
fnum++; // 失败接收次数加1
} else {
stateInfo += line + "\n";
}
}
if (totalTime == 0) {
minTime = 0;
}
// 已发送包数
datas2[0] = "" + (snum + fnum);
datas2[1] = "" + snum;
datas2[2] = "" + fnum;
BigDecimal fnum0 = new BigDecimal(fnum);
BigDecimal tnum0 = new BigDecimal(snum + fnum);
DecimalFormat df = new DecimalFormat("####0.00");
datas2[3] = "" + ((new BigDecimal(df.format(fnum0.divide(tnum0))))
.multiply(new BigDecimal(100)));
datas2[4] = "" + minTime;
datas2[5] = "" + maxTime;
datas2[6] = "" + (snum == 0 ? 0 : (totalTime / snum));
} catch (Exception e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}finally{
if(in!=null){try {
in.close();
} catch (IOException e) {
logger.error("",e);
}}
if(process!= null)process.destroy();
process = null;
}
/*if(state==-1){
isSuccess = false;
}else{
isSuccess = true;
}*/
return datas2;
}
//收集数据DC端主动收集数据监测数据、任务结果、回传文件
private void collectDatas(){
int zipDetect = 0;
int csvDetect = 0;
int zipTaskResult = 0;
int objTaskResult = 0;
int zipTaskReturn = 0;
int fileTaskReturn = 0;
try {
//- 非升级操作判断
if(Common.SERVER_UN_UPGRADE_FLAG){
this.createClientSocket();
sendMessage(SocketCMD.REQ_DATA_COLLECT);//DC要进行数据的收集监测数据、任务结果、回传文件
String msg0 = receiveMessage();//Client:发送数据文件类型监测数据、任务结果、回传文件的zip、csv或者list或者没有数据结束通信或者关闭socket则会收到null
while(true) {
logger.info("数据收集client端"+this.ip+"回应信息:"+msg0);
//监测数据---start
if(SocketCMD.DETECT_DATA_ZIP_TYPE.equalsIgnoreCase(msg0)) {
logger.info("数据类型监测数据的zip文件");
this.sendMessage(SUCCESS);//DC告诉client我知道你要发送zip类型的数据了
String uploadPath = Constants.ZIP_FILE_DETECT_DATA_DIR;
String fileName = receiveMessage();//client发送zip文件的名称
this.sendMessage(SUCCESS);//DC收到zip文件的名称给client回成功信息
bpReceiveFile(uploadPath+File.separator+fileName);//client收到zip文件名发送成功后发送zip文件DC接收client发送的zip文件
this.sendMessage(SUCCESS);//DC接收完client发送的zip文件存入指定路径后给client回接收成功信息
//启动并注册 解压文件线程
Future<?> future = Common.getFutureMap().get(Constants.UNZIP_FILE_MANAGER);
if(future == null){
future = Common.scheduled.scheduleWithFixedDelay(new UnZipManagerThread(), 0, 30, TimeUnit.SECONDS);
Common.registRunnable(Constants.UNZIP_FILE_MANAGER, future);
}
zipDetect++;
msg0 = receiveMessage();//Client:再次发送数据文件类型,或者没有数据,结束通信
}
else if(SocketCMD.DETECT_DATA_CSV_TYPE.equalsIgnoreCase(msg0)) {
logger.info("数据类型监测数据的csv文件");
sendMessage(SUCCESS);//DC告诉client我知道你要发送csv类型的数据了client端就开始发送csv文件
LinkedList<byte []> bslist = receiveFileBytesByBath();//DC端就准备接收csv文件:可能是多个csv文件
if(bslist!=null && bslist.size()>0){
Common.addAllDeteDataList(bslist);
}else{
logger.debug("接收 监测数据 文件数:0");
}
sendMessage(SUCCESS);//DC端csv文件接收完毕后告诉client端文件接收完毕
csvDetect++;
msg0 = receiveMessage();//Client:再次发送数据文件类型,或者没有数据,结束通信
}
//监测数据---end
//任务结果---start
else if(SocketCMD.TASK_RESULT_ZIP_TYPE.equalsIgnoreCase(msg0)) {
logger.info("数据类型任务结果的zip文件");
this.sendMessage(SUCCESS);//DC告诉client我知道你要发送zip类型的数据了
String uploadPath = Constants.ZIP_FILE_TASK_RESULT_DIR;
String fileName = receiveMessage();//client发送zip文件的名称
this.sendMessage(SUCCESS);//DC收到zip文件的名称给client回成功信息
bpReceiveFile(uploadPath+File.separator+fileName);//client收到zip文件名发送成功后发送zip文件DC接收client发送的zip文件
this.sendMessage(SUCCESS);//DC接收完client发送的zip文件存入指定路径后给client回接收成功信息
//启动并注册 解压文件线程
Future<?> future = Common.getFutureMap().get(Constants.UNZIP_FILE_MANAGER);
if(future == null){
future = Common.scheduled.scheduleWithFixedDelay(new UnZipManagerThread(), 0, 30, TimeUnit.SECONDS);
Common.registRunnable(Constants.UNZIP_FILE_MANAGER, future);
}
zipTaskResult++;
msg0 = receiveMessage();//Client:再次发送数据文件类型,或者没有数据,结束通信
}
else if(SocketCMD.TASK_RESULT_OBJ_TYPE.equalsIgnoreCase(msg0)){//-- 接收返回的任务结果修改为receiveObject
logger.info("数据类型任务结果的List<String[]>");
sendMessage(SUCCESS);
List<String> resultList = (List<String>)receiveObject();
sendMessage(SUCCESS);
for (String result: resultList) {
logger.info("任务结果:"+result);
String[] misRlt2 = result.split(Constants.COMMON_DATA_SPLIT);
MissionResult2 result2 = Common.resoveMissionResult(misRlt2);
Common.addResultToResultList(result2);//没有addAll因为传递的任务结果可能是不同类型的任务结果1-6
}
objTaskResult++;
msg0 = receiveMessage();//Client:再次发送数据文件类型,或者没有数据,结束通信
}
//任务结果---end
//回传文件---start
else if(SocketCMD.TASK_RETURN_ZIP_TYPE.equalsIgnoreCase(msg0)) {
logger.info("数据类型回传文件的zip文件");
this.sendMessage(SUCCESS);//DC告诉client我知道你要发送zip类型的数据了
String uploadPath = Constants.ZIP_FILE_TASK_RETURN_DIR;
String fileName = receiveMessage();//client发送zip文件的名称
this.sendMessage(SUCCESS);//DC收到zip文件的名称给client回成功信息
bpReceiveFile(uploadPath+File.separator+fileName);//client收到zip文件名发送成功后发送zip文件DC接收client发送的zip文件
this.sendMessage(SUCCESS);//DC接收完client发送的zip文件存入指定路径后给client回接收成功信息
//启动并注册 解压文件线程
Future<?> future = Common.getFutureMap().get(Constants.UNZIP_FILE_MANAGER);
if(future == null){
future = Common.scheduled.scheduleWithFixedDelay(new UnZipManagerThread(), 0, 30, TimeUnit.SECONDS);
Common.registRunnable(Constants.UNZIP_FILE_MANAGER, future);
}
zipTaskReturn++;
msg0 = receiveMessage();//Client:再次发送数据文件类型,或者没有数据,结束通信
}
else if(SocketCMD.TASK_RETURN_FILE_TYPE.equalsIgnoreCase(msg0)){//-- 接收任务4“启动”的回传文件
sendMessage(SUCCESS);
String msg1 = receiveMessage();
sendMessage(SUCCESS);
logger.info(msg1);
String [] result = msg1.split(Constants.COMMON_DATA_SPLIT);
MissionResult2 result2 = Common.resoveMissionResult(result);
String fileName = receiveMessage();
sendMessage(SUCCESS);
logger.debug("MISSION_FILE_UPLOAD_DIR"+Constants.MISSION_FILE_UPLOAD_DIR);
this.bpReceiveFile(Constants.MISSION_FILE_UPLOAD_DIR+fileName);
sendMessage(SUCCESS);
logger.debug("MISSION_FILE_UPLOAD_DIR"+Constants.MISSION_FILE_UPLOAD_DIR+fileName);
result2.setFileInfo(fileName);
Common.addResultToResultList(result2);
fileTaskReturn++;
msg0 = receiveMessage();//Client:再次发送数据文件类型,或者没有数据,结束通信
}
//回传文件---end
else {//如果没有这个else且对方发送的命令非以上6种则会死循环
logger.info("数据收集线程与client端"+this.ip+"的通信结束");
break;
}
}
logger.info("client端"+this.ip+",监测数据zip文件发送次数"+zipDetect);//每次可以发送多个zip
logger.info("client端"+this.ip+",监测数据csv文件发送次数"+csvDetect);//每次可以发送多个csv
logger.info("client端"+this.ip+",任务结果zip文件发送次数"+zipTaskResult);//每次可以发送多个
logger.info("client端"+this.ip+",任务结果obj文件发送次数"+objTaskResult);//每次可以发送多个
logger.info("client端"+this.ip+",回传文件zip文件发送次数"+zipTaskReturn);//每次可以发送多个
logger.info("client端"+this.ip+",回传文件file文件发送次数"+fileTaskReturn);//每次可以发送多个
}
} catch (Exception e) {
logger.error("The DC side actively collects data (monitoring data, task results, return files) exceptions",e);
}
}
// public void run() {
//
// Thread.currentThread().setName(name+" "+ip);
//
// try {
//
// Calendar checkTime = Calendar.getInstance();
// Calendar nextTime = Calendar.getInstance();
// nextTime.add(Calendar.MINUTE, Long.valueOf(gap).intValue());
//
// List<String> datas = new ArrayList<String>(); //拼写数据格式 已安全进入公共数据解析入口
//
// //--初始部分数据整理
// datas.add(Common.getIpSeqIdMap().get(ip)+"");//IP
// datas.add(sitInfoId+"");//监测设置ID
// datas.add(checkTypeName);//监测类别,
// datas.add(processIden);//进程名称(检查类别设置名称),
//
// String stateInfo ="";
// int state = -1;//测试使用
// String[] datas2 = new String[6];
// int a = 0;
// String [] msgArr = null;
//
// loop:
// for(int i = 0 ; i < maxTimes ;i++){
// datas2[3] = Calendar.getInstance().getTimeInMillis()+"";
// msgArr = this.sockeHandshake();
// a = a+1;
// datas2[4] = Calendar.getInstance().getTimeInMillis()+"";
// if("1".equals(msgArr[0])){ //成功
// break loop;
// }else{ //失败
// continue loop;
// }
// }
// datas2[0] = SocketCMD.CLIENT_REQ_HAND_SHAKE;
// datas2[1] = msgArr[1];
// stateInfo += "开始"+format.format(new Date(Long.parseLong(datas2[3])))+ " NMSClient握手";
// if("1".equals(msgArr[0])){ //成功
// if(msgArr[1] != null && !"".equals(msgArr[1])){
// String mreturn[] = msgArr[1].split("\\|");
// if(mreturn != null && mreturn.length >= 2){
// datas.add(mreturn[1]);//监测服务启动时间,
// }
// }
// stateInfo += format.format(new Date(Long.parseLong(datas2[4]))) + " 成功 ";
// datas2[2] = "0";
// }else{ //失败
// datas.add(startTime+"");//监测服务启动时间,
// stateInfo += format.format(new Date(Long.parseLong(datas2[4]))) + " 失败 ";
// datas2[2] = "1";
// String [] pingData = pingHandshake();
//
// if ((StringUtils.isEmpty(pingData[1]) || "0".equals(pingData[1])) ) {
// stateInfo = "网络异常";
// } else {
//// stateInfo = "请检查目标主机NMSClient是否启动";
// }
// }
// datas2[5] = DateUtil.getSecondsFromBeinToEnd(new Date(Long
// .parseLong(datas2[3].toString())).getTime(), new Date(Long
// .parseLong(datas2[4].toString())).getTime())
// + "";
// state = 0;
//
//
// datas.add("0");//检测时延(秒)
// datas.add(checkTime.getTimeInMillis()+"");//本次检测时间,
//
// if(state!=-1){
// datas.add(a+"");// 尝试次数,+"/"+maxTimes
// datas.add(nextTime.getTimeInMillis()+"");// 下次计划监测时间,
// String [] pArray = getAlarmState(Common.getAlarmInfoMap().get(sitInfoId.longValue()+""), datas2);
// if("1".equals(msgArr[0])){
// datas.add("1"); // 执行状态
// datas.add(""); // 告警列序号,
// datas.add(""); // 告警级别,
// datas.add(""); // 告警值,
// }else {
// datas.add("0"); // 执行状态
// datas.add(pArray==null?"":pArray[0]); // 告警列序号,
// datas.add(pArray==null?"":pArray[1]); // 告警级别,
// datas.add(pArray==null?"":pArray[2]); // 告警值,
// }
// datas.add(stateInfo); // 状态信息(描述信息),
// datas.add(stateInfo); // 性能数据,
// datas.addAll(Arrays.asList(datas2));//监测具体数据信息(每个字段一列)
// } else {//测试告警的代码,无用
// datas.add(a+"");// 尝试次数,+"/"+maxTimes
// datas.add(nextTime.getTimeInMillis()+"");// 下次计划监测时间,
// datas.add("-1"); // 执行状态
// datas.add("3"); // 告警列序号,(丢包数 列 序号 为3)
// datas.add("1"); // 告警级别,
// datas.add("1"); // 告警值,
// datas.add(stateInfo); // 状态信息(描述信息),
// datas.add(stateInfo); // 性能数据,
// }
// datas.add(checkTime.getTimeInMillis()+"");//本次检测时间,
//
// //- 存入缓存
// try {
// logger.debug("data"+Arrays.toString(datas.toArray()));
// Common.addDeteData(CSVUtils.csvBytesPrinter(datas, Constants.COMMON_TEXT_CODING));
// logger.debug("监测数据以 CSV格式 保存完成");
// } catch (Exception e) {
// logger.error("监测数据以 CSV格式 保存异常", e);
// }
// } catch (Exception ex) {
// logger.error(ExceptionPrintUtils.printExceptionStack(ex));
// String[] alarm = Common.alarmExceptionInfo(sitInfoId, ip, Constants.DETEC_NMSC_STR, processIden, startTime, 1,Constants.DETECTION_INFO_ALARM_WRONG, ex.getMessage());
// Common.addAlarmData(alarm);
// }finally{
// if(downLatch!=null){
// downLatch.countDown();
// }
// }
// }
//
// private String[] sockeHandshake(){//此方法无用了
// String [] msgArr = new String[2];
// msgArr[0] = 0+"";
//
// //set up a connection
// SSLSocketFactory ssf = null;
// try {
// //-- create SocketFactory
// ssf = sSLContext.getSocketFactory();
//
// //-- create socket
// socket=(SSLSocket)ssf.createSocket(ip,port);
// logger.debug("create socket success.");
// socket.setSoTimeout((int)3000);
// //-- handshake 握手
// ((SSLSocket) socket).startHandshake();
// logger.debug("handshake success.");
//
// outl = new OutputStreamLimiter(socket.getOutputStream());
// inl = new InputStreamLimiter(socket.getInputStream());
//
// sendMessage(SocketCMD.CLIENT_REQ_HAND_SHAKE);
// msgArr[1] = receiveMessage();
//
// msgArr[0] = 1+"";
// }catch (IOException e) {
// logger.error("",e);
// } catch (Exception e) {
// logger.error("",e);
// }finally{
// close();
// }
//
// return msgArr;
// }
//获得当前的报警设置信息,与相应字段值比较
// private String[] getAlarmState(List<AlarmInfo> alarmInfos, String[] sysData){
// String[] strs = null;
// if(alarmInfos!=null){
// strs = new String[]{"", "", ""};
// for(AlarmInfo alarm : alarmInfos){
// if(sysData.length>=alarm.getShowNum()){
// Double data = Math.abs(Double.parseDouble(sysData[alarm.getShowNum()-1]));
// if("equal".equals(alarm.getPoliceSysmbols())){
// if((data+"").equals(alarm.getPoliceValue())){
// strs[0] += alarm.getShowNum() + "|";// 告警序列号
// strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
// strs[2] += alarm.getPoliceValue() + "|"; //告警值
// }
// }
// else if("include".equals(alarm.getPoliceSysmbols())){
// if((data+"").indexOf(alarm.getPoliceValue())!=-1){
// strs[0] += alarm.getShowNum() + "|";// 告警序列号
// strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
// strs[2] += alarm.getPoliceValue() + "|"; //告警值
// }
// }
// else if("exclude".equals(alarm.getPoliceSysmbols())){
// if((data+"").indexOf(alarm.getPoliceValue())==-1){
// strs[0] += alarm.getShowNum() + "|";// 告警序列号
// strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
// strs[2] += alarm.getPoliceValue() + "|"; //告警值
// }
// }
// else{
// double result = data - Double.parseDouble(alarm.getPoliceValue());
// if ((">".equals(alarm.getPoliceSysmbols()) && result > 0)
// || ("<".equals(alarm.getPoliceSysmbols()) && result < 0)
// || ("=".equals(alarm.getPoliceSysmbols()) && result == 0)
// || (">=".equals(alarm.getPoliceSysmbols()) && result >= 0)
// || ("<=".equals(alarm.getPoliceSysmbols()) && result <=0) ) {
// strs[0] += alarm.getShowNum() + "|";// 告警序列号
// strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
// strs[2] += alarm.getPoliceValue() + "|"; //告警值
// }
// }
// }
// }
// for(int i=0; i<strs.length; i++){
// if(strs[i].length()>0){
// strs[i] = strs[i].substring(0, strs[i].length()-1);
// }
// }
// }
//
// if(strs!=null && "".equals(strs[0])){
// strs = null;
// }
//
// return strs;
// }
//main测试使用的构造方法
public NMSClientForSocketThread(String name,Long sitInfoId,String socketIp,int socketPort,long gap,long outTime,long maxTimes) {
super(socketIp, socketPort);
this.name = name;
this.sitInfoId = sitInfoId;
this.outTime = outTime;
this.maxTimes = maxTimes;
this.gap = gap;
}
public static void main(String [] args) {
Thread thread = new Thread(new NMSClientForSocketThread("NMSC Thread",10l,"10.0.6.102",60701,2,100,3));
// String name,Long sitInfoId,String socketIp,int socketPort,long gap,long outTime,long maxTimes
thread.start();
}
}

View File

@@ -0,0 +1,354 @@
package com.nms.server.thread.monitor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.log4j.Logger;
import com.nms.server.bean.AlarmInfo;
import com.nms.server.bean.SetInfo;
import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.util.CSVUtils;
import com.nms.server.util.ExceptionPrintUtils;
/**
* 监测数据 Ping数据获取执行线程
*
* @date Jul 18, 2011 5:32:44 PM
* @author ZhangGang
*
*/
public class PingThread implements Runnable {
private Logger logger = Logger.getLogger(PingThread.class);
private String name;
private String pingIp = "";
private long startTime = Calendar.getInstance().getTimeInMillis();
private String checkTypeName = null;
private Long sitInfoId = null;
private long outTime = 2;
private long maxTimes = 3;
private long gap = 0;
private CountDownLatch downLatch;
/**
* 构造方法
* @param name 线程名称
* @param ip 被监测端IP
* @param port socket通信端口
* @param info
*/
public PingThread(String name,String ip,SetInfo info,Long startTime,CountDownLatch downLatch) {
this.name = name;
this.pingIp = ip;
this.sitInfoId = info.getId();
this.checkTypeName = info.getCheckTypeName();
this.startTime = startTime;
this.outTime = info.getCheckOutTime();
this.maxTimes = info.getCheckMaxTimes();
this.gap = info.getCheckGap();
this.downLatch = downLatch;
}
public PingThread(String name,String ip,SetInfo info,Long startTime) {
this.name = name;
this.pingIp = ip;
this.sitInfoId = info.getId();
this.checkTypeName = info.getCheckTypeName();
this.startTime = startTime;
this.outTime = info.getCheckOutTime();
this.maxTimes = info.getCheckMaxTimes();
this.gap = info.getCheckGap();
this.downLatch = downLatch;
}
/**
* 构造方法
*
* @param name
* 线程名称
* @param pingIp
* 被监测端IP
* @param sitInfoId
* 设置信息ID
* @param outTime
* 超时时间
* @param maxTimes
* 最大尝试次数
*/
/*public PingThread(String name, Long sitInfoId, String pingIp, long gap,
long outTime, long maxTimes) {
this.name = name;
this.pingIp = pingIp;
this.sitInfoId = sitInfoId;
this.outTime = outTime;
this.maxTimes = maxTimes;
this.gap = gap;
}
*/
@Override
public void run() {
Thread.currentThread().setName(name + " " + pingIp);
BufferedReader in = null; // 读取 Ping命令返回的信息
try {
StringBuffer buffer = new StringBuffer();
logger.debug("Ping 监测获取开始");
Calendar checkTime = Calendar.getInstance();
Calendar nextTime = Calendar.getInstance();
nextTime.add(Calendar.MINUTE, Long.valueOf(gap).intValue());
List<String> datas = new ArrayList<String>(); // 拼写数据格式
// --初始部分数据整理
datas.add(Common.getIpSeqIdMap().get(pingIp)+"");// IP
datas.add(sitInfoId + "");// 监测设置ID
datas.add(checkTypeName);// 监测类别,
datas.add("");// 进程名称(检查类别设置名称),
datas.add(startTime + "");// 监测服务启动时间,
datas.add("0");// 检测时延(秒)
datas.add(checkTime.getTimeInMillis() + "");// 本次检测时间,
String command = ""; // 命令语句
int minTime = Integer.MAX_VALUE, maxTime = 0, totalTime = 0, curTime; // 最短时间,最长时间,总时间,时间变量
int snum = 0, fnum = 0; // 发包成功和失败数
// 判断系统类型 win or Linux
String system = (String) (System.getProperty("os.name"))
.toLowerCase();
if (system.toLowerCase().indexOf("win") != -1) {
command += "ping -n " + maxTimes + " -w " + outTime * 1000
+ " " + pingIp;
} else if (system.toLowerCase().indexOf("linux") != -1) {
command += "ping -c " + maxTimes + " -w " + outTime
+ " " + pingIp;
} else {
command += "ping -w 4 " + pingIp;
}
String stateInfo = "";
int state = -1;
String[] datas2 = new String[7];
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
in = new BufferedReader(new InputStreamReader(process
.getInputStream()));
String line = null;
long count = maxTimes + 10;
int index;
// 最多只读10行
while ((line = in.readLine()) != null && count != 0) {
if ("".equals(line)) {
continue;
} // 空串跳过
//System.out.println("-- "+line);
buffer.append(line + "\n");
line = line.toLowerCase();
// System.out.println(pingIp+"> line === "+line);
if (line.indexOf("ttl") > 0) { // 获得成功响应的数据
count--; // 计数器自减1
// 截取time 值
if ((index = line.lastIndexOf("ms")) != -1) {
byte[] buf = line.getBytes();
int start = 0, end = buf.length, i, j;
// 下标末点
for (i = index; i >= 0; i--) {
if (Character.isDigit((char) buf[i])) {
end = i;
break;
}
}
if (i == 0)
continue;
// 下标起点
for (j = end; j >= 0; j--) {
if (!Character.isDigit((char) buf[j])) {
start = j + 1;
break;
}
}
// 时间值截取
curTime = Integer.parseInt(new String(buf, start,
end + 1 - start));
snum++; // 成功接收次数加1
totalTime += curTime; // 计算总时间
if (curTime < minTime) {
minTime = curTime;
} // 最小时间
if (curTime > maxTime) {
maxTime = curTime;
} // 最大时间
}
} else if (line.split(" ").length < 4) {
count--; // 计数器自减1
fnum++; // 失败接收次数加1
} else {
stateInfo += line + "\n";
}
}
if (totalTime == 0) {
minTime = 0;
}
// 已发送包数
datas2[0] = "" + (snum + fnum);
datas2[1] = "" + snum;
datas2[2] = "" + fnum;
if (snum == 0 && fnum == 0) {
state = -1;
fnum = 1;
} else {
state = 0;
}
BigDecimal fnum0 = new BigDecimal(fnum);
BigDecimal tnum0 = new BigDecimal(snum + fnum);
DecimalFormat df = new DecimalFormat("####0.00");
datas2[3] = ""
+ ((new BigDecimal(df.format(fnum0.divide(tnum0,2,RoundingMode.HALF_UP))))
.multiply(new BigDecimal(100)));
datas2[4] = "" + minTime;
datas2[5] = "" + maxTime;
datas2[6] = "" + (snum == 0 ? 0 : (totalTime / snum));
} catch (Exception e) {
state = -1;
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}finally{
if(in!=null){try {
in.close();
} catch (IOException e) {
logger.error("",e);
}}
if(process!= null)process.destroy();
process = null;
}
if (state != -1) {
datas.add((snum + fnum) + "");// 尝试次数,
datas.add(nextTime.getTimeInMillis() + "");// 下次计划监测时间,
// -- 执行状态是否成功,记录的状态是否正常(用于报警),
String[] pArray = getAlarmState(Common.getAlarmInfoMap().get(
sitInfoId.longValue() + ""), datas2);
if (pArray == null && snum > 0) {
datas.add("1"); // 执行状态 正常
datas.add(""); // 告警列序号,
datas.add(""); // 告警级别,
datas.add(""); // 告警值,
} else {
datas.add("0"); // 执行状态 非正常
datas.add(pArray == null ? "" : pArray[0]); // 告警列序号,
datas.add(pArray == null ? "" : pArray[1]); // 告警级别,
datas.add(pArray == null ? "" : pArray[2]); // 告警值,
}
if(snum == 0){
// stateInfo = "目标主机ping失败 \n"+stateInfo;
// stateInfo = "Failed to ping the target host \n"+stateInfo;
stateInfo = "i18n_server.PingThread.ping_n81i \n"+stateInfo;
}
datas.add(stateInfo); // 状态信息(描述信息),
datas.add(stateInfo); // 性能数据,
datas.addAll(Arrays.asList(datas2));// 监测具体数据信息(每个字段一列)
} else {
datas.add((snum + fnum) + ""); // 尝试次数,
datas.add(nextTime.getTimeInMillis() + "");// 下次计划监测时间,
datas.add("-1"); // 执行状态
datas.add(""); // 告警列序号,
datas.add(""); // 告警级别,
datas.add(""); // 告警值,
datas.add(stateInfo); // 状态信息(描述信息),
datas.add(stateInfo); // 性能数据,
}
//- 存入缓存
try {
Common.addDeteData(CSVUtils.csvBytesPrinter(datas, Constants.COMMON_TEXT_CODING));
logger.debug("监测数据以 CSV格式 保存完成");
} catch (Exception e) {
logger.error("Monitoring data to save exceptions in CSV format", e);
}
} catch (Exception ex) {
logger.error("",ex);
String[] alarm = Common.alarmExceptionInfo(sitInfoId, pingIp, Constants.DETEC_PING_STR, "", startTime, 1,Constants.DETECTION_INFO_ALARM_WRONG, ex.getMessage());
Common.addAlarmData(alarm);
} finally {
if(downLatch != null){
downLatch.countDown();
}
try {
if (in != null)
in.close();
} catch (IOException e) {
logger.error(ExceptionPrintUtils.printExceptionStack(e));
}
}
}
// 获得当前的报警设置信息,与相应字段值比较
private String[] getAlarmState(List<AlarmInfo> alarmInfos, String[] sysData) {
String[] strs = null;
if (alarmInfos != null) {
strs = new String[] { "", "", "" };
for (AlarmInfo alarm : alarmInfos) {
if (sysData.length >= alarm.getShowNum()) {
Double data = Math.abs(Double.parseDouble(sysData[alarm
.getShowNum() - 1]));
if("equal".equals(alarm.getPoliceSysmbols())){
if((data+"").equals(alarm.getPoliceValue())){
strs[0] += alarm.getShowNum() + "|";// 告警序列号
strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
strs[2] += alarm.getPoliceValue() + "|"; //告警值
}
}
else if("include".equals(alarm.getPoliceSysmbols())){
if((data+"").indexOf(alarm.getPoliceValue())!=-1){
strs[0] += alarm.getShowNum() + "|";// 告警序列号
strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
strs[2] += alarm.getPoliceValue() + "|"; //告警值
}
}
else if("exclude".equals(alarm.getPoliceSysmbols())){
if((data+"").indexOf(alarm.getPoliceValue())==-1){
strs[0] += alarm.getShowNum() + "|";// 告警序列号
strs[1] += alarm.getPoliceLevel() + "|"; //告警级别
strs[2] += alarm.getPoliceValue() + "|"; //告警值
}
}
else{
double result = data - Double.parseDouble(alarm.getPoliceValue());
if ((">".equals(alarm.getPoliceSysmbols()) && result > 0)
|| ("<".equals(alarm.getPoliceSysmbols()) && result < 0)
|| ("=".equals(alarm.getPoliceSysmbols()) && result == 0)
|| (">=".equals(alarm.getPoliceSysmbols()) && result >= 0)
|| ("<=".equals(alarm.getPoliceSysmbols()) && result <= 0)) {
strs[0] += alarm.getShowNum() + "|";// 告警序列号
strs[1] += alarm.getPoliceLevel() + "|"; // 告警级别
strs[2] += alarm.getPoliceValue() + "|"; // 告警值
}
}
}
}
for (int i = 0; i < strs.length; i++) {
if (strs[i].length() > 0) {
strs[i] = strs[i].substring(0, strs[i].length() - 1);
}
}
}
if (strs != null && "".equals(strs[0])) {
strs = null;
}
return strs;
}
/* public static void main(String [] args) {
Thread thread = new Thread(new PingThread("Ping Thread",10l,"10.0.6.11",2,100,3));
// String name,Long sitInfoId,String socketIp,int socketPort,long gap,long outTime,long maxTimes
thread.start();
}*/
}

Some files were not shown because too many files have changed in this diff Show More