CollIBMWithCMD.java
49.2 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
package com.sitech.ismp.coll.centercoll;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.sitech.ismp.coll.CollBase;
import com.sitech.ismp.coll.basic.TblATO_KPIDETAIL;
import com.sitech.util.DES3;
import com.sitech.util.Formater;
import com.sitech.util.Ping;
import com.sitech.util.upload.RomoteController;
import com.sitech.util.upload.SSHThread;
import com.sitech.util.upload.TelnetUtil;
/**
* IBM主机集中采集
*
* 2012-12-05 LINXC代码整理优化
*/
public class CollIBMWithCMD {
private Logger logger = Logger.getLogger(CollIBMWithCMD.class);
String preUnitId = "10-10-20";
String deviceName = "";
String ipAddr;
String deviceId = "";
double noncompSize = 0d;
RomoteController tt = null;
private void init(HashMap<String, String> params) {
ipAddr = params.get("IP_ADDR");
deviceName = params.get("HOST_NAME");
deviceId = Formater.neatenunitid(deviceName);
String username = params.get("USERNAME");
String password = params.get("PASSWORD");
password = DES3.decrypt(password);
String specPrompt = params.get("SPEC_PROMPT");
String protol = (String) params.get("PROTOCOL");
if (protol != null && protol.equals("telnet")) {
tt = new TelnetUtil(ipAddr, 23, username, password);
} else {
tt = new SSHThread(ipAddr, 22, username, password);
}
try{
noncompSize = Double.parseDouble(params.get("NON_COMP"));
}catch (Exception ex){
noncompSize = 0d;
}
try{
tt.initial();
} catch (Exception e) {
logger.error("Exception while init IBM center collector!!", e);
}
}
/**
* @return 采集时间
*/
private String getCollTime(){
try{
return Formater.datetimeToString(new Date());
}catch (Exception e) {
logger.error("Exception while getCollTime()", e);
}
return null;
}
/**
* 采集主机配置信息
*/
public Vector<TblATO_KPIDETAIL> getConfig(HashMap<String, String> params) {
// 保存采集结果
CollBase collResult = new CollBase();
try {
logger.info("Begin collect IBM host config...");
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
//判断如果是telnet,则执行如下代码
if(tt instanceof TelnetUtil)
{
try
{
List<String> commandList= new ArrayList<String>();
commandList.add("prtconf |grep 'Number Of Processors:'");
commandList.add("prtconf |grep 'Processor Type:'");
commandList.add("prtconf |grep 'Processor Clock Speed:'");
commandList.add("prtconf |grep 'Good Memory Size:'");
commandList.add("oslevel");
commandList.add("lspv");
commandList.add("swap -l | awk '{print $4}'");
commandList.add("lsps -s | grep -v 'Paging Space'");
commandList.add("netstat -in | grep 127.0.0.1");
commandList.add("netstat -in | grep -v Mtu | grep -v 127.0.0.1");
commandList.add("df -k | grep -v Filesystem");
tt.executeCommand(commandList);
}
catch (Exception e)
{
e.printStackTrace();
}
}
String totalUnitId = preUnitId + "-10:" + deviceId + "-total";
// 增加采集时间指标
// collResult.addKPI(totalUnitId, "CM-00-01-001-22", getCollTime());
// 常用ip,用于告警标题
collResult.addKPI(totalUnitId, "CM-00-01-001-50", params.get("IP_ADDR"));
// 主机名称
collResult.addKPI(totalUnitId, "CM-00-01-001-01", deviceName);
// 主机类型
collResult.addKPI(totalUnitId, "CM-00-01-001-03", "IBM");
// CPU个数
collResult.addKPI(totalUnitId, "CM-00-01-001-04", getCpuNum());
// CPU类型
collResult.addKPI(totalUnitId, "CM-00-01-001-05", getCpuType());
// CPU主频
collResult.addKPI(totalUnitId, "CM-00-01-001-06", getCpuSpeed());
// 内存大小
collResult.addKPI(totalUnitId, "CM-00-01-001-07", getMemSize());
// 系统版本
String osVersion = getOsVersion();
collResult.addKPI(totalUnitId, "CM-00-01-001-08", getOsVersion());
// 主机内置盘总大小
collResult.addKPI(totalUnitId, "CM-00-01-001-09", getDiskTotalSize());
// 交换分区大小
collResult.addKPI(totalUnitId, "CM-00-01-001-13", getPagespace(osVersion));
// 采集网卡指标
String preNetUnitId = preUnitId + "-16:" + deviceId;
String loopback_name = "grep";
// 得到本地网卡的名称
Vector<String> loopback = tt
.getResultAsVector("netstat -in | grep 127.0.0.1");
if (loopback != null && loopback.size() > 0) {
loopback_name = split((String) loopback.elementAt(0), 0);
}
Vector<String> lancard=null;
if(tt instanceof TelnetUtil)
{
try
{
lancard = tt
.getResultAsVector("netstat -in | grep -v Mtu | grep -v 127.0.0.1");
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
// 采集非本地网卡的 物理地址与ip地址, 网卡数量
lancard = tt
.getResultAsVector("netstat -in | grep -v Mtu | grep -v 127.0.0.1 | grep -v "
+ loopback_name);
}
Set lancardSet = new HashSet();
String service_ip = "";
String value = "";
for (int i = 0; i < lancard.size(); i++) {
String lan_name = split((String) lancard.elementAt(i), 0);
String network = split((String) lancard.elementAt(i), 2); // 如果含有link,则为物理地址,否则为本地地址
if (network.indexOf("link") > -1) {
// 物理地址
value = split((String) lancard.elementAt(i), 3);
collResult.addKPI(preNetUnitId + "-" + lan_name, "CM-00-01-001-12", value);
} else {
value = split((String) lancard.elementAt(i), 3);
// ip地址,同一网卡可能出现多个ip地址的情况
collResult.addKPI(preNetUnitId+ "-" + lan_name, "CM-00-01-001-11", value);
service_ip = service_ip + "," + value;
}
lancardSet.add(lan_name.trim());
}
// 主机(服务)地址 CM-00-01-001-02, 将所有ip地址累加
collResult.addKPI(totalUnitId, "CM-00-01-001-02", service_ip.substring(1, service_ip.length()));
// KPI: CM-00-01-001-10 系统网络接口数
collResult.addKPI(totalUnitId, "CM-00-01-001-10", Formater.formatDecimalKpivalue(String.valueOf(lancardSet.size())));
// 文件系统
String fsPreUnitId = this.preUnitId + "-14:" + deviceId;
// 16 CM-00-01-001-16 文件系统名称 文件系统的标识 1天 字符串型
// 17 CM-00-01-001-17 文件系统的总空间 主机文件系统总的可用量 1天 数值型
// 文件系统名称 ,并 计算文件系统总空间
Vector fileSystem = tt
.getResultAsVector("df -k | grep -v Filesystem");
long fs_sum = 0; // 文件系统总空间,兆
for (int i = 0; i < fileSystem.size(); i++) {
try {
String fs_info = (String) fileSystem.elementAt(i);
String fs_name = collResult.split(fs_info, 6);
if (fs_name != null && fs_name.trim().equals("/")) {
collResult.addKPI(fsPreUnitId+ "-" + Formater.neatenunitid("//"),
"CM-00-01-001-16", fs_name);
} else {
collResult.addKPI(fsPreUnitId+ "-" + Formater.neatenunitid(fs_name),
"CM-00-01-001-16", fs_name);
}
String fs_size = collResult.split(fs_info, 1);
fs_size = (fs_size == null || fs_size.trim().length() == 0 || fs_size
.trim().equals("-")) ? "0" : fs_size.trim();
long lfs_size = Long.parseLong(fs_size);
fs_sum = fs_sum + lfs_size;
} catch (Exception e) {
logger.error("Error", e);
}
}// end for
collResult.addKPI(totalUnitId, "CM-00-01-001-17", Formater
.formatDecimalKpivalue(String.valueOf(fs_sum / 1024)));
// 系统运行时长 PM-20-20-001-52
collResult.addKPI(totalUnitId, "PM-20-20-001-52", getSysUptime());
logger.info("end getConfig");
} catch (Exception e) {
logger.error("Exception while getConfig", e);
} finally {
tt.close();
}
return collResult.getKPISet();
} // End getConfig
/**
* 采集交换分区大小
*/
private String getPagespace(String osVersion) {
String pagespaceSize = "-";
try{
if ((osVersion.indexOf("52") == 0)
|| (osVersion.indexOf("53") == 0)) {
Vector<String> result_swap1 = tt
.getResultAsVector("swap -l | awk '{print $4}'");
int swap_sum = 0;
for (int i = 1; i < result_swap1.size(); i++) {
String swap_total_info = (String) result_swap1
.elementAt(i);
String swap_size = swap_total_info.substring(0,
swap_total_info.length() - 2);
swap_sum = swap_sum + Integer.parseInt(swap_size);
}
pagespaceSize = String.valueOf(swap_sum);
} else {
// "4096MB 32%"
Vector<String> result_swap1 = tt
.getResultAsVector("lsps -s | grep -v 'Paging Space'");
String swap_info = (String) result_swap1.elementAt(0);
String swap_size = split(swap_info, 0);
pagespaceSize = swap_size.substring(0, swap_size.length() - 2); // 去掉后面的
}
}catch (Exception e) {
logger.error("Exception while getPagespace", e);
}
logger.info("-- pagespace size : " + pagespaceSize);
return pagespaceSize;
}
/**
* @return 系统运行时间
*/
private String getSysUptime(){
Vector<String> host = tt.getResultAsVector("uptime | awk '{print $3\" \"$4}'");
String uptime = (String) host.elementAt(0);
return uptime;
}
/**
* 采集内置磁盘总大小
* @return
*/
private String getDiskTotalSize() {
String diskTotalSize = "";
try{
Vector<String> disk_infoV = tt.getResultAsVector("lspv");
Vector<String> disk_nameV = new Vector<String>();
Vector<String> active_disk_nameV = new Vector<String>();
for (int i = 0; i < disk_infoV.size(); i++) {
String diskInfo = (String) disk_infoV.elementAt(i);
String disk_name = split(diskInfo, 0);
disk_nameV.add(disk_name);
if (diskInfo.indexOf("active") > 0) {
active_disk_nameV.add(disk_name);
}
}
int disk_total = 0;
if(tt instanceof TelnetUtil)
{
try
{
RomoteController ttClone=tt.cloneObject();
List<String> commandList= new ArrayList<String>();
for (int i = 0; i < active_disk_nameV.size(); i++) {
commandList.add("lspv "
+ (String) active_disk_nameV.elementAt(i)+ " |grep 'TOTAL PPs:'");
}
ttClone.executeCommand(commandList);
for (int i = 0; i < active_disk_nameV.size(); i++) {
Vector disk_total1 = ttClone.getResultAsVector("lspv "
+ (String) active_disk_nameV.elementAt(i)
+ " |grep 'TOTAL PPs:'");
String disk_temp = (String) disk_total1.elementAt(0);
int index1 = disk_temp.indexOf("(");
int index2 = disk_temp.indexOf("megabytes");
disk_temp = disk_temp.substring(index1 + 1, index2).trim();
disk_total = disk_total + Integer.parseInt(disk_temp);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
for (int i = 0; i < active_disk_nameV.size(); i++) {
Vector disk_total1 = tt.getResultAsVector("lspv "
+ (String) active_disk_nameV.elementAt(i)
+ " |grep 'TOTAL PPs:'");
String disk_temp = (String) disk_total1.elementAt(0);
int index1 = disk_temp.indexOf("(");
int index2 = disk_temp.indexOf("megabytes");
disk_temp = disk_temp.substring(index1 + 1, index2).trim();
disk_total = disk_total + Integer.parseInt(disk_temp);
}
}
diskTotalSize = String.valueOf(disk_total);
}catch (Exception e) {
logger.error("Exception while getDiskTotalSize()", e);
diskTotalSize = "-";
}
logger.info("-- disk total size: " + diskTotalSize);
return diskTotalSize;
}
/**
* 采集系统版本
*/
private String getOsVersion() {
String version = "-";
try {
version = tt.getResultAsStr("oslevel");
version = split(version, 0);
} catch (Exception e) {
logger.error("Exception while getOsVersion!", e);
}
logger.info("-- os version: " + version);
return version;
}
/**
* CPU主频
*/
private String getCpuSpeed() {
String cpuSpeed = "-";
try {
Vector<String> cpunum = tt
.getResultAsVector("prtconf |grep 'Processor Clock Speed:'");
for (String line : cpunum) {
if (line.indexOf("Processor Clock Speed:") >= 0) {
cpuSpeed = split(line, 3);
break;
}
}
} catch (Exception e) {
logger.error("Exception while getCpuSpeed!", e);
}
logger.info("-- cpu speed: " + cpuSpeed);
return cpuSpeed;
}
/**
* 采集内存大小
*/
private String getMemSize() {
String memSize = "-";
try {
Vector<String> cpunum = tt
.getResultAsVector("prtconf |grep 'Good Memory Size:'");
for (String line : cpunum) {
if (line.indexOf("Good Memory Size:") >= 0) {
line = line.substring(line.indexOf("Size:") + 5);
memSize = split(line, 0);
break;
}
}
} catch (Exception e) {
logger.error("Exception while getMemSize!", e);
}
logger.info("-- memory size: " + memSize);
return memSize;
}
/**
* 采集CPU类型
*/
private String getCpuType() {
String cpuType = "-";
try {
Vector<String> cpunum = tt
.getResultAsVector("prtconf |grep 'Processor Type:'");
for (String line : cpunum) {
if (line.indexOf("Processor Type:") >= 0) {
cpuType = split(line, 2);
break;
}
}
} catch (Exception e) {
logger.error("Exception while getCpuType!", e);
}
logger.info("-- cpu type: " + cpuType);
return cpuType;
}
/**
* 采集CPU个数
*/
private String getCpuNum() {
String cpuNum = "-";
try {
Vector<String> cpunum = tt
.getResultAsVector("prtconf |grep 'Number Of Processors:'");
for (String line : cpunum) {
if (line.indexOf("Number Of Processors:") >= 0) {
cpuNum = split(line, 3);
break;
}
}
} catch (Exception e) {
logger.error("Exception while getCpuNum!", e);
}
logger.info("-- cpu num: " + cpuNum);
return cpuNum;
}
/**
* 得到主机名
*/
private String getHostName() {
Vector<String> host = tt.getResultAsVector("uname -a");
String host_name = (String) host.elementAt(0);
host_name = split(host_name, 1);
return host_name;
}
/**
* 采集CPU性能指标
*/
public Vector<TblATO_KPIDETAIL> getCpu(HashMap<String, String> params) {
logger.info("Begin getCpu");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
if(tt == null || !tt.isAuthorized()){
logger.error("RemoteController is null!!");
}
//判断如果是telnet,则执行如下代码
if(tt instanceof TelnetUtil)
{
logger.info("Use TelnetUtil...");
try
{
List<String> commandList= new ArrayList<String>();
commandList.add("vmstat 2 3");
commandList.add("ifconfig -a");
tt.executeCommand(commandList);
}
catch (Exception e)
{
e.printStackTrace();
logger.error("Exception while TelnetUtil.executeCommand()", e);
}
}
String unitId = this.preUnitId + "-11:" + deviceId + "-cpu";
Vector<String> vmstatResult = tt.getResultAsVector("vmstat 2 3");
String log = "-- doCommand: vmstat 2 3\n";
if(vmstatResult == null || vmstatResult.size()==0){
logger.info("-- do vmstat 2 3, result is null" );
}
for(String temp : vmstatResult){
log += temp + "\n";
}
logger.info("--a1:" + log);
String cpurun = vmstatResult.get(vmstatResult.size() - 1);
logger.info("--a2:" + cpurun);
try {
// CPU时间:空闲百分比
collResult.addKPI(unitId, "PM-00-01-001-01", split(cpurun, 15));
// CPU时间:系统百分比
collResult.addKPI(unitId, "PM-00-01-001-02",split(cpurun, 14));
// CPU时间:用户百分比
collResult.addKPI(unitId, "PM-00-01-001-03", split(cpurun, 13));
// CPU时间:等待百分比
collResult.addKPI(unitId, "PM-00-01-001-04", split(cpurun, 16));
// CPU运行队列中进程个数
collResult.addKPI(unitId, "PM-00-01-001-06", split(cpurun, 0));
// CPU使用率
double cpuUsage = 100 - Double.parseDouble(split(cpurun, 15));
collResult.addKPI(unitId, "PM-00-01-001-05", String.valueOf(cpuUsage));
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception while getCpu()", e);
}
try {
// 网卡状态
String netPreUnitId = this.preUnitId + "-16:" + deviceId;
Vector<String> ifconfigV = tt.getResultAsVector("ifconfig -a");
String log1 = "-- doCommand: ifconfig -a\n";
for(String temp : ifconfigV){
log1 += temp + "\n";
}
logger.info(log1);
for(String line : ifconfigV){
if (line.indexOf("flags") < 0) {
continue;
}
String lanName = line.substring(0, line.indexOf(':'));
String lanState = "";
try {
lanState = line.substring(line.indexOf('<') + 1, line.indexOf(',',line.indexOf('<')));
} catch (Exception e) {
logger.error("Exception while getCpu()", e);
lanState = "-";
}
String netUnitId = netPreUnitId + "-" + Formater.neatenunitid(lanName);
collResult.addKPI(netUnitId, "FM-00-01-001-03", lanState);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception while getCpu()", e);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception while getCpu!", e);
} finally {
tt.close();
}
logger.info("end getCpu");
return collResult.getKPISet();
}
/**
* PM-00-01-002-01 内存的使用率 vmstat 中的memory - free *4k 为空闲内存
* PM-00-01-002-02 内存交换请求数 vmstat 中的page - fr
* PM-00-01-002-03 内存交换页换进率 vmstat 中的page - pi
* PM-00-01-002-04 内存交换页换出率 vmstat 中的page - po
* PM-00-01-002-05 内存队列数 等待内存的进程或线程数量vmstat 中的 kthr - r
* PM-00-01-002-06 系统内存使用率 系统内存占所有物理内存的百分比 无此概念
* PM-00-01-002-07 用户内存使用率 用户内存占所有物理内存的百分比 无此概念
* PM-00-01-002-08 文件系统数据缓冲命中率 文件系统数据缓冲命中率 使用sar 2 2 , 平均读写命中率
*/
public Vector<TblATO_KPIDETAIL> getMemory(HashMap<String,String> params) {
logger.info("begin getMemory");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
if(tt instanceof TelnetUtil)
{
try
{
List<String> commandList= new ArrayList<String>();
commandList.add("vmstat 2 5");
commandList.add("sar -b 2 2");
commandList.add("prtconf |grep 'Good Memory Size:'");
tt.executeCommand(commandList);
}
catch (Exception e)
{
e.printStackTrace();
}
}
String unitId = this.preUnitId + "-12:" + deviceId + "-memory";
Vector<String> memoryout = tt.getResultAsVector("vmstat 2 5");
String memoryrun = memoryout.get(memoryout.size() - 1);
// PM-00-01-002-01 内存的使用率 主机内存的使用量与内存总量的比值
try {
// 空余内存 单位:M
int memFree = Integer.parseInt(split(memoryrun, 3)) * 4 / 1024;
// 总内存 单位:M
int memTotal = Integer.parseInt(getMemSize());
// 内存使用率
double memUsage = 100.0 - (memFree * 100.0) / memTotal - noncompSize;
collResult.addKPI(unitId, "PM-00-01-002-01", Formater.formatDecimalKpivalue(String.valueOf(memUsage)));
} catch (Exception e) {
logger.error("Exception while getMemory", e);
}
collResult.addKPI(unitId, "PM-00-01-002-02", split(memoryrun, 7));
collResult.addKPI(unitId, "PM-00-01-002-03", split(memoryrun, 5));
collResult.addKPI(unitId, "PM-00-01-002-04", split(memoryrun, 6));
collResult.addKPI(unitId, "PM-00-01-002-05", split(memoryrun, 6));
// 文件系统数据缓冲命中率
Vector<String> filerate_result = tt.getResultAsVector("sar -b 2 2");
logger.info("filerate_result.size() is " + filerate_result.size());
if (filerate_result != null && filerate_result.size() > 0) {
for (String line : filerate_result) {
if (line.indexOf("Average") < 0) {
continue;
}
int r_rate = Integer.parseInt(split(line, 3));
int w_rate = Integer.parseInt(split(line, 6));
collResult.addKPI(unitId, "PM-00-01-002-08", String.valueOf((r_rate + w_rate) / 2));
}
} else {
logger.warn("error when exe 'sar -b 2 2' , null or nothing return");
}
} catch (Exception e) {
logger.error("Exception while getMemory", e);
} finally {
tt.close();
}
logger.info("end getMemory");
return collResult.getKPISet();
}
/**
* ok
*
* 每秒磁盘读写请求 PM-00-01-003-04/05现在得到的值为 r+w
*
* 在规范磁盘性能指标基础上,增加了FM指标,内置盘状态
*
* 对物理磁盘的状态属性获取目前只通过lspv取得active的磁盘设备。以后要支持所有设备 这里目前通过sar获取所有io设备的情况,而不只是磁盘
*
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getDisk(HashMap<String,String> params) {
logger.info("begin getDisk");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
if(tt instanceof TelnetUtil)
{
try
{
List<String> commandList= new ArrayList<String>();
commandList.add("lspv");
commandList.add("sar -d 5 5");
tt.executeCommand(commandList);
}
catch (Exception e)
{
e.printStackTrace();
}
}
String diskPreUnitId = this.preUnitId + "-13:" + deviceId;
String value = "";// 临时变量
// -----------------获取磁盘名称,后面通过sar命令取设备信息的时候,如果不在磁盘列表中,那么直接过滤掉----------------------------------------
Vector disk_infoV = tt.getResultAsVector("lspv");
Set disk_nameSet = new HashSet();
for (int i = 0; i < disk_infoV.size(); i++) {
String diskInfo = (String) disk_infoV.elementAt(i);
String disk_name = collResult.split(diskInfo, 0);
String pv_state = collResult.split(diskInfo, 3);
if (pv_state == null || "".equals(pv_state)) {
continue;
}
// 磁盘名称
collResult.addKPI(diskPreUnitId + "-" + Formater.neatenunitid(disk_name),
"CM-00-01-001-20", disk_name);
disk_nameSet.add(disk_name.trim());
// System.out.println("disk_name:"+disk_name +" is add to
// disk_nameSet");
}
// 从出现Average的这行开始,每一行表示一个磁盘的数据
// 这里的处理稍微复杂,修改请注意,测试后再发布
try {
Vector diskV = tt.getResultAsVector("sar -d 5 5");
boolean checkAverage = true; // 是否检查Average这个字符串
for (int i = 0; i < diskV.size(); i++) {
String device_valueInfo = (String) diskV.elementAt(i);
String device_name = "inital";
// 设定checkAverage的值
if (checkAverage) {
int iPos = device_valueInfo.indexOf("Average");
if (iPos > -1) {
checkAverage = false;
device_name = "Average_row";
}
}
// 如果不用检查,那么本行就是一个磁盘
if (!checkAverage) {
if (device_name.equals("Average_row")) {
// 说明是Average_row
device_name = split(device_valueInfo, 1);
} else {
device_name = split(device_valueInfo, 0);
}
// System.out.println("device_valueInfo:"+device_valueInfo);
// System.out.println("device_name :"+device_name);
// 在指标获取前,判断该设备是否是磁盘设备,不是的话,不采集
if (!disk_nameSet.contains(device_name.trim())) {
System.out.println("not contains : " + device_name);
continue;
}
String neat_disk_name = Formater
.neatenunitid(device_name);
// 磁盘物理IO操作速率
value = split(device_valueInfo, 5);
collResult.addKPI(diskPreUnitId + "-" + neat_disk_name,
"PM-00-01-003-01", Formater
.formatDecimalKpivalue(value));
// 等待磁盘系统进程线程数
value = split(device_valueInfo, 3);
collResult.addKPI(diskPreUnitId + "-" + neat_disk_name,
"PM-00-01-003-02", Formater
.formatDecimalKpivalue(value));
// 磁盘忙的百分比
value = split(device_valueInfo, 2);
collResult.addKPI(diskPreUnitId + "-" + neat_disk_name,
"PM-00-01-003-03", Formater
.formatDecimalKpivalue(value));
// 每秒读请求
value = split(device_valueInfo, 4);
collResult.addKPI(diskPreUnitId + "-" + neat_disk_name,
"PM-00-01-003-04", Formater
.formatDecimalKpivalue(value));
// 每秒写请求
value = split(device_valueInfo, 4);
collResult.addKPI(diskPreUnitId + "-" + neat_disk_name,
"PM-00-01-003-05", Formater
.formatDecimalKpivalue(value));
}
}
} catch (Exception e) {
e.printStackTrace();
}
// 内置盘状态
// 对于active那列没有值的,使用 '-'代替
// Vector lspvV = tt.getResultAsVector("lspv | grep active");
Vector lspvV = tt.getResultAsVector("lspv");
for (int i = 0; i < lspvV.size(); i++) {
String pvinfo = (String) lspvV.elementAt(i);
String pv_name = split(pvinfo, 0);
String pv_state = split(pvinfo, 3);
// 对于active那列没有值的,使用 '-'代替
if (pv_state == null || pv_state.trim().length() == 0) {
continue;
// pv_state = "-";
}
String neat_pv_name = Formater.neatenunitid(pv_name);
collResult.addKPI(diskPreUnitId + "-"
+ neat_pv_name, "FM-00-01-001-02", pv_state);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
tt.close();
}
logger.info("end getDisk");
return collResult.getKPISet();
}// end getDisk
/**
* PM-00-01-004-01 文件系统使用比率(文件系统已使用的空间与总空间的比值)
* PM-00-01-004-02 交换区使用百分比(交换区使用百分比)
* PM-00-01-004-03 逻辑卷(裸设备)文件系统使用率(各逻辑卷上文件系统的使用率)
*/
public Vector<TblATO_KPIDETAIL> getFileSystem(HashMap<String, String> params) {
logger.info("Begin getFileSystem...");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
if(tt instanceof TelnetUtil)
{
try
{
List<String> commandList= new ArrayList<String>();
commandList.add("df -k");
commandList.add("lsps -s ");
tt.executeCommand(commandList);
}
catch (Exception e)
{
e.printStackTrace();
}
}
String fsPreUnitId = this.preUnitId + "-14" + ":" + deviceId;
// 文件系统总空间
long totalSize = 0;
// 文件系统总已空余空间
long totalFreeSize = 0;
Vector<String> filesystemV = tt.getResultAsVector("df -k");
logger.info(" --Filesystem's count: " + filesystemV.size());
if (filesystemV != null && filesystemV.size() > 0) {
for (int i=1; i<filesystemV.size(); i++) {
String line = filesystemV.get(i);
// 文件系统名称
String fsName = split(line, 6);
// 文件系统使用率
String usedPercent = split(line, 3);
// 文件系统大小
String fsSize = split(line, 1);
// 文件系统剩余大小
String fsFree = split(line, 2);
fsSize = fsSize.equals("-") ? "0" : fsSize;
fsFree = fsFree.equals("-") ? "0" : fsFree;
totalSize = totalSize + Long.parseLong(fsSize);
totalFreeSize = totalFreeSize + Long.parseLong(fsFree);
if (usedPercent.trim().equals("-")) {
usedPercent = "0";
}else if (usedPercent.length() > 1) {
// 去除百分号
usedPercent = usedPercent.substring(0, usedPercent.length() - 1);
}
String fsId = Formater.neatenunitid(fsName);
String unitId = "";
try {
if (fsId != null && fsId.equals("/")) {
unitId = fsPreUnitId + "-//";
} else {
unitId = fsPreUnitId + "-" + fsId;
}
// 文件系统使用率
collResult.addKPI(unitId, "PM-00-01-004-03",
usedPercent);
// 文件系统可用空间
fsFree = String.valueOf(Double.parseDouble(fsFree) / 1024);
collResult.addKPI(unitId, "PM-00-01-004-04", Formater
.formatDecimalKpivalue(fsFree));
// 文件系统挂载磁盘
collResult.addKPI(unitId, "PM-00-01-004-14", split(
line, 0));
} catch (Exception e) {
logger.error("Exception while getFileSystem", e);
}
}
}
String totalUnitId = this.preUnitId + "-10:" + deviceId + "-total";
// PM-00-01-004-01 文件系统总使用率
if (totalSize != 0) {
String totalUsage = Formater.formatDecimalKpivalue(String
.valueOf(100 - totalFreeSize * 100.0 / totalSize));
collResult.addKPI(totalUnitId, "PM-00-01-004-01", totalUsage);
}
Vector<String> swapV = tt.getResultAsVector("lsps -s ");
if (swapV != null && swapV.size() > 0) {
String pagespaceInfo = swapV.get(swapV.size() - 1);
String swapUsage = split(pagespaceInfo, 1);
// 去除百分号
swapUsage = swapUsage.substring(0, swapUsage.length() - 1);
collResult.addKPI(totalUnitId, "PM-00-01-004-02", swapUsage);
}
// netstat -n | awk '/^tcp/ {++state[$NF]} END {for(key in state) print key,"\t",state[key]}'
// LISTEN 303
// CLOSE_WAIT 7
// ESTABLISHED 1003
String strNet = "netstat -n | awk '/^tcp/ {++state[$NF]} END {for(key in state) print key,\"\\t\",state[key]}'";
Vector<String> listNet = tt.getResultAsVector(strNet);
String strNetTypeNums = ",";
if (listNet != null && listNet.size() > 0) {
for (int i = 0; i < listNet.size(); i++) {
String strMsg = listNet.get(i);
String strType = split(strMsg, 0);
String strNum = split(strMsg, 1);
strNetTypeNums += splitNetTypeNum(strType, strNum);
}
}
// 网络连接情况 PM-00-01-900-10
collResult.addKPI(totalUnitId, "PM-00-01-900-10", strNetTypeNums.substring(1, strNetTypeNums.length() - 1));
} catch (Exception e) {
logger.error("Exception while getFileSystem", e);
} finally {
tt.close();
}
logger.info("End getFileSystem!!");
return collResult.getKPISet();
}
public Vector getPing(HashMap<String, String> params){
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
String net_unit = this.preUnitId + "-35:" + deviceId;
List<String> ips = split(params.get("POINT_IPS"), ",");
for(String ip:ips){
String pingResult = "ping -c 5 "+ip+"|grep -E 'transmitted|round-trip'";
Vector pingV = tt.getResultAsVector(pingResult);
if (pingV != null && pingV.size() != 0) {
String unitid = net_unit+"-"+ip;
String responseTimes = "";
String packageLoss = "";
String responseTime ="";
if(pingV.size()>1){
packageLoss = StringUtils.remove(split(pingV.get(0).toString(), 6), "%");
responseTimes = split(pingV.get(1).toString(),3);
responseTime = split(responseTimes,"/").get(1).toString();
}else if(pingV.size()==1){
packageLoss = "100";
responseTime = "∞";
}else {
throw new Exception("get pointIPs failed");
}
collResult.addKPI(unitid, "CM-01-03-001-02", ip);
collResult.addKPI(unitid, "PM-00-01-006-04", packageLoss);
collResult.addKPI(unitid, "PM-00-01-006-05", responseTime);
}
}
}catch (Exception e) {
e.printStackTrace();
} finally {
release();
}
return collResult.getKPISet();
}
/**
* 获取关键进程信息
* @param params
* @return
*/
public Vector getBusiProcess(HashMap<String, String> params) {
logger.info("begin getProcessByKey");
CollBase collResult = new CollBase();
DecimalFormat df = new DecimalFormat("#.##");
try {
init(params);
String pro_PRE_UNITID = preUnitId + "-25";
String processName = params.get("PROCESS_NAME");
if(StringUtils.isNotBlank(processName)) {
String[] processNames = processName.split(",");
for (String _processName : processNames) {
if (StringUtils.isBlank(_processName.trim())) {
continue;
}
String cmd = "ps aux | grep -v grep | grep '" + _processName + "'";
Vector vec = tt.getResultAsVector(cmd);
int _count = -1;
int count = 0;
for (int i = 0; i < 10; i++) {
count = new Integer(String.valueOf(vec.size())).intValue();
Thread.sleep(3000);
logger.info("exec command " + (i + 1) + " t");
if (count != _count) {
vec = tt.getResultAsVector(cmd);
_count = count;
} else {
if (((String) vec.elementAt(0)).length() == 0) {
vec = tt.getResultAsVector(cmd);
_count = count;
continue;
} else {
break;
}
}
}
// 进程关键字 CM-00-01-005-10
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "CM-00-01-005-10", _processName);
// 更新时间 CM-00-03-002-10
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "CM-00-03-002-10", Formater.datetimeToString(new Date()));
// 进程个数 PM-00-01-005-12 CPU使用率 PM-00-01-000-01 内存使用率 PM-00-01-002-01
String temp = "";
String result = "";
Double cpu_usage = 0D;
Double mem_usage = 0D;
for (int i = 0; i < count; i++) {
String proInfo = (String) vec.elementAt(i);
if (StringUtils.isBlank(proInfo)) continue;
String puser = split(proInfo, 0);
String ppid = split(proInfo, 1);
Double cpu = Double.parseDouble(split(proInfo, 2));
Double mem = Double.parseDouble(split(proInfo, 3));
String pstart = split(proInfo, 8);
cpu_usage = cpu_usage + cpu;
mem_usage = mem_usage + mem;
temp += puser + ":" + ppid + ":" + pstart + ",";
if (i == count - 1) {
result += StringUtils.isBlank(ppid) ? "0" : ppid;
} else {
result += StringUtils.isBlank(ppid) ? "0" : ppid + ",";
}
}
// 关键进程PID PM-00-01-005-17
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-005-17", result);
if ("::,".equals(temp) || "".equals(temp)) {
// 借用进程指令行KPI CM-00-01-005-08
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "CM-00-01-005-08", "");
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-005-12", "0");
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-000-01", "0");
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-002-01", "0");
} else {
// 借用进程指令行KPI CM-00-01-005-08
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "CM-00-01-005-08", temp.substring(0, temp.length() - 1));
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-005-12", count + "");
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-000-01", df.format(cpu_usage));
collResult.addKPI(pro_PRE_UNITID + ":" + deviceId + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-002-01", df.format(mem_usage));
}
}
}
} catch (Exception e) {
logger.error("getProcessByKey has error", e);
}
logger.info("end getProcessByKey");
return collResult.getKPISet();
}
public Vector<TblATO_KPIDETAIL> getFileChange(HashMap<String, String> params) {
logger.info("Begin getFileChange...");
logger.info(params.toString());
CollBase collResult = new CollBase();
String UNIT_ID = params.get("KBP_CLASS");
init(params);
try{
// 获得结果
logger.info("-------coll------filepaths--------");
//得到filechange UnitId
String filechangeUnitId = UNIT_ID + "-20:" + deviceId + "-";
String filePaths = params.get("FILE_PATHS");
String[] filePathList = filePaths.split(",");
// 获得结果
for(String tempPath:filePathList) {
Vector<String> fileResult = tt.getResultAsVector("ls -l " +tempPath);
/**
* 分析传入的文件绝对路径参数
* 如果传入的参数中是路径则采集该路径下所有的文件
* 如果传入的参数中包含文件名则采集该文件
*/
if (fileResult.size() > 1) {//说明该tempPath为目录,记录当前目录下文件数(除去文件夹及文件夹下内容)。
Vector<String> dirResult = tt.getResultAsVector("ls -l " +tempPath+" |grep \"^-\"");
//文件数量
collResult.addKPI(filechangeUnitId + tempPath, "PM-01-09-021-01", dirResult.size()+"");
}else {
collResult.addKPI(filechangeUnitId + tempPath, "PM-01-09-021-01", "0");
}
Boolean isChange = checkFileChange(fileResult, tempPath, deviceId);
//文件名称
collResult.addKPI(filechangeUnitId + tempPath, "CM-10-10-020-01", tempPath);
//变动部分有结果,则生成告警指标
collResult.addKPI(filechangeUnitId + tempPath, "FM-10-10-020-01", isChange.toString());
}
}catch (Exception e) {
logger.error("Exception while get fileChange!",e);
}finally {
release();
}
logger.info("END COLL fileChange ");
return collResult.getKPISet();
}
private Boolean checkFileChange(List result,String fileName,String deviceId){
Boolean isChange = false;
try{
String now = this.getVetorString(result);
String data_path = "../filechange";
fileName = StringUtils.replace(fileName,"/","-");
String now_filename = "now_" + deviceId + "-"+fileName+".dat";
String tmp_filename = "tmp_" + deviceId + "-"+fileName+".dat";
String diff_filename = "diff_" + deviceId + "-"+fileName+".dat";
//目录不存在则创建
File f = new File(data_path);
if(!f.exists()){
f.mkdir();
}
File now_file = new File(data_path+"/" + now_filename);// 最新日志信息
File tmp_file = new File(data_path+"/" + tmp_filename);// 上次日志信息
File diff_file = new File(data_path+"/" + diff_filename);// 增量日志
PrintWriter write_now = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(now_file), "GB2312"));
PrintWriter write_tmp = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(tmp_file, true), "GB2312"));
PrintWriter write_diff = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(diff_file), "GB2312"));
String path = now_file.getAbsolutePath();
logger.info("Current path is " + path);
// 日志解析
if (tmp_file.exists() && tmp_file.length() > 0) {// 非第一次采集
write_now.write(now);
write_now.flush();
write_now.close();
// 读取上次日志文件(tmp)
FileReader tmp_reader = new FileReader(tmp_file);
BufferedReader tmp = new BufferedReader(tmp_reader);
String line;
String tmp_file_string = "";
while ((line = tmp.readLine()) != null) {
tmp_file_string += line + "\n";
}
tmp.close();
tmp_reader.close();
// 读取本次日志文件(now),生成差异文件(diff)
FileReader now_reader = new FileReader(now_file);
BufferedReader br = new BufferedReader(now_reader);
while ((line = br.readLine()) != null) {
if (tmp_file_string.indexOf(line) == -1)
write_diff.write(line);
else
continue;
}
br.close();
now_reader.close();
write_diff.flush();
write_diff.close();
write_tmp = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(tmp_file), "GB2312"));
write_tmp.write(now);
write_tmp.flush();
write_tmp.close();
// 生成指标
FileReader diff_reader = new FileReader(diff_file);
BufferedReader diff = new BufferedReader(diff_reader);
//变动部分有结果,则生成告警指标
if (diff.readLine() != null) {
isChange =true;
}
diff.close();
diff_reader.close();
} else {// 第一次采集
write_tmp.write(now);
write_tmp.flush();
write_tmp.close();
write_diff.write(now);
write_diff.flush();
write_diff.close();
}
}catch (Exception e) {
logger.error("Exception while get fileChange!",e);
}finally {
return isChange;
}
}
public Vector<TblATO_KPIDETAIL> getCatalog(HashMap<String, String> params) {
logger.info("Begin getCatalog...");
logger.info(params.toString());
CollBase collResult = new CollBase();
String UNIT_ID = params.get("KBP_CLASS");
//建立连接
init(params);
try{
int count=0;
String[] catalogList = params.get("CATALOG").split(",");
//单目录采集 开始
String catalog = catalogList[0];
String size = new BigDecimal(catalogList[1]).toPlainString().toString();
// ls -ltrd catalog | grep '^d' | grep -v '201[456789]' |sort -nrk5 | awk '$5>size {print $0}' |head -50
StringBuffer cmdsb = new StringBuffer();
//拼接采集语句
cmdsb.append("ls -ltrd ").append(catalog).append(" | grep '^d' | grep -v '201[456789]' |sort -nrk5 | awk '$5>").append(size).append(" {print $0}' |head -50");
logger.info("-------coll------Catalog--------");
// 获得结果
Vector<String> netlogV = tt.getResultAsVector(cmdsb.toString());
String host_name = deviceId;
// 得到unit_id中使用的主机名称
String neat_host_name = Formater.neatenunitid(host_name);
List<List<String>> resultList = analyticalResult(netlogV);
for(List list:resultList){
if(list.size() ==2){
//添加采集路径
// CM-20-21-027-21关键路径
collResult.addKPI(UNIT_ID + "-74:"+host_name+"-" + list.get(0).toString(), "CM-20-21-027-01" , list.get(0).toString());
//添加采集路径大小 保留小数点后四位 b
// PM-20-21-027-21关键路径大小
collResult.addKPI(UNIT_ID + "-74:"+host_name+"-" + list.get(0).toString(), "PM-20-21-027-01" , Formater.formatDecimalByScale((Double.parseDouble(list.get(1).toString())/1024/1024)+"",4));
}
}
//循环执行 用于多目录采集
// for(count = 0;count<catalogList.length;count=count+2){
// String catalog = catalogList[count];
// String size = catalogList[count+1];
// // ls -ltrd catalog | grep '^d' | grep -v '201[456789]' |sort -nrk5 | awk '$5>size {print $0}' |head -50
// StringBuffer cmdsb = new StringBuffer();
// //拼接采集语句
// cmdsb.append("ls -ltrd ").append(catalog).append(" | grep '^d' | grep -v '201[456789]' |sort -nrk5 | awk '$5>").append(size).append(" {print $0}' |head -50");
// logger.info("-------coll------Catalog--------");
// // 获得结果
// Vector<String> netlogV = tt.getResultAsVector(cmdsb.toString());
// String host_name = deviceId;
// // 得到unit_id中使用的主机名称
// String neat_host_name = Formater.neatenunitid(host_name);
// List<List<String>> resultList = analyticalResult(netlogV);
// for(List list:resultList){
// if(list.size() ==2){
// //添加采集路径
// // CM-20-21-027-21关键路径
// collResult.addKPI(UNIT_ID + "-74:"+host_name+"-" + list.get(0).toString(), "CM-20-21-027-01" , list.get(0).toString());
// //添加采集路径大小 保留小数点后4位
// // PM-20-21-027-21关键路径大小
// collResult.addKPI(UNIT_ID + "-74:"+host_name+"-" + list.get(0).toString(), "PM-20-21-027-01" , Formater.formatDecimalByScale((Double.parseDouble(list.get(1).toString())/1024/1024)+"",4));
// }
// }
// }
}catch (Exception e) {
logger.error("Exception while get Catalog!",e);
}finally {
release();
}
logger.info("END COLL Catalog ");
return collResult.getKPISet();
}
/**
* 解析目录采集结果返回指定集合
* @param list
* @return
*/
private List<List<String>> analyticalResult(List list){
List<List<String>> resultList = new ArrayList<List<String>>();
int i = 0;
for(i=0;i< list.size();i++){
//目标目录
String path = split(list.get(i).toString(), 8);
//目录大小
String size = split(list.get(i).toString(),4);
List<String> strList = new ArrayList<String>();
strList.add(path);
strList.add(size);
if((path != null & path !="") && (size != null & size != "") ){
resultList.add(strList);
}
}
return resultList;
}
public String getVetorString(List v) {
StringBuffer sb = new StringBuffer();
if (v != null && v.size() > 0) {
for (int i = 0; i < v.size(); i++) {
String s = (String) v.get(i);
if (s != null && i < v.size()) {
sb.append(s + "\n");
}
}
}
return sb.toString();
}
private String splitNetTypeNum(String strType, String strNum) {
if ("ESTABLISHED".equalsIgnoreCase(strType)) {
return "ES:" + strNum + ",";
} else if ("SYN_SENT".equalsIgnoreCase(strType)) {
return "SS:" + strNum + ",";
} else if ("SYN_RECV".equalsIgnoreCase(strType)) {
return "SR:" + strNum + ",";
} else if ("FIN_WAIT1".equalsIgnoreCase(strType)) {
return "F1:" + strNum + ",";
} else if ("FIN_WAIT2".equalsIgnoreCase(strType)) {
return "F2:" + strNum + ",";
} else if ("TIME_WAIT".equalsIgnoreCase(strType)) {
return "TW:" + strNum + ",";
} else if ("CLOSED".equalsIgnoreCase(strType)) {
return "CD:" + strNum + ",";
} else if ("CLOSE_WAIT".equalsIgnoreCase(strType)) {
return "CW:" + strNum + ",";
} else if ("LAST_ACK".equalsIgnoreCase(strType)) {
return "LA:" + strNum + ",";
} else if ("LISTEN".equalsIgnoreCase(strType)) {
return "LI:" + strNum + ",";
} else if ("CLOSING".equalsIgnoreCase(strType)) {
return "CL:" + strNum + ",";
} else if ("UNKNOWN".equalsIgnoreCase(strType)) {
return "UN:" + strNum + ",";
} else {
return strType.substring(0, 3) + ":" + strNum + ",";
}
}
/**
* 如果超出了返回空串
*/
private String split(String str, int pos) {
StringTokenizer st = new StringTokenizer(str);
Vector<String> values = new Vector<String>();
while (st.hasMoreTokens()) {
values.add(st.nextToken());
}
if (pos >= 0 && pos < values.size()) {
return (String) values.elementAt(pos);
}
return "";
}
public ArrayList split(String str, String sp) {
int ip = 0;
ArrayList al = new ArrayList();
ip = str.indexOf(sp);
if (ip != -1) {
al.add(str.substring(0, ip));
str = str.substring(ip + sp.length());
if (str.length() != 0) {
al.addAll(split(str, sp));
}
} else {
al.add(str);
}
return al;
}
public void release() {
if (tt != null){
tt.close();
tt=null;
}
System.gc();
}
}