DowntimeServer.java
12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package com.sitech.ismp.check.downtime;
import com.sitech.ismp.app.event.KPI2Event;
import com.sitech.ismp.coll.basic.TblATO_EVENT;
import com.sitech.util.Base62Util;
import com.sitech.util.RandomGUID;
import com.sitech.util.upload.RomoteController;
import com.sitech.util.upload.SSHThread;
import com.sitech.util.upload.TelnetThread;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* @author frank zmm@honggroup.com.cn
* @Description: 宕机检测MBean对应Server类。
* ping的布尔结果 true:能ping通, false:ping不通
* ssh连接的布尔结果 true:能ssh连接, false:ssh连接异常
* @Package com.sitech.ismp.check.downtime
* @ClassName: com.sitech.ismp.check.downtime.DowntimeServer
* @date 2017年04月12日 16:22
*/
public class DowntimeServer implements Runnable{
private static Logger log=Logger.getLogger(DowntimeServer.class);
private DowntimeBean bean;
DowntimeHistoryDao historyDao=new DowntimeHistoryDao();
public DowntimeServer(DowntimeBean bean){
this.bean=bean;
}
/**
* 1 对表中的主机进行ping操作。
* 2 对表中的主机进行SSH登录认证。
* 3 发送告警信息。
*/
@Override
public void run(){
getPingResult(bean);
getSshResult(bean);
sendEvent2Workstation(bean);
}
/**
* 将每个IP ping后的结果设置到pingState属性上。
* @param bean
* @return
*/
public void getPingResult(DowntimeBean bean){
String ipAddr=null;
log.info("============================== ping all parames ======================");
log.info(bean.toString());
ipAddr=bean.getDEVICE_IP();
boolean temp=pingIpAddress(ipAddr);
bean.setPingState(temp);
}
/**
* 进行SSH连接,并设置对应告警的内容。
* @param bean
* @return
*/
public void getSshResult(DowntimeBean bean){
boolean pingState=bean.isPingState(); // true:能ping通, false:ping不通
log.info("========== pingState=== "+pingState+"==========");
boolean sshState=contentWithSsh(bean);
log.info("========== sshState=== "+sshState+"==========");
if(!pingState){ // ping 不通 false
if(!sshState){ // ssh 不能连接 严重告警
bean.setWarningLevel(1);
bean.setWarningResult(bean.getDEVICE_IP()+" 的主机连接异常,请检查网络是否正常或主机宕机!");
log.info("========== bean.setWarningResult sshState ="+sshState+",=ip is ["+bean.getDEVICE_IP()+"] host connect error");
}
}else{ //能ping 通
if(!sshState){ // ssh 不能连接 重要告警
bean.setWarningLevel(2);
bean.setWarningResult(bean.getDEVICE_IP()+" 的主机不能进行登录,请检查用户名或密码!!");
log.info("========== bean.setWarningResult sshState ="+sshState+",=ip is["+bean.getDEVICE_IP()+"] host login error");
}
}
}
/**
* 将告警信息发送到Workstation。
* 当ping的结果为false的时候才发送。
* @param bean
*/
private void sendEvent2Workstation(DowntimeBean bean){
log.info("******************************************************");
log.info("*************** sendEvent2Workstation ****************");
log.info("******************************************************");
log.info(bean.toString());
if(!bean.isSshState()){
KPI2Event event=new KPI2Event();
TblATO_EVENT tblato_event = new TblATO_EVENT();
String eventId= RandomGUID.getRandomGUID();
try {
tblato_event.setEVENT_ID(eventId); // 随即生成一个GUID作为唯一键
tblato_event.setUNIT_ID(bean.getUnitId()); // UNIT_ID在页面显示的为平台类型。
tblato_event.setKPI_ID("FM-00-01-001-999");
tblato_event.setKPI_VALUE(bean.getWarningResult());
tblato_event.setEVENT_TITLE(bean.getWarningResult());
tblato_event.setEVENT_CLASS(bean.getWarningLevel()); // 告警级别
tblato_event.setCLL_TIME(new java.util.Date());
tblato_event.setGENERANT_TIME(new java.util.Date());
tblato_event.setCFG_GUID(RandomGUID.getRandomGUID());
log.info("hava finish set values to TblATO_EVENT!");
} catch (ParseException e) {
log.error("set values to TblATO_EVENT hava error!",e);
}
try {
event.sendEvent2Workstation(tblato_event);
addDowntimeHistory(bean);
log.info("have write object(TblATO_EVENT) to Workstation!");
} catch (Exception e) {
log.error("have write object(TblATO_EVENT) to Workstation have error!",e);
}
}
}
private void addDowntimeHistory(DowntimeBean bean){
DowntimeHistoryBean historyBean=new DowntimeHistoryBean();
historyBean.setDEVICE_ID(bean.getDEVICE_ID());
historyBean.setDEVICE_IP(bean.getDEVICE_IP());
SimpleDateFormat formaF=new SimpleDateFormat("yyyy-MM-dd");
String date=formaF.format(new Date())+"";
date=date.substring(0,10);
historyBean.setCREATE_DATE(date);
historyDao.addDowntimeHistory(historyBean);
}
/**
* 获取ping 后的结果,是否可以平通指定的IP。
* @param ipAddr
* @return
*/
private boolean pingIpAddress(String ipAddr){
int pingErrorCount=0; // ping 不通的次数,ping3次。
int interval=8; // 时间间隔8秒。
boolean flag=false;
boolean temp=false;
for(int i=0;i<3;i++){
temp=executeCommand(ipAddr); // ping不通返回false。
log.info("["+ipAddr+"]ping result is ["+temp+"],(true:can connect;false:can't connect)");
if(!temp){
pingErrorCount++;
}
try {
Thread.sleep(interval*1000);
log.info("ping ["+ipAddr+"] trread sleep "+interval+" secound........");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(pingErrorCount == 3){
log.info("["+ipAddr+"] can't connect 3 times.");
}else{
flag=true;
log.info("["+ipAddr+"] can connect.");
}
return flag;
}
/**
* 进行ssh连接,判断是否可以连接成功。
* windows操作系统使用 TelnetThread类连接。 Windows的客户端需要配置并开启Telnet相关的服务。
* @return
*/
private boolean contentWithSsh(DowntimeBean bean){
String protocol=bean.getPROTOCOL();
String ipAddr=bean.getDEVICE_IP();
String deviceAlias=bean.getDEVICE_ALIAS();
int protocolPort=bean.getPROTOCOL_PORT();
String userName=bean.getUSER_NAME();
String password=bean.getPASSWORD();
bean.setUnitId(getUnitId(deviceAlias));
log.info("execute contentWithSsh method ......");
boolean temp=false;
RomoteController tt = null;
log.info("host params is: ipAddr="+ipAddr+",protocol="+protocol+",protocolPort="+protocolPort+",userName="+userName);
if(loginParamterIsOk(protocol,ipAddr,protocolPort,userName,password,deviceAlias)){
try {
if (protocol != null && protocol.equalsIgnoreCase("telnet")) {
tt = new TelnetThread(ipAddr, protocolPort, userName, password);
} else if (protocol != null && protocol.equalsIgnoreCase("ssh")) {
tt = new SSHThread(ipAddr, protocolPort, userName, password);
}else{
log.error("===================== unknown protocol =====================");
}
}catch (Exception e){
log.error(protocol+"connect have exception!");
}
tt.initial();
boolean flag=tt.isAuthorized();
log.info("******************* tt.isAuthorized() result is "+flag);
if (flag){ // 认证通过
log.info(ipAddr+" SSH connect,Authorized result is true authorized success!");
temp=true;
bean.setSshState(true);
}else{
log.info(ipAddr+" SSH connect,Authorized result is false authorized fail!!");
bean.setSshState(false);
}
}
return temp;
}
/**
* 判断所有的参数是否为空。
* @param protocol 协议类型
* @param ipAddr IP地址
* @param protocolPort 协议端口
* @param userName 用户名
* @param password 密码
* @param deviceAlias 主机别名
* @return
*/
private boolean loginParamterIsOk(String protocol,String ipAddr,int protocolPort,String userName,
String password,String deviceAlias){
boolean flag=true;
if(StringUtils.isEmpty(protocol)){
flag=false;
}
if(StringUtils.isEmpty(ipAddr)){
flag=false;
}
if(StringUtils.isEmpty(protocolPort+"")){
flag=false;
}
if(StringUtils.isEmpty(userName)){
flag=false;
}
if(StringUtils.isEmpty(password)){
flag=false;
}
if(StringUtils.isEmpty(deviceAlias)){
flag=false;
}
return flag;
}
private String getUnitId(String deviceAlias){
StringBuffer bf=new StringBuffer("10-10-99-98:");
bf.append(deviceAlias).append("_").append(getEncryptStr());
return bf.toString();
}
/**
* 返回加密后的一个唯一字符串。
* @return
*/
private String getEncryptStr(){
SimpleDateFormat forma=new SimpleDateFormat("yyMMddHHmmss");
Random rr= new Random();
String str=rr.nextInt(999)+forma.format(new Date())+rr.nextInt(999);
return Base62Util.encode(Long.parseLong(str));
}
/**
* 返回ping后的结果。
* @param ipAddr ip 地址。
* @return
*/
private boolean executeCommand(String ipAddr){
String command = "/bin/ping -c 3 -w 3 " + ipAddr;;
// 执行command 命令。
boolean flag=false;
String line = null;
StringBuilder sb = new StringBuilder();
Runtime runtime = Runtime.getRuntime();
Process process = null;
long startTime = new Date().getTime();
try {
process = runtime.exec(command);
} catch (IOException e) {
log.error("execute command ["+command+"] has some error!");
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
log.error("======== bufferedReader.readLine() has some error!");
}
String pingResult=sb.toString();
/**
* 当执行结果出现下面字符说明已经执行完成。
* ping 通的时候 结果包含【min/avg/max/mdev】
* ping 不通的时候 结果包含【100% packet loss】
*/
if(pingResult.contains("100% packet loss") || (pingResult.contains("min/avg/max/mdev"))){
process.destroy();
log.info("execute command ["+command+"] finish!");
}
String os = System.getProperty("os.name").toLowerCase();
log.info("------------ operator system is :" + os);
// 解析command命令结果,包含【100% packet loss】 意味着ping不通,返回 false。
if(os.indexOf("linux") >= 0){
if (!StringUtils.isEmpty(pingResult)) {
if(!pingResult.contains("100% packet loss")){
flag = true;
}
}
}
return flag;
}
/**
* 添加已经发送的告警信息。
* @param bean,取出对象中的ID与IP,外加时间(年月日)
*/
public void addSendedEvent(DowntimeBean bean){
}
}