CollHPWithCMD.java
100 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
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
package com.sitech.ismp.coll.centercoll;
import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import com.sitech.base.AgentProperties;
import com.sitech.util.RandomGUID;
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.upload.RomoteController;
import com.sitech.util.upload.SSHThread;
import com.sitech.util.upload.TelnetThread;
/**
* @author zang
*
*
* Window - Preferences - Java - Code Style - Code Templates
*/
public class CollHPWithCMD extends CollBase {
String PRE_UNITID = "10-10-21";
String ipAddr;
String deviceName;
String deviceId;
String data_path;
static final String RESULT_PATH = "../result/";
static final String tempKpiFileName = "temp_show.txt";
static final String kpiFileName = "show.txt";
static final String cpuFileName = "hp_hardware_cpu.txt";
static final String memFileName = "hp_hardware_mem.txt";
static final String drvFileName = "hp_hardware_drv.txt";
static final String nicFileName = "hp_hardware_nic.txt";
static final String fanFileName = "hp_hardware_fan.txt";
static final String senFileName = "hp_hardware_sen.txt";
static final String sotFileName = "hp_hardware_sot.txt";
static final String powFileName = "hp_hardware_pow.txt";
static final String posFileName = "hp_hardware_pos.txt";
public void init(HashMap<String,String> params) {
deviceName = params.get("DEVICE_NAME");
deviceId = Formater.neatenunitid(deviceName);
ipAddr = params.get("IP_ADDR");
String user = params.get("USERNAME");
String passwd = params.get("PASSWORD");
passwd = DES3.decrypt(passwd);
String protocol = params.get("PROTOCOL");
if (protocol != null && protocol.equals("telnet")) {
tt = new TelnetThread(ipAddr, 23, user, passwd);
} else {
tt = new SSHThread(ipAddr, 22, user, passwd);
}
try {
tt.initial();
} catch (Exception e) {
logger.error("Exception while initial RomoteController!", e);
}
}
/**
* 得到主机名
*/
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;
}
/**
* @return 系统运行时间
*/
private String getSysUptime(){
Vector<String> host = tt.getResultAsVector("uptime | awk '{print $3\" \"$4}'");
String uptime = (String) host.elementAt(0);
return uptime;
}
/**
* @return 内存大小
*/
public String getMemTotal() {
String memTotalSize="";
try {
memTotalSize = tt.getResultAsStr("/usr/contrib/bin/machinfo|grep Memory");
logger.info("----/usr/contrib/bin/machinfo|grep Memory---- memTotalSize:" + memTotalSize);
int idx = memTotalSize.indexOf("Memory:");
if (idx < 0) {
idx = memTotalSize.indexOf("Memory =");
if (idx >= 0) {
memTotalSize = memTotalSize.substring(idx);
// 单位
String unit = split(memTotalSize, 3);
if (unit.trim().equals("MB")) {
memTotalSize = split(memTotalSize, 2);
}
}else{
memTotalSize = AgentProperties.MEM_TOTAL_SIZE;
}
} else {
idx = memTotalSize.indexOf("Memory:");
memTotalSize = memTotalSize.substring(idx);
// 单位
String unit = split(memTotalSize, 2);
if (unit.trim().equals("MB")) {
memTotalSize = split(memTotalSize, 1);
}
}
logger.info("-- Memory toltal size:" + memTotalSize);
return memTotalSize;
} catch (Exception e) {
logger.info("----/usr/contrib/bin/machinfo|grep Memory---- memTotalSize:" + memTotalSize);
logger.error("Exception while initial getMemUsage!", e);
return null;
}
}
/**
* 内存已使用情况通过vmstat的fre字段 乘以 4k
*
* PM-00-01-002-01 内存的使用率 vmstat 中的memory - free *4k 为空闲内存,不通过本方法获取,通过SNMP获取
* 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.PRE_UNITID + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
if (!tt.isAuthorized()) {
return collResult.KPISet;
}
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-12"开头
String memUnitId = PRE_UNITID + "-12:" + deviceId + "-memory";
Vector<String> vmstat_result = tt.getResultAsVector("vmstat 2 2");
String vmstat_string = vmstat_result.get(vmstat_result.size() - 1);
String memTotalSize = getMemTotal();
if(memTotalSize != null){
double memFreeSize = Double.parseDouble(split(vmstat_string, 4)) * 4 / 1024;
logger.info("-- Memory free size:" + memFreeSize);
// 内存使用率
double memUsage = 100.0 - (memFreeSize * 100.0) / Double.parseDouble(memTotalSize);
collResult.addKPI(memUnitId, "PM-00-01-002-01", Formater.formatDecimalKpivalue(String.valueOf(memUsage)));
collResult.addKPI(PRE_UNITID + "-10:" + deviceId + "-total", "CM-00-01-001-07", Formater.formatDecimalKpivalue(memTotalSize));
}
String value = "";
value = split(vmstat_string, 9);
collResult.addKPI(memUnitId, "PM-00-01-002-02", Formater.formatDecimalKpivalue(value));
value = split(vmstat_string, 7);
collResult.addKPI(memUnitId, "PM-00-01-002-03", Formater.formatDecimalKpivalue(value));
value = split(vmstat_string, 8);
collResult.addKPI(memUnitId, "PM-00-01-002-04", Formater.formatDecimalKpivalue(value));
value = split(vmstat_string, 0);
collResult.addKPI(memUnitId, "PM-00-01-002-05", Formater.formatDecimalKpivalue(value));
try {
Vector<String> filerate_result = tt.getResultAsVector("sar -b 2 2 | grep Average");
String filerate_string = (String) filerate_result.elementAt(filerate_result.size() - 1);
int r_rate = Integer.parseInt(split(filerate_string, 3));
int w_rate = Integer.parseInt(split(filerate_string, 6));
collResult.addKPI(memUnitId, "PM-00-01-002-08", Formater.formatDecimalKpivalue(String.valueOf((r_rate + w_rate) / 2)));
} catch (Exception e) {
logger.error("Exception while getMemory.", e);
}
} catch (Exception e) {
logger.error("Exception while getMemory.", e);
} finally {
tt.close();
}
return collResult.getKPISet();
}
/**
* 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.PRE_UNITID + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
if (!tt.isAuthorized()) {
return collResult.KPISet;
}
// 采集各文件系统占用率
long fs_sum = 0; // 文件系统总空间 兆
long fs_sum_used = 0; // 文件系统总空余空间
Vector<String> fileSystemV = tt.getResultAsVector("df -k");
for (int i = 0; i < fileSystemV.size(); i += 4) {
try {
String fsname_info = (String) fileSystemV.elementAt(i);
String fspercent_info = (String) fileSystemV.elementAt(i + 3);
String fsused_info = (String) fileSystemV.elementAt(i + 2);
String fsfree_info = (String) fileSystemV.elementAt(i + 1);
String fs_name = split(fsname_info, 0);
String fs_size = fsname_info.substring(fsname_info.indexOf(')') + 4, fsname_info.indexOf("total")).trim();
String fs_used_percent = split(fspercent_info, 0);
String fs_used = split(fsused_info, 0);
String diskName = split(fsname_info, 1);
diskName = diskName.replace("(", "").replace(")", "").replace("", "").trim();
fsfree_info = split(fsfree_info, 0);
float free = Float.parseFloat(fsfree_info) / 1024;
String tmp_free = Float.toString(free);
String fsUnitId;
if (fs_name != null && fs_name.equals("/")) {
fsUnitId = PRE_UNITID + "-14:" + deviceId + "-//";
} else {
fsUnitId = PRE_UNITID + "-14:" + deviceId + "-" + Formater.neatenunitid(fs_name);
}
// 文件系统使用率
collResult.addKPI(fsUnitId, "PM-00-01-004-03", Formater.formatDecimalKpivalue(fs_used_percent));
// 文件系统可用空间
collResult.addKPI(fsUnitId, "PM-00-01-004-04", Formater.formatDecimalKpivalue(tmp_free));
// 文件系统挂载磁盘
collResult.addKPI(fsUnitId, "PM-00-01-004-14", diskName);
long lfs_size = Long.parseLong(fs_size);
fs_sum = fs_sum + lfs_size;
long lfs_used = Long.parseLong(fs_used);
fs_sum_used = fs_sum_used + lfs_used;
} catch (Exception e) {
e.printStackTrace();
}
}
// PM-00-01-004-01 文件系统总占用率需要计算
if (fs_sum != 0) {
collResult.addKPI(PRE_UNITID + "-10:" + deviceId + "-total", "PM-00-01-004-01", Formater.formatDecimalKpivalue(String.valueOf(fs_sum_used * 100.0 / fs_sum)));
}
Vector swapV = tt.getResultAsVector("/usr/sbin/swapinfo -atm | grep dev ");
if (swapV != null && swapV.size() > 0) {
long swap_sum_avl = 0;
long swap_sum_usd = 0;
for (int i = 0; i < swapV.size(); i++) {
String swap_info = (String) swapV.elementAt(i);
String swap_avl = split(swap_info, 1);
String swap_usd = split(swap_info, 2);
swap_sum_avl = swap_sum_avl + Long.parseLong(swap_avl);
swap_sum_usd = swap_sum_usd + Long.parseLong(swap_usd);
}
String swap_usd_percent = getByScale(String.valueOf(swap_sum_usd * 100.0 / swap_sum_avl));
collResult.addKPI(PRE_UNITID + "-10:" + deviceId + "-total", "PM-00-01-004-02", Formater.formatDecimalKpivalue(swap_usd_percent));
}
// 实际打开进程数/允许打开进程数 实际使用inod数/允许使用inod数 实际打开文件数/允许打开文件数
String strUserRate = "sar -v 1 | tail -n 1";
Vector<String> listUserRate = tt.getResultAsVector(strUserRate);
if (listUserRate != null && listUserRate.size() > 0) {
String strMsg = listUserRate.get(0);
String[] strProc = split(strMsg, 3).split("/");
String[] strInod = split(strMsg, 5).split("/");
String[] strFile = split(strMsg, 7).split("/");
String procUsage = String.valueOf(Double
.parseDouble(strProc[0])
/ Double.parseDouble(strProc[1]) * 100);
String inodUsage = String.valueOf(Double
.parseDouble(strInod[0])
/ Double.parseDouble(strInod[1]) * 100);
String fileUsage = String.valueOf(Double
.parseDouble(strFile[0])
/ Double.parseDouble(strFile[1]) * 100);
String totalUnitId = PRE_UNITID + "-10:" + deviceId + "-total";
// 实际打开进程数量与可供打开数比率
collResult.addKPI(totalUnitId, "PM-00-01-004-05", Formater.formatDecimalKpivalue(procUsage));
// 实际使用inod比率
collResult.addKPI(totalUnitId, "PM-00-01-004-06", Formater.formatDecimalKpivalue(inodUsage));
// 实际打开文件数比率
collResult.addKPI(totalUnitId, "PM-00-01-004-07", Formater.formatDecimalKpivalue(fileUsage));
// 实际打开进程数
collResult.addKPI(totalUnitId, "PM-00-01-004-08", strProc[0]);
// 允许打开进程数
collResult.addKPI(totalUnitId, "PM-00-01-004-09", strProc[1]);
// 实际使用inod数
collResult.addKPI(totalUnitId, "PM-00-01-004-10", strInod[0]);
// 允许使用inod数
collResult.addKPI(totalUnitId, "PM-00-01-004-11", strInod[1]);
// 实际打开文件数
collResult.addKPI(totalUnitId, "PM-00-01-004-12", strFile[0]);
// 允许打开文件数
collResult.addKPI(totalUnitId, "PM-00-01-004-13", strFile[1]);
}
// netstat -n | awk '/^tcp/ {++state[$NF]} END {for(key in state) print key,"\t",state[key]}'
// FIN_WAIT_2 1
// TIME_WAIT 192
// ESTABLISHED 119
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);
}
}
String unitId = PRE_UNITID + "-10:" + deviceId + "-total";
// 网络连接情况 PM-00-01-900-10
collResult.addKPI(unitId, "PM-00-01-900-10", strNetTypeNums.substring(1, strNetTypeNums.length() - 1));
} catch (Exception e) {
e.printStackTrace();
} finally {
tt.close();
}
return collResult.getKPISet();
}
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_WAIT_1".equalsIgnoreCase(strType)) {
return "F1:" + strNum + ",";
} else if ("FIN_WAIT_2".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 + ",";
}
}
/**
*
* 获取所有用户用户进程数
*
* @param params
* @return
*/
public Vector getUserProNum(HashMap params) {
logger.info("begin getUserProNum ");
logger.info("begin getUserProName ");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
// 得到所有用户的列表,该用户名出现多少次,就表明ps出来有多少行,即有多少进程
Vector userV = new Vector();
Vector processV = tt.getResultAsVector("ps -ef | grep -v UID");
// 原来采用以下命令,但在jilin 10.161.1.132 hp主机上有时出现 用户名称为 _3的情况,所以弃用
// tt.getResultAsVector("export UNIX95=XPG4;ps -ef -o user | grep -v
// USER");
for (int i = 0; i < processV.size(); i++) {
String processInfo = (String) processV.elementAt(i);
userV.add(collResult.split(processInfo, 0));
}
processV = null;
if (userV == null || userV.size() == 0) {
return new Vector();
}
// 计算各个用户的进程数,并保存在这个map中
// user - user process numer
Map user_pronum = new HashMap();
// 将用户排序,然后遍历计算
java.util.Collections.sort(userV);
String userName = "";
for (int i = 0; i < userV.size(); i++) {
userName = ((String) userV.elementAt(i)).trim();
int pro_number = 1;
String nextUer = "";
for (int j = i + 1; j < userV.size(); j++) {
// 到了下一个用户
nextUer = ((String) (userV.elementAt(j))).trim();
if (!userName.equals(nextUer)) {
i = j - 1;
break;
}
pro_number++;
}
user_pronum.put(userName, new Integer(pro_number));
}
// end for
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-10"开头,代表Total数据
String pro_PRE_UNITID = PRE_UNITID + "-15"; // total值
// 获取主机名称
String host_name = this.getHostName();
// 得到unit_id中使用的主机名称
String neat_host_name = Formater.neatenunitid(host_name);
Set users = user_pronum.keySet();
// System.out.println("users------------"+users);
Iterator iter = users.iterator();
while (iter.hasNext()) {
String username = (String) iter.next();
// System.out.println("username------------"+username);
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(username), "PM-00-01-005-06", ((Integer) user_pronum.get(username)).toString());
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(username), "CM-00-01-005-06", Formater.neatenunitid(username));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
tt.close();
}
return collResult.getKPISet();
}
/**
* @return 采集时间
*/
private String getCollTime(){
try{
return Formater.datetimeToString(new Date());
}catch (Exception e) {
logger.error("Exception while getCollTime()", e);
}
return null;
}
/**
* @return CPU个数
*/
private String getCpuNum(){
try{
Vector<String> cpunumV = tt.getResultAsVector("/usr/sbin/ioscan -fnk |grep processor");
return String.valueOf(cpunumV.size());
}catch (Exception e) {
logger.error("Cant't getCpuNum.", e);
return "-";
}
}
/**
* @return CPU类型
*/
private String getCpuType(){
String cpuInfo = "-";
try{
String osVersion = tt.getResultAsStr("uname -r");
logger.info("OS Version: " + osVersion);
Vector<String> cputypeV = tt.getResultAsVector("/usr/contrib/bin/machinfo");
if (osVersion != null && osVersion.indexOf("B.11.23") >= 0) {
// B.11.23 版本特殊处理
for (int i = 0; i < cputypeV.size(); i++) {
String line = cputypeV.get(i);
if (line.indexOf("processor family:") >= 0) {
cpuInfo = line.replace("processor family:", "").trim();
break;
}
}
} else {
for (int i = 0; i < cputypeV.size(); i++) {
String line = cputypeV.get(i);
if (line.indexOf("CPU info:") >= 0 && (i + 1) < cputypeV.size()) {
cpuInfo = cputypeV.get(i+1);
StringTokenizer st = new StringTokenizer(cpuInfo);
String cpuType = "";
while (st.hasMoreTokens()) {
cpuType += st.nextToken() + " ";
}
break;
}
}
}
}catch (Exception e) {
logger.error("Cant't getCpuType.", e);
}
return cpuInfo.trim();
}
/**
* @return CPU主频
*/
private String getCpuClockSpeed(){
String cpuHZ = "-";
DecimalFormat df = new DecimalFormat("#.##");
try{
Vector<String> cputypeV = tt.getResultAsVector("/usr/contrib/bin/machinfo");
for (int i = 0; i < cputypeV.size(); i++) {
String line = cputypeV.get(i);
if (line.contains("GHz,")) {
int begigIndex =line.lastIndexOf("(");
int endIndex = line.indexOf("GHz,");
cpuHZ = line.substring(begigIndex+1, endIndex);
cpuHZ =df.format(Double.parseDouble(cpuHZ)*1024);//将GHz转换为MHz
break;
}
}
}catch (Exception e) {
logger.error("Cant't getCpuHZ.", e);
}
return cpuHZ.trim();
}
/**
* @return 操作系统版本
*/
private String getOsVersion(){
try{
Vector<String> host = tt.getResultAsVector("uname -a");
return split(host.get(0), 2);
}catch (Exception e) {
logger.error("Cant't getOsVersion.", e);
return "-";
}
}
/**
* @return 内置盘大小
*/
private String getDiskSize(){
int disksize_sum = 0;
try{
// 这里得到的pe size默认认为是megadata
// 一下两个命令得到的结果行数一致,分别表示物理设备大小,以及该大小的单位(pe size)
Vector<String> disksizeV = tt.getResultAsVector("/usr/sbin/vgdisplay |grep 'Total PE'");
Vector<String> diskpesizeV = tt.getResultAsVector("/usr/sbin/vgdisplay |grep 'PE Size'");
for (int i = 0; i < disksizeV.size(); i++) {
String pesizeInfo = diskpesizeV.get(i);
String disksizeInfo = disksizeV.get(i);
if(pesizeInfo == null || pesizeInfo.indexOf("PE Size") <0){
continue;
}
if(disksizeInfo == null || disksizeInfo.indexOf("Total PE") <0){
continue;
}
String pesize = split(pesizeInfo, 3);
int i_pesize = Integer.parseInt(pesize);
String disksize = (String) split(disksizeInfo, 2);
int i_disksize = Integer.parseInt(disksize);
disksize_sum = disksize_sum + i_pesize * i_disksize;
}
}catch (Exception e) {
logger.error("Cant't getDiskSize.", e);
return "-";
}
return disksize_sum + "";
}
/**
* @return 采集网络配置
*/
private Vector<TblATO_KPIDETAIL> getNetWorkConfig(){
CollBase result = new CollBase();
String totalUnitId = PRE_UNITID + "-10:" + deviceId + "-total";
String netPreUnitId = PRE_UNITID + "-16:" + deviceId;
try{
// -----网卡配置
Vector<String> netstatV = tt.getResultAsVector("netstat -in| grep -v Mtu | grep -v 127.0.0.1 | grep -v none ");
Vector<String> lanscanV = tt.getResultAsVector("/usr/sbin/lanscan | grep -v Hardware | grep -v Path");
Vector<String> ioscanLanV = tt.getResultAsVector("/usr/sbin/ioscan -funC lan | grep lan");
Vector<String> ioscanFcV = tt.getResultAsVector("/usr/sbin/ioscan -funC fc | grep Fibre");
// CM-00-01-001-10 系统网络接口数, lanscan得出的行数
result.addKPI(totalUnitId, "CM-00-01-001-10", String.valueOf(lanscanV.size()));
// 网口数量 CM-00-01-001-43
result.addKPI(totalUnitId, "CM-00-01-001-43", String.valueOf(ioscanLanV.size()));
// 光口数量 CM-00-01-001-44
result.addKPI(totalUnitId, "CM-00-01-001-44", String.valueOf(ioscanFcV.size()));
Map<String, String> ipMap = new HashMap<String, String>();
// CM-00-01-001-11 系统网络接口IP地址
String service_ip = "";
for (int i = 0; i < netstatV.size(); i++) {
String netstatInfo = (String) netstatV.elementAt(i);
String lan_name = split(netstatInfo, 0);
String ip = split(netstatInfo, 3);
ipMap.put(lan_name, ip);
service_ip = service_ip + "," + ip;
}
// 主机(服务)地址 CM-00-01-001-02, 将所有ip地址累加
result.addKPI(totalUnitId, "CM-00-01-001-02", service_ip.substring(1, service_ip.length()));
// CM-00-01-001-12 系统网络接口物理地址
for (int i = 0; i < lanscanV.size(); i++) {
String lancanInfo = (String) lanscanV.elementAt(i);
String lan_name = split(lancanInfo, 4);
String phy_address = split(lancanInfo, 1);
result.addKPI(netPreUnitId + "-" + Formater.neatenunitid(lan_name), "CM-00-01-001-12", phy_address);
String ip = ipMap.get(lan_name);
if(ip == null){
ip = "-";
}
result.addKPI(netPreUnitId + "-" + Formater.neatenunitid(lan_name), "CM-00-01-001-11", ip);
}
}catch (Exception e) {
logger.error("Exception while getNetWorkConfig.", e);
}
return result.KPISet;
}
/**
* @return 交换分区大小
*/
private String getSwapSize(){
try{
Vector<String> result_swap = tt.getResultAsVector("/usr/sbin/swapinfo -atm ");
if (result_swap.size() > 0) {
String value_swap = result_swap.elementAt(result_swap.size() - 1);
return split(value_swap, 1);
}
}catch (Exception e) {
logger.error("Cant't getOsVersion.", e);
}
return "-";
}
/**
* @return 采集文件系统配置
*/
private Vector<TblATO_KPIDETAIL> getFileSysConfig(){
CollBase result = new CollBase();
String totalUnitId = PRE_UNITID + "-10:" + deviceId + "-total";
String preUnitId = PRE_UNITID + "-14:" + deviceId;
try{
// CM-00-01-001-16 文件系统名称
// CM-00-01-001-17 文件系统的总空间,单位:M
Vector<String> fileSystemV = tt.getResultAsVector("df -k ");
long fs_sum = 0; // 文件系统总空间,兆
for (int i = 0; i < fileSystemV.size(); i += 4) {
String fsname_info = "";
try {
fsname_info = (String) fileSystemV.elementAt(i);
String fs_name = split(fsname_info, 0);
String fs_size = "";
logger.info("----fileSystemV("+i+")="+ fsname_info);
try{
fs_size = fsname_info.substring(fsname_info.indexOf(')') + 4, fsname_info.indexOf("total")).trim();
}catch(Exception e){
fs_size = split(fsname_info, 1);
}
if (fs_name != null && fs_name.trim().equals("/")) {
result.addKPI(preUnitId + "-" + Formater.neatenunitid("//"), "CM-00-01-001-16", fs_name);
} else {
result.addKPI(preUnitId + "-" + Formater.neatenunitid(fs_name), "CM-00-01-001-16", fs_name);
}
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("----fileSystemV("+i+")="+ fsname_info);
logger.error("Exception while getFileSysConfig.", e);
}
}// end for
result.addKPI(totalUnitId, "CM-00-01-001-17", Formater.formatDecimalKpivalue(String.valueOf(fs_sum / 1024)));
}catch (Exception e) {
logger.error("Exception while getFileSysConfig.", e);
}
return result.KPISet;
}
/**
* 17个指标中 15个ok 1 hp CM-00-01-001-06(cpu频率) 待完成 主机物理内存大小通过SNMP获取 其他待测试
*
* 在方法的最后面增加了getAllDisk的指标采集,该方法的采集值比较多,所以放在这里了。
*
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getConfig(HashMap<String,String> params) {
logger.info("begin getConfig");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.PRE_UNITID + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
if (!tt.isAuthorized()) {
return collResult.KPISet;
}
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-10"开头,代表Total数据
String config_PRE_UNITID = PRE_UNITID + "-10"; // total值
String unitId = config_PRE_UNITID + ":" + deviceId + "-total";
// 增加采集时间指标
collResult.addKPI(unitId, "CM-00-01-001-22", getCollTime());
// 主机名称
collResult.addKPI(unitId, "CM-00-01-001-01", getHostName());
// 主机类型
collResult.addKPI(unitId, "CM-00-01-001-03", "HP");
// CPU信息:
// CM-00-01-001-04(个数)
// CM-00-01-001-05(型号)
// CM-00-01-001-06(主频)
collResult.addKPI(unitId, "CM-00-01-001-04", getCpuNum());
collResult.addKPI(unitId, "CM-00-01-001-05", getCpuType());
collResult.addKPI(unitId, "CM-00-01-001-06", getCpuClockSpeed());
// 主机操作系统版本 CM-00-01-001-08
collResult.addKPI(unitId, "CM-00-01-001-08", getOsVersion());
// 内置盘大小 CM-00-01-001-09
collResult.addKPI(unitId, "CM-00-01-001-09", getDiskSize());
// 交换分区大小 CM-00-01-001-13
collResult.addKPI(unitId, "CM-00-01-001-13", getSwapSize());
// 采集网络配置
collResult.addKPISet(getNetWorkConfig());
// 采集文件系统配置
collResult.addKPISet(getFileSysConfig());
// 系统运行时长 PM-20-20-001-52
collResult.addKPI(unitId, "PM-20-20-001-52", getSysUptime());
} catch (Exception e) {
logger.error("Exception while getConfig.", e);
} finally {
tt.close();
}
return collResult.getKPISet();
}// end getConfig
/**
* 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.PRE_UNITID + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
String unitId = PRE_UNITID + "-11:" + deviceId + "-cpu";
Vector<String> cpuout = tt.getResultAsVector("vmstat 1 3");
String cpurun = cpuout.get(cpuout.size() - 1);
// CPU时间:空闲百分比
collResult.addKPI(unitId, "PM-00-01-001-01", split(cpurun, 17));
// CPU时间:系统百分比
collResult.addKPI(unitId, "PM-00-01-001-02", split(cpurun, 16));
// CPU时间:用户百分比
collResult.addKPI(unitId, "PM-00-01-001-03", split(cpurun, 15));
// CPU利用率
String cpuFree = split(cpurun, 17);
double cpuUsage = 100 - Double.parseDouble(cpuFree);
collResult.addKPI(unitId, "PM-00-01-001-05", Formater.formatDecimalKpivalue(String.valueOf(cpuUsage)));
// CPU运行队列中进程个数
collResult.addKPI(unitId, "PM-00-01-001-06", split(cpurun, 0));
// CPU时间:等待百分比
String cpuWaitPercent = getCpuWaitPercent();
if(cpuWaitPercent != null && !cpuWaitPercent.trim().equals("")){
collResult.addKPI(unitId, "PM-00-01-001-04", cpuWaitPercent);
}
// 网卡状态
collResult.addKPISet(getNetWorkState());
} catch (Exception e) {
logger.error("Exception while getCpu().", e);
} finally {
tt.close();
}
return collResult.getKPISet();
}
/**
* 采集网卡状态
* @return
*/
private Vector<TblATO_KPIDETAIL> getNetWorkState() {
CollBase result = new CollBase();
String netPreUnitId = PRE_UNITID + "-16:" + deviceId;
try{
Vector<String> lan_stateV = tt.getResultAsVector("/usr/sbin/lanscan | tail +3 | awk '{ print $5,$4}'");
if (lan_stateV != null && lan_stateV.size() > 0) {
for (String lan : lan_stateV) {
String name = split(lan, 0);
String state = split(lan, 1);
String unitId = netPreUnitId + "-" + Formater.neatenunitid(name);
result.addKPI(unitId, "FM-00-01-001-03", state);
}
}
}catch (Exception e) {
logger.error("Exception while initial getCpuWaitPercent!", e);
}
return result.KPISet;
}
/**
* 采集CPU等待百分比
*/
private String getCpuWaitPercent() {
try {
Vector<String> sarResult = tt.getResultAsVector("sar -u 1 3");
String line = sarResult.get(sarResult.size() - 1);
return split(line, 3);
} catch (Exception e) {
logger.error("Exception while initial getCpuWaitPercent!", e);
return null;
}
}
public Vector<TblATO_KPIDETAIL> getDisk(HashMap<String,String> params) {
return this.getActiveDisk(params);
}
/**
* ok
*
* 采集当前采集周期内有活动的主机磁盘状态,读写指标
*
* 该方法是相对于getAllDisk而言的
*
* 每秒磁盘读写请求 PM-00-01-003-04/05现在得到的值为 r+w
*
* 在规范磁盘性能指标基础上,增加了FM指标,内置盘状态
*
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getActiveDisk(HashMap<String,String> params) {
logger.info("begin getActiveDisk");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.PRE_UNITID + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + deviceId + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
if (!tt.isAuthorized()) {
return collResult.KPISet;
}
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-13"开头,代表disk数据
String disk_PRE_UNITID = PRE_UNITID + "-13:" + deviceId ;
String value = "";// 临时变量
// 内置盘状态
// Vector<String> diskState = tt.getResultAsVector("/usr/sbin/ioscan -fnkC disk | grep -v 'Description' | grep -v '==' ");
//
// HashMap<String, String> diskStateMap = new HashMap<String, String>();// 用于存储磁盘名称与磁盘状态。用于后面sar命令中没有得到的磁盘指标附值,hp主机sar命令只采活动io设备
//
// for (int i = 0; i < diskState.size() - 1; i++) {
// String diskInfo1 = diskState.get(i);
// if(diskInfo1.indexOf("/dev/dsk") >=0 || diskInfo1.indexOf("/dev/deviceFileSystem") >=0){
// continue;
// }
//
// String diskInfo2 = diskState.get(i + 1);
//
// String disk_state = split(diskInfo1, 4);
//
// String diskName = split(diskInfo2, 0);
//
// // 只取 / 后面的名称
// if (diskName.indexOf('/') > -1) {
// diskName = diskName.substring(diskName.lastIndexOf('/') + 1, diskName.length());
// }
//
// diskStateMap.put(diskName, disk_state);
// }
// 从出现Average的这行开始,每一行表示一个磁盘的数据
Vector<String> diskV = tt.getResultAsVector("sar -d 1 3");
for (int i = 0; i < diskV.size(); i++) {
String disk_value = (String) diskV.elementAt(i);
if (disk_value.indexOf("Average") < 0){
continue;
}
String disk_name = split(disk_value, 1);
// String sar_disk_state = diskStateMap.get(disk_name);
String neat_disk_name = Formater.neatenunitid(disk_name);
String unitId = disk_PRE_UNITID + "-" + neat_disk_name;
collResult.addKPI(unitId, "CM-00-01-001-20", disk_name);
// collResult.addKPI(unitId, "FM-00-01-001-02", sar_disk_state);
// 磁盘物理IO操作速率
value = split(disk_value, 5);
collResult.addKPI(unitId, "PM-00-01-003-01", Formater.formatDecimalKpivalue(value));
// 等待磁盘系统进程线程数
value = split(disk_value, 3);
collResult.addKPI(unitId, "PM-00-01-003-02", Formater.formatDecimalKpivalue(value));
// 磁盘忙的百分比
value = split(disk_value, 2);
collResult.addKPI(unitId, "PM-00-01-003-03", Formater.formatDecimalKpivalue(value));
// 每秒读请求
value = split(disk_value, 4);
collResult.addKPI(unitId, "PM-00-01-003-04", Formater.formatDecimalKpivalue(value));
// 每秒写请求
value = split(disk_value, 4);
collResult.addKPI(unitId, "PM-00-01-003-05", Formater.formatDecimalKpivalue(value));
}
} catch (Exception e) {
logger.error("Exception while getActiveDisk", e);
} finally {
tt.close();
}
return collResult.getKPISet();
}
public Vector getJLSpecProcess(HashMap params) {
logger.info("begin getSpecProcess : " + params.get("PROCESS_NAME"));
logger.info("begin getSpecProcess : " + params.get("PROCESS_NUM"));
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
String process_name = (String) params.get("PROCESS_NAME");
String process_num = (String) params.get("PROCESS_NUM");
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-10"开头,代表Total数据
String pro_PRE_UNITID = PRE_UNITID + "-15"; // total值
// 获取主机名称
String host_name = this.getHostName();
// 得到unit_id中使用的主机名称
String neat_host_name = Formater.neatenunitid(host_name);
String unit_process = "export UNIX95=XPG4;ps -ef -o pcpu,state,sz,pid,ruser,stime,args | grep '" + process_name + "' | grep -v grep | grep -v '%CPU'";
Vector proV = tt.getResultAsVector(unit_process);
String snum = String.valueOf(proV.size()).trim();
if (snum.equals(process_num)) {
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(process_name), "PM-00-01-005-02", "UP");
} else if (!snum.equals(process_num)) {
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(process_name), "PM-00-01-005-03", "DOWN");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
tt.close();
}
return collResult.getKPISet();
}
/**
* 本类用于获取指定某个进程的各个参数
*
* 新建2个kpi PM-00-01-005-07 进程所属用户 PM-00-01-005-02
* 如果该进程相关信息不存在,那么直接返回这样一个kpi值DOWN,
*
* @param params
* @return
*/
public Vector getSpecProcess(HashMap params) {
logger.info("begin getSpecProcess : " + params.get("PROCESS_NAME"));
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
DecimalFormat df = new DecimalFormat("#.##");
try {
init(params);
String processName = (String) params.get("PROCESS_NAME");
String max_c = (String) params.get("MAX_COUNT");
String min_c = (String) params.get("MIN_COUNT");
int max_count = 0;
int min_count = 0;
if (max_c != null && !max_c.equals("") && !max_c.equals("null")) {
max_count = new Integer(max_c).intValue();
} else {
max_count = -1;
}
if (min_c != null && !min_c.equals("") && !min_c.equals("null")) {
min_count = new Integer(min_c).intValue();
} else {
min_count = 0;
}
String[] processNames = processName.split(",");
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-10"开头,代表Total数据
String pro_PRE_UNITID = PRE_UNITID + "-15"; // total值
// 获取主机名称
String host_name = getHostName();
// 得到unit_id中使用的主机名称
String neat_host_name = Formater.neatenunitid(host_name);
for (String process_name : processNames) {
if (StringUtils.isBlank(process_name.trim())) continue;
// 获取进程开始时间PM-00-01-005-04,所属用户PM-00-01-005-07,
// 时间中没有 ":" , 那么把后面的一位也算上
String unit_process = "export UNIX95=XPG4;ps -ef -o pcpu,state,sz,pid,ruser,stime,args | grep '" + process_name + "' | grep -v grep | grep -v '%CPU' | wc -l";
// 含义UID PID PPID C STIME TTY TIME CMD
// 数据:" root 98368 1 0 Mar 17 - 18:51 /usr/sbin/syncd 60"
// 数据:"agent 299122 831586 0 11:05:34 pts/3 0:00 -ksh"
String v1 = tt.getResultAsStr(unit_process);
if (v1 == null || v1.equals("") || v1.equals("null")) {
// 不存在该进程
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(process_name), "PM-00-01-005-02", "DOWN");
return collResult.getKPISet();
} else {
int count = new Integer(v1).intValue();
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(process_name), "PM-00-01-005-06", v1);
if (max_count == -1) {
if (count >= min_count) {
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(process_name), "PM-00-01-005-06", "natural");
} else {
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(process_name), "PM-00-01-005-06", "abnormity");
}
} else {
if (count >= min_count && count < max_count) {
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(process_name), "PM-00-01-005-06", "natural");
} else {
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(process_name), "PM-00-01-005-06", "abnormity");
}
}
}// end v1
}
} catch (Exception e) {
e.printStackTrace();
} finally {
tt.close();
}
logger.info("end getSpecProcess : " + params.get("PROCESS_NAME"));
return collResult.getKPISet();
}
/**
*
* 得到指定精度的double类型数值 精度设定为4
* @return
*/
private String getByScale(String double_value) {
int scale = 4;
return Formater.getByScale(double_value, scale);
}
/**
* ok 采集所有主机磁盘状态,读写指标 对于当前采集周期非活动的状态为CLAIMED的磁盘,其指标设定默认值 0
*
* 每秒磁盘读写请求 PM-00-01-003-04/05现在得到的值为 r+w
*
* 在规范磁盘性能指标基础上,增加了FM指标,内置盘状态
*
* @param params
* @return
*/
public Vector getAllDisk(HashMap params) {
logger.info("begin getAllDisk");
init(params);
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-13"开头,代表disk数据
String disk_PRE_UNITID = PRE_UNITID + "-13";
// 获取主机名称
String host_name = this.getHostName();
// 得到unit_id中使用的主机名称
String neat_host_name = Formater.neatenunitid(host_name);
// 增加采集时间指标
String pattern = "yyyy-MM-dd-HH-mm-ss";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "", "CM-00-01-001-22", dateFormat.format(new java.util.Date()));
String value = "";// 临时变量
/*
* //内置盘状态 Vector otherResult = tt.getResultAsVector("ioscan -fnkC disk |
* tail +3 | grep disk | awk '{print $5}'"); Vector otherResult2 =
* tt.getResultAsVector("ioscan -fnkC disk | tail +3 |grep -v disk | awk
* '{print $1}'"); for(int i=0;i<otherResult.size();i++){ String state =
* (String)otherResult.elementAt(i); String name =
* (String)otherResult2.elementAt(i); collResult.addKPI(disk_PRE_UNITID +
* ":" + neat_host_name + "-"+name, "FM-00-01-001-02", state); }
*/
// 内置盘状态
Vector diskState = tt.getResultAsVector("ioscan -fnkC disk | grep -v 'Description' | grep -v '==' ");
Vector diskStateV = this.transMSG(diskState);
HashMap disk_stateMap = new HashMap();// 用于存储磁盘名称与磁盘状态。用于后面sar命令中没有得到的磁盘指标附值,hp主机sar命令只采活动io设备
// 输出格式
/*
* hpj5000:root:/>ioscan -fnkC disk | grep -v 'Description' | grep -v
* '==' disk 0 10/0/14/0.0.0 sdisk CLAIMED DEVICE TEAC CD-532E-B
* /dev/dsk/c0t0d0 /dev/rdsk/c0t0d0 disk 2 10/0/15/1.3.0 sdisk CLAIMED
* DEVICE FUJITSU MAF3364LCX /dev/dsk/c3t3d0 /dev/rdsk/c3t3d0
*/
for (int i = 0; i < diskStateV.size(); i = i + 2) {
String diskInfo1 = (String) diskStateV.elementAt(i); // "disk 0
// 10/0/14/0.0.0
// sdisk
// CLAIMED
// DEVICE
// TEAC
// CD-532E-B"
String diskInfo2 = (String) diskStateV.elementAt(i + 1); // "/dev/dsk/c0t0d0
// /dev/rdsk/c0t0d0"
String disk_state = split(diskInfo1, 4);
String disk_nameInfo = split(diskInfo2, 0); // /dev/dsk/c0t0d0
String disk_name = disk_nameInfo;
// 只取 / 后面的名称
if (disk_nameInfo.indexOf('/') > -1) {
disk_name = disk_nameInfo.substring(disk_nameInfo.lastIndexOf('/') + 1, disk_nameInfo.length());
}
disk_stateMap.put(disk_name, disk_state);
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + Formater.neatenunitid(disk_name), "FM-00-01-001-02", disk_state);
}
// 从出现Average的这行开始,每一行表示一个磁盘的数据
Vector diskV = tt.getResultAsVector("sar -d 5 5");
Set sarDiskSet = new HashSet(); // 保存所有sar命令能取到的io设备名称
for (int i = 0; i < diskV.size(); i++) {
String disk_value = (String) diskV.elementAt(i);
if (disk_value.indexOf("Average") < 0)
continue;
String disk_name = split(disk_value, 1);
sarDiskSet.add(disk_name);
String neat_disk_name = Formater.neatenunitid(disk_name);
// 磁盘物理IO操作速率
value = split(disk_value, 5);
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-01", Formater.formatDecimalKpivalue(value));
// 等待磁盘系统进程线程数
value = split(disk_value, 3);
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-02", Formater.formatDecimalKpivalue(value));
// 磁盘忙的百分比
value = split(disk_value, 2);
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-03", Formater.formatDecimalKpivalue(value));
// 每秒读请求
value = split(disk_value, 4);
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-04", Formater.formatDecimalKpivalue(value));
// 每秒写请求
value = split(disk_value, 4);
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-05", Formater.formatDecimalKpivalue(value));
}
// 给sar命令没有取到的磁盘设备,该设备为CLAIMED状态的情况 附初始值
Set allDiskSet = disk_stateMap.keySet();
Iterator iter = allDiskSet.iterator();
while (iter.hasNext()) {
String disk_name = (String) iter.next();
if (sarDiskSet.contains(disk_name)) {
continue;
} else {
if (disk_stateMap.get(disk_name).equals("CLAIMED")) {
String neat_disk_name = Formater.neatenunitid(disk_name);
// 磁盘物理IO操作速率
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-01", "0");
// 等待磁盘系统进程线程数
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-02", "0");
// 磁盘忙的百分比
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-03", "0");
// 每秒读请求
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-04", "0");
// 每秒写请求
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-05", "0");
}
}
}
tt.close();
return collResult.getKPISet();
}
// 采集Syslog
public Vector getSyslog(HashMap params) {
logger.info("begin getSyslog ");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
String host_ip = (String) params.get("IP_ADDR");
String now_filename = "now_" + host_ip + ".dat";
String tmp_filename = "tmp_" + host_ip + ".dat";
String diff_filename = "diff_" + host_ip + ".dat";
try {
init(params);
String now = tt.getResultAsStr("grep EMS /var/adm/syslog/syslog.log | sed -n \"1,1000p\"");
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();
} else {// 第一次采集
write_tmp.write(now);
write_tmp.flush();
write_tmp.close();
write_diff.write(now);
write_diff.flush();
write_diff.close();
}
// 生成指标
FileReader diff_reader = new FileReader(diff_file);
BufferedReader diff = new BufferedReader(diff_reader);
String line1;
// 获取主机名称
String host_name = this.getHostName();
// 得到unit_id中使用的主机名称
String neat_host_name = Formater.neatenunitid(host_name);
while ((line1 = diff.readLine()) != null) {
String value1 = "err";
String value2 = (line1.split("Value:"))[1];
String[] value3_m = ((line1.split(":"))[2]).split(" ");
String value3 = value3_m[2] + value3_m[3];
String[] value4_m = line1.split(" ");
String value4 = value4_m[0] + value4_m[1] + value4_m[2];
String unitid = "10-10-21-17:" + neat_host_name + "-syslog-" + value3;
collResult.addKPI(unitid, "FM-00-01-900-03", value1);
collResult.addKPI(unitid, "FM-00-01-900-04", value2);
collResult.addKPI(unitid, "CM-00-01-900-03", value3);
collResult.addKPI(unitid, "CM-00-01-900-04", value4);
}
diff.close();
diff_reader.close();
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
} finally {
tt.close();
}
return collResult.getKPISet();
}
public Vector getPing(HashMap<String, String> params){
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
String net_unit = "10-10-21-35:" + deviceId;
List<String> ips = split(params.get("POINT_IPS"), ",");
for(String ip:ips){
String pingResult = "ping "+ip+" -n 5|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(),4);
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<TblATO_KPIDETAIL> getCabinetRackInfo(HashMap<String, String> params) {
logger.info("[HP COLL]begin getCabinetRackInfo");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
init(params);
// 得到unit_id中使用的主机名称
String neat_host_name = Formater.neatenunitid(deviceId);
try{
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-30"开头
String ntpq_PRE_UNITID = PRE_UNITID + "-30";
//检查各服务器状态
logger.info("--------------begin get serverInfo------------------");
Vector<String> serverInfo = tt.getResultAsVector("show server status all");
if (serverInfo != null && serverInfo.size() > 0) {
String name = "";
for (int i = 0; i < serverInfo.size(); i++) {
String tempLine = serverInfo.get(i);
if(StringUtils.contains(tempLine, "Power:")){
name = StringUtils.remove(serverInfo.get(i-1),"Status:").trim();
collResult.addKPI(ntpq_PRE_UNITID + ":" + neat_host_name + "-"+name,
"CM-20-21-030-01", name);
//记录电源模块状态
collResult.addKPI(ntpq_PRE_UNITID + ":" + neat_host_name + "-"+name,
"FM-20-21-030-01", StringUtils.remove(tempLine,"Power:").trim());
}else if(StringUtils.contains(serverInfo.get(i), "Internal Health:")){
//记录内部健康状态
collResult.addKPI(ntpq_PRE_UNITID + ":" + neat_host_name + "-"+name,
"FM-20-21-030-02", StringUtils.remove(tempLine,"Internal Health:").trim());
}else if(StringUtils.contains(serverInfo.get(i), "Health:")){
//记录健康状态
collResult.addKPI(ntpq_PRE_UNITID + ":" + neat_host_name + "-"+name,
"FM-20-21-030-03", StringUtils.remove(tempLine,"Health:").trim());
}
}
}
logger.info("--------------end get serverInfo------------------");
} catch (Exception e){
logger.error("[HP COLL] Exception while getServerInfo",e);
}
try{
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-31"开头
String ntpq_PRE_UNITID = PRE_UNITID + "-31";
//enclosure Status 附件状态
logger.info("--------------begin get enclosureStatus------------------");
Vector<String> enclosureStatus = tt.getResultAsVector("show enclosure status");
if (enclosureStatus != null && enclosureStatus.size() > 0) {
for (int i = 0; i < enclosureStatus.size(); i++) {
if(StringUtils.contains(enclosureStatus.get(i), "Status:") && !StringUtils.contains(enclosureStatus.get(i),"Diagnostic Status:")){
String status = StringUtils.remove(enclosureStatus.get(i),"Status:").trim();
String name = StringUtils.remove(enclosureStatus.get(i-1),":").trim();
//记录附件名称
collResult.addKPI(ntpq_PRE_UNITID + ":" + neat_host_name + "-"+name,
"CM-20-21-031-01", name);
//记录附件状态
collResult.addKPI(ntpq_PRE_UNITID + ":" + neat_host_name + "-"+name,
"FM-20-21-031-01", status);
}
}
}
logger.info("--------------end get enclosureStatus------------------");
} catch (Exception e){
logger.error("[HP COLL] Exception while get enclosure Status",e);
}
try{
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-31"开头
String ntpq_PRE_UNITID = PRE_UNITID + "-31";
//Interconnect Module Status 内部模块状态
logger.info("--------------begin get moduleStatus------------------");
Vector<String> moduleStatus = tt.getResultAsVector("show interconnect status all");
if (moduleStatus != null && moduleStatus.size() > 0) {
for (int i = 0; i < moduleStatus.size(); i++) {
if(StringUtils.contains(moduleStatus.get(i), "Status:")
&& !StringUtils.contains(moduleStatus.get(i),"Diagnostic")
&& !StringUtils.contains(moduleStatus.get(i),"Interconnect")){
String status = StringUtils.remove(moduleStatus.get(i),"Status:").trim();
String name = StringUtils.remove(moduleStatus.get(i-1),"Status:").trim();
//记录模块名称
collResult.addKPI(ntpq_PRE_UNITID + ":" + neat_host_name + "-"+name,
"CM-20-21-031-02", name);
//记录模块状态
collResult.addKPI(ntpq_PRE_UNITID + ":" + neat_host_name + "-"+name,
"FM-20-21-031-02", status);
}
}
}
logger.info("--------------end get moduleStatus------------------");
} catch (Exception e){
logger.error("[HP COLL] Exception while get moduleStatus",e);
}
try{
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-31"开头
String ntpq_PRE_UNITID = PRE_UNITID + "-31";
//Onboard Administrator Status 板载管理器状态
logger.info("--------------begin get onboardStatus------------------");
Vector<String> onboardStatus = tt.getResultAsVector("show oa status");
if (onboardStatus != null && onboardStatus.size() > 0) {
String name = "";
for (int i = 0; i < onboardStatus.size(); i++) {
if(StringUtils.contains(onboardStatus.get(i), "Name:")){
name = StringUtils.remove(onboardStatus.get(i),"Name:").trim();
//记录板载管理器名称
collResult.addKPI(ntpq_PRE_UNITID + ":" + neat_host_name + "-"+name,
"CM-20-21-031-03", name);
}
if(StringUtils.contains(onboardStatus.get(i), "Status:")
&& !StringUtils.contains(onboardStatus.get(i),"Diagnostic")
&& !StringUtils.contains(onboardStatus.get(i),"Onboard") ){
String status = StringUtils.remove(onboardStatus.get(i),"Status:").trim();
//记录板载管理器状态
collResult.addKPI(ntpq_PRE_UNITID + ":" + neat_host_name + "-"+name,
"FM-20-21-031-03", status);
}
}
}
logger.info("--------------end get onboardStatus------------------");
} catch (Exception e){
logger.error("[HP COLL] Exception while get onboardStatus",e);
}
return collResult.getKPISet();
}
/**
* 获取含有“=”字符串“=”右边的字符
* @param str
* @return
* @author wangyang_bj
*/
public String getRightStrOfEqualSign(String str){
String rightStr = "";
if(str.contains("=")){
str = str.trim();
int equnum = str.indexOf("=");
rightStr = str.substring(equnum+1, str.length());
}else{
rightStr = "";
}
return rightStr;
}
/**
* 获取硬件信息
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getShow(HashMap<String, String> params) {
logger.info("[HP COLL]begin getShow");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
PrintWriter kpiFileStream = null;
init(params);
try {
logger.info("--------------begin get showInfo------------------");
Vector<String> showInfo = tt.getResultAsVector("show -a");
if (kpiFileStream == null) {
kpiFileStream = new PrintWriter(new FileWriter(RESULT_PATH + tempKpiFileName, true), true);
}
if (showInfo != null && showInfo.size() > 0) {
try {
for (int i = 0; i < showInfo.size(); i++) {
String tempLine = showInfo.get(i);
kpiFileStream.println(tempLine);
}
} catch(Exception e) {
logger.error("Exception while saveFile.", e);
} finally {
if (kpiFileStream != null) {
kpiFileStream.close();
kpiFileStream = null;
}
}
try {
File tempSwapFile = new File(RESULT_PATH + tempKpiFileName);
File swapFile = new File(RESULT_PATH + kpiFileName);
tempSwapFile.renameTo(swapFile);
logger.info("=============" + tempKpiFileName + "===============" + kpiFileName + "===============");
} catch (Exception e) {
logger.error("Exception while saveFile.", e);
}
}
logger.info("--------------end get showInfo------------------");
} catch (Exception e){
logger.error("[HP COLL] Exception while getShow",e);
}
return collResult.getKPISet();
}
//采集硬件Disk信息
public Vector getHWDisk(HashMap params){
return null;
}
//采集硬件NetWork信息
public Vector getHWNetWork(HashMap params){
return null;
}
/**
* 通过IPMITools获取HP服务器上风扇信息
* CM-00-01-002-24 风扇名称对应KPI
* CM-00-01-002-22 风扇位置对应KPI
* FM-00-01-001-11 风扇状态对应KPI
* CM-00-01-002-25 风扇转速对应KPI
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getHWFan(HashMap<String, String> params) {
logger.info("getHWFan begin....");
CollBase collResult = new CollBase();
try {
init(params);
String fanUnitId = this.PRE_UNITID + "-40:" + deviceId;
String filepath = RESULT_PATH + fanFileName;
Vector<Map<String, String>> fanMapInfos = parseFanInfos(filepath);
for (Map<String, String> fanmap : fanMapInfos) {
String fanUnitID = fanUnitId + "-" + fanmap.get("fan_name");
collResult.addKPI(fanUnitID, "CM-00-01-002-24", fanmap.get("fan_name"));
collResult.addKPI(fanUnitID, "CM-00-01-002-22", fanmap.get("fan_position"));
collResult.addKPI(fanUnitID, "FM-00-01-001-11", fanmap.get("fan_status"));
collResult.addKPI(fanUnitID, "CM-00-01-002-25", fanmap.get("fan_rpm"));
}
} catch (Exception e) {
e.printStackTrace();
}
logger.info("getHWFan end.");
return collResult.getKPISet();
}
/**
* 读取硬件信息文件并将同类硬件信息按照个数分组,将每个硬件属性与值放入Map集合,然后放入到Vector集合中,集合长度就是对应该类硬件信息的个数
* @param filepath 存放该类硬件信息文本的路径
// * @param linenum 文本中每个硬件属性信息对应的行数。
* @return list
* @author wangyang_bj
* 2015-03-05
*/
public Vector<Map<String, String>> parseFanInfos(String filepath){
Vector<Map<String,String>> faninfosvector = new Vector<Map<String,String>>();
String encoding = "GBK";
Map<String,String> map = new HashMap<String, String>();
String lineString = null;
File file = null;
InputStreamReader read = null;
BufferedReader bufRead = null;
file = new File(filepath);
if(file.isFile() && file.exists()){
try {
read = new InputStreamReader(new FileInputStream(file), encoding);
bufRead = new BufferedReader(read);
while((lineString = bufRead.readLine()) != null){
if (!"--".equals(lineString.trim())) {
if (lineString.contains("/system1/fan")) {
map.put("fan_position", lineString);
map.put("fan_name", lineString.split("/")[2]);
}
if (lineString.contains("DesiredSpeed")) {
map.put("fan_rpm", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("HealthState")) {
map.put("fan_status", getRightStrOfEqualSign(lineString));
}
} else {
faninfosvector.add(map);
map = new HashMap<String, String>();
}
}
} catch (UnsupportedEncodingException e) {
logger.info("编码不支持", e);
} catch (FileNotFoundException e) {
logger.info("没有找到该文件",e);
} catch (IOException e) {
logger.info("读取文件出错", e);
}
try {
bufRead.close();
read.close();
} catch (IOException e) {
logger.info("关闭流出错", e);
}
}
return faninfosvector;
}
/**
* 获取传感器相关信息
* @param params
* @return
* @author wangyang_bj
* CM-00-01-002-26 传感器名称
* CM-00-01-002-22 传感器位置
* CM-00-01-002-27 传感器类型
* FM-00-01-001-12 传感器状态
* PM-00-01-008-03 传感器当期读数
* CM-00-01-002-28 传感器单位
*/
public Vector<TblATO_KPIDETAIL> getHWSensor(HashMap<String,String> params){
logger.info("getSensro begin....");
CollBase collResult = new CollBase();
try{
init(params);
String senUnitId = this.PRE_UNITID + "-41:" + deviceId;
String filepath = RESULT_PATH + senFileName;
Vector<Map<String, String>> sensorMapInfos = parseSensorInfos(filepath);
for(Map<String,String> sensormap : sensorMapInfos){
String sensorUnitID = senUnitId + "-" + sensormap.get("sensor_name");
collResult.addKPI(sensorUnitID, "CM-00-01-002-26", sensormap.get("sensor_name"));
collResult.addKPI(sensorUnitID, "CM-00-01-002-22", sensormap.get("sensor_position"));
collResult.addKPI(sensorUnitID, "CM-00-01-002-27", sensormap.get("sensor_type"));
collResult.addKPI(sensorUnitID, "FM-00-01-001-12", sensormap.get("sensor_status"));
collResult.addKPI(sensorUnitID, "PM-00-01-008-04", sensormap.get("sensor_value"));
collResult.addKPI(sensorUnitID, "CM-00-01-002-28", sensormap.get("sensor_units"));
}
}catch(Exception e){
e.printStackTrace();
}
logger.info("getHWSensor end.");
return collResult.getKPISet();
}
/**
* 解析传感器文本信息。
* @param filepath 传感器文件路径
* @return 传感器个数列表
* @author wangyang_bj
*/
public Vector<Map<String,String>> parseSensorInfos(String filepath){
Vector<Map<String,String>> sensorInfosVector = new Vector<Map<String,String>>();
String encoding = "GBK";
Map<String, String> map = new HashMap<String, String>();
String lineString = null;
File file = null;
InputStreamReader read =null;
BufferedReader bufRead = null;
file = new File(filepath);
if(file.isFile() && file.exists()){
try {
read=new InputStreamReader(new FileInputStream(file), encoding);
bufRead = new BufferedReader(read);
while((lineString = bufRead.readLine()) != null){
if(!"--".equals(lineString.trim())){
//添加传感器的名称和位置
if(lineString.contains("/system1/sensor")){
map.put("sensor_position", lineString);
map.put("sensor_name", lineString.split("/")[2]);
}
//添加传感器的单位
if(lineString.contains("RateUnits")){
map.put("sensor_units", getRightStrOfEqualSign(lineString));
}
//添加传感器的类型
if(lineString.contains("SensorType")){
map.put("sensor_type", getRightStrOfEqualSign(lineString));
}
//添加传感器当前读数
if(lineString.contains("CurrentReading")){
map.put("sensor_value", getRightStrOfEqualSign(lineString));
}
//添加传感器状态
if(lineString.contains("HealthState")){
map.put("sensor_status", getRightStrOfEqualSign(lineString));
}
}else{
sensorInfosVector.add(map);
map = new HashMap<String,String>();
}
}
} catch (UnsupportedEncodingException e) {
logger.info("编码不支持", e);
} catch (FileNotFoundException e) {
logger.info("没有找到该文件",e);
} catch (IOException e) {
logger.info("读取文件出错", e);
}
}
return sensorInfosVector;
}
//采集硬件层面PCI插槽信息
public Vector getHWPCISolt(HashMap params) {
logger.info("getHWPCISolt begin....");
CollBase collResult = new CollBase();
try {
init(params);
String sotUnitId = this.PRE_UNITID + "-42:" + deviceId;
String filepath = RESULT_PATH + sotFileName;
Vector<Map<String, String>> pcisoltInfos = parsePCISoltInfos(filepath);
for (Map<String, String> pcimap : pcisoltInfos) {
String pciSoltUnitID = sotUnitId + "-" + pcimap.get("pci_name");
collResult.addKPI(pciSoltUnitID, "CM-00-01-002-29", pcimap.get("pci_name"));
collResult.addKPI(pciSoltUnitID, "CM-00-01-002-30", pcimap.get("pci_id"));
collResult.addKPI(pciSoltUnitID, "CM-00-01-002-31", pcimap.get("pic_type"));
collResult.addKPI(pciSoltUnitID, "CM-00-01-002-32", pcimap.get("pci_width"));
}
} catch (Exception e) {
e.printStackTrace();
}
logger.info("getHWPCISolt end.");
return collResult.getKPISet();
}
/**
* 解析PCI插槽信息。
*
* @param filepath
* @return
*/
public Vector<Map<String, String>> parsePCISoltInfos(String filepath) {
Vector<Map<String, String>> pciSoltvector = new Vector<Map<String, String>>();
String encoding = "GBK";
Map<String, String> map = new HashMap<String, String>();
String lineString = null;
File file = null;
InputStreamReader read = null;
BufferedReader bufRead = null;
file = new File(filepath);
if (file.isFile() && file.exists()) {
try {
read = new InputStreamReader(new FileInputStream(file), encoding);
bufRead = new BufferedReader(read);
while ((lineString = bufRead.readLine()) != null) {
if (!"--".equals(lineString.trim())) {
if (lineString.contains("/system1/slot")) {
map.put("pci_id", lineString.trim());
map.put("pci_name", lineString.split("/")[2]);
}
if (lineString.contains("type")) {
map.put("pic_type", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("width")) {
map.put("pci_width", getRightStrOfEqualSign(lineString));
}
} else {
pciSoltvector.add(map);
map = new HashMap<String, String>();
}
}
} catch (UnsupportedEncodingException e) {
logger.info("编码不支持", e);
} catch (FileNotFoundException e) {
logger.info("没有找到该文件", e);
} catch (IOException e) {
logger.info("读取文件出错", e);
}
try {
bufRead.close();
read.close();
} catch (IOException e) {
logger.info("关闭流出错", e);
}
}
return pciSoltvector;
}
//采集硬件层面SP管理卡信息
public Vector getHWSPCard(HashMap params){
return null;
}
//采集硬件层面Power插槽信息
public Vector getHWPower(HashMap params) {
logger.info("getHWPower begin....");
CollBase collResult = new CollBase();
try {
init(params);
String powUnitId = this.PRE_UNITID + "-43:" + deviceId;
String filepath = RESULT_PATH + powFileName;
Vector<Map<String, String>> powMapInfos = parsePowerInfos(filepath);
for (Map<String, String> powmap : powMapInfos) {
String powUnitID = powUnitId + "-" + powmap.get("power_name");
collResult.addKPI(powUnitID, "CM-00-01-001-46", powmap.get("power_name"));
collResult.addKPI(powUnitID, "PM-00-01-008-04", powmap.get("curr_consumer"));
collResult.addKPI(powUnitID, "PM-00-01-008-05 ",powmap.get("max_consumer"));
collResult.addKPI(powUnitID, "PM-00-01-008-06", powmap.get("min_consumer"));
collResult.addKPI(powUnitID, "PM-00-01-008-07", powmap.get("avg_consumer"));
collResult.addKPI(powUnitID, "PM-00-01-008-08", powmap.get("power_consumer"));
collResult.addKPI(powUnitID, "PM-00-01-008-09", powmap.get("max_work_power"));
collResult.addKPI(powUnitID, "PM-00-01-008-10", powmap.get("min_work_power"));
collResult.addKPI(powUnitID, "CM-00-02-001-03", powmap.get("power_version"));
collResult.addKPI(powUnitID, "CM-00-01-001-47", powmap.get("top_consumer"));
collResult.addKPI(powUnitID, "CM-00-01-001-48", powmap.get("consum_type"));
collResult.addKPI(powUnitID, "CM-00-01-001-49", powmap.get("warning_threshold"));
collResult.addKPI(powUnitID, "CM-00-01-002-46", powmap.get("warning_type"));
collResult.addKPI(powUnitID, "CM-00-01-001-51", powmap.get("ato_pwr"));
collResult.addKPI(powUnitID, "CM-00-01-001-52", powmap.get("waring_durtime"));
}
} catch (Exception e) {
e.printStackTrace();
}
logger.info("getHWPower end.");
return collResult.getKPISet();
}
/**
* 解析电源属性参数
*
* @param filepath
* @return
*/
public Vector<Map<String, String>> parsePowerInfos(String filepath) {
Vector<Map<String, String>> powerinfoVector = new Vector<Map<String, String>>();
String encoding = "GBK";
Map<String, String> map = new HashMap<String, String>();
String lineString = null;
File file = null;
InputStreamReader read = null;
BufferedReader bufRead = null;
file = new File(filepath);
if (file.isFile() && file.exists()) {
try {
read = new InputStreamReader(new FileInputStream(file), encoding);
bufRead = new BufferedReader(read);
while ((lineString = bufRead.readLine()) != null) {
if (!"--".equals(lineString.trim())) {
if (lineString.contains("/system1/oemhp_power")) {
map.put("power_name", lineString.split("/")[2]);
}
//当前功耗
if (lineString.contains("oemhp_PresentPower")) {
map.put("curr_consumer", getRightStrOfEqualSign(lineString));
}
//平均功耗
if (lineString.contains("oemhp_AvgPower")) {
map.put("avg_consumer", getRightStrOfEqualSign(lineString));
}
//最大功耗
if (lineString.contains("oemhp_MaxPower")) {
map.put("max_consumer", getRightStrOfEqualSign(lineString));
}
//最小功耗
if (lineString.contains("oemhp_MinPower")) {
map.put("min_consumer", getRightStrOfEqualSign(lineString));
}
//供电功率
if (lineString.contains("oemhp_powersupplycapacity")) {
map.put("power_consumer", getRightStrOfEqualSign(lineString));
}
//最大工作功率
if (lineString.contains("oemhp_servermaxpower")) {
map.put("max_work_power", getRightStrOfEqualSign(lineString));
}
//最小工作功率
if (lineString.contains("oemhp_serverminpower")) {
map.put("min_work_power", getRightStrOfEqualSign(lineString));
}
//软件版本
if (lineString.contains("oemhp_power_micro_ver")) {
map.put("power_version", getRightStrOfEqualSign(lineString));
}
//封顶功耗
if (lineString.contains("oemhp_pwrcap")) {
map.put("top_consumer", getRightStrOfEqualSign(lineString));
}
//能耗模式
if (lineString.contains("oemhp_powerreg")) {
map.put("consum_type", getRightStrOfEqualSign(lineString));
}
//告警门限
if (lineString.contains("warning_threshold")) {
map.put("warning_threshold", getRightStrOfEqualSign(lineString));
}
//触发告警
if (lineString.contains("warning_type")) {
map.put("warning_type", getRightStrOfEqualSign(lineString));
}
//自动耗能调节
if (lineString.contains("oemhp_auto_pwr")) {
map.put("ato_pwr", getRightStrOfEqualSign(lineString));
}
//告警持续时间
if (lineString.contains("warning_duration")) {
map.put("waring_durtime", getRightStrOfEqualSign(lineString));
}
} else {
powerinfoVector.add(map);
map = new HashMap<String, String>();
}
}
} catch (UnsupportedEncodingException e) {
logger.info("编码不支持", e);
} catch (FileNotFoundException e) {
logger.info("没有找到该文件", e);
} catch (IOException e) {
logger.info("读取文件出错", e);
}
try {
bufRead.close();
read.close();
} catch (IOException e) {
logger.info("关闭流出错", e);
}
}
return powerinfoVector;
}
//采集硬件层面PowerSupply信息
public Vector getHWPowerSupply(HashMap params) {
logger.info("getHWPowerSupply begin....");
CollBase collResult = new CollBase();
try {
init(params);
String posUnitId = this.PRE_UNITID + "-44:" + deviceId;
String filepath = RESULT_PATH + posFileName;
Vector<Map<String, String>> powsupMapInfos = parsePowerSupplyInfos(filepath);
for (Map<String, String> powsupmap : powsupMapInfos) {
String powSupUnitID = posUnitId + "-" + powsupmap.get("powsup_name");
collResult.addKPI(powSupUnitID, "CM-00-01-002-49", powsupmap.get("powsup_name"));
collResult.addKPI(powSupUnitID, "FM-00-02-001-01", powsupmap.get("powsup_status"));
collResult.addKPI(powSupUnitID, "FM-00-01-001-14", powsupmap.get("running_status"));
collResult.addKPI(powSupUnitID, "CM-00-01-002-50", powsupmap.get("powsup_desc"));
}
} catch (Exception e) {
e.printStackTrace();
}
logger.info("getHWPowerSupply end.");
return collResult.getKPISet();
}
/**
* 解析电源信息
*
* @param filepath
* @return
*/
public Vector<Map<String, String>> parsePowerSupplyInfos(String filepath) {
Vector<Map<String, String>> powsupplyvector = new Vector<Map<String, String>>();
String encoding = "GBK";
Map<String, String> map = new HashMap<String, String>();
String lineString = null;
File file = null;
InputStreamReader read = null;
BufferedReader bufRead = null;
file = new File(filepath);
if (file.isFile() && file.exists()) {
try {
read = new InputStreamReader(new FileInputStream(file), encoding);
bufRead = new BufferedReader(read);
while ((lineString = bufRead.readLine()) != null) {
if (!"--".equals(lineString.trim())) {
if (lineString.contains("/system1/powersupply")) {
map.put("powsup_name", lineString.split("/")[2]);
}
if (lineString.contains("ElementName")) {
map.put("powsup_desc", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("HealthState")) {
map.put("running_status", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("OperationalStatus")) {
map.put("powsup_status", getRightStrOfEqualSign(lineString));
}
} else {
powsupplyvector.add(map);
map = new HashMap<String, String>();
}
}
} catch (UnsupportedEncodingException e) {
logger.info("编码不支持", e);
} catch (FileNotFoundException e) {
logger.info("没有找到该文件", e);
} catch (IOException e) {
logger.info("读取文件出错", e);
}
try {
bufRead.close();
read.close();
} catch (IOException e) {
logger.info("关闭流出错", e);
}
}
return powsupplyvector;
}
/**
* CM-00-01-002-12 描述
* CM-00-01-002-13 标识
* CM-00-01-002-14 内核数
* PM-00-01-008-03 活动内核
* CM-10-10-11-57 线程数
* CM-00-01-002-15 一级缓存
* CM-00-01-002-16 二级缓存
* CM-00-01-002-17 三级缓存
*
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getHWCPU(HashMap<String, String> params) {
logger.info("getHWCPU begin....");
CollBase collResult = new CollBase();
try {
init(params);
String cpuUnitId = this.PRE_UNITID + "-45:" + deviceId;
String filepath = RESULT_PATH + cpuFileName;
Vector<Map<String, String>> cpuMapInfos = parseCpuInfos(filepath);
for (Map<String, String> cpumap : cpuMapInfos) {
String cpuUnitID = cpuUnitId + "-" + cpumap.get("cpu_name");
collResult.addKPI(cpuUnitID, "CM-00-01-002-12", cpumap.get("cpu_desc"));
collResult.addKPI(cpuUnitID, "CM-00-01-002-13", cpumap.get("cpu_id"));
collResult.addKPI(cpuUnitID, "CM-00-01-002-14", cpumap.get("core_num"));
collResult.addKPI(cpuUnitID, "PM-00-01-008-03", cpumap.get("active_core_num"));
collResult.addKPI(cpuUnitID, "CM-10-10-11-57", cpumap.get("thread_num"));
collResult.addKPI(cpuUnitID, "CM-00-01-002-15", cpumap.get("cachememory1"));
collResult.addKPI(cpuUnitID, "CM-00-01-002-16", cpumap.get("cachememory2"));
collResult.addKPI(cpuUnitID, "CM-00-01-002-17", cpumap.get("cachememory3"));
}
} catch (Exception e) {
e.printStackTrace();
}
logger.info("getHWSensor end.");
return collResult.getKPISet();
}
/**
* 解析CPU信息文本
*
* @param filepath
* @return
*/
public Vector<Map<String, String>> parseCpuInfos(String filepath) {
Vector<Map<String, String>> memInfoVector = new Vector<Map<String, String>>();
String encoding = "GBK";
Map<String, String> map = new HashMap<String, String>();
String lineString = null;
File file = null;
InputStreamReader read = null;
BufferedReader bufRead = null;
file = new File(filepath);
if (file.isFile() && file.exists()) {
try {
read = new InputStreamReader(new FileInputStream(file), encoding);
bufRead = new BufferedReader(read);
while ((lineString = bufRead.readLine()) != null) {
if (!"--".equals(lineString.trim())) {
if (lineString.contains("/system1/cpu")) {
map.put("cpu_id", lineString.trim());
map.put("cpu_name", lineString.split("/")[2]);
}
if (lineString.contains("memory_technology")) {
map.put("cpu_desc", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("number_cores")) {
map.put("core_num", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("active_cores")) {
map.put("active_core_num", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("threads")) {
map.put("thread_num", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("cachememory1")) {
map.put("cachememory1", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("cachememory2")) {
map.put("cachememory2", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("cachememory3")) {
map.put("cachememory3", getRightStrOfEqualSign(lineString));
}
} else {
memInfoVector.add(map);
map = new HashMap<String, String>();
}
}
} catch (UnsupportedEncodingException e) {
logger.info("编码不支持", e);
} catch (FileNotFoundException e) {
logger.info("没有找到该文件", e);
} catch (IOException e) {
logger.info("读取文件出错", e);
}
try {
bufRead.close();
read.close();
} catch (IOException e) {
logger.info("关闭流出错", e);
}
}
return memInfoVector;
}
/**
* 获取硬件层面内存信息
* CM-00-01-002-18 名称
* CM-00-01-002-19标识
* CM-00-01-002-20容量
* CM-00-01-002-21主频
* CM-00-01-002-22 位置
*
* @param params
* @return
*/
public Vector<TblATO_KPIDETAIL> getHWMemory(HashMap<String, String> params) {
logger.info("getHWMemory begin....");
CollBase collResult = new CollBase();
try {
init(params);
String memUnitId = this.PRE_UNITID + "-46:" + deviceId;
String filepath = RESULT_PATH + memFileName;
Vector<Map<String, String>> memInfos = parseMemInfos(filepath);
for (Map<String, String> memmap : memInfos) {
String memUnitID = memUnitId + "-" + memmap.get("mem_name");
collResult.addKPI(memUnitID, "CM-00-01-002-18", memmap.get("mem_name"));
collResult.addKPI(memUnitID, "CM-00-01-002-19", memmap.get("mem_id"));
collResult.addKPI(memUnitID, "CM-00-01-002-20", memmap.get("mem_cap"));
collResult.addKPI(memUnitID, "CM-00-01-002-21", memmap.get("mem_freq"));
collResult.addKPI(memUnitID, "CM-00-01-002-22", memmap.get("mem_posit"));
}
} catch (Exception e) {
e.printStackTrace();
}
logger.info("getHWMemory end.");
return collResult.getKPISet();
}
/**
* 解析硬件层面内存文本信息。
*
* @param filepath
* @return
*/
public Vector<Map<String, String>> parseMemInfos(String filepath) {
Vector<Map<String, String>> cpuInfoVector = new Vector<Map<String, String>>();
String encoding = "GBK";
Map<String, String> map = new HashMap<String, String>();
String lineString = null;
File file = null;
InputStreamReader read = null;
BufferedReader bufRead = null;
file = new File(filepath);
if (file.isFile() && file.exists()) {
try {
read = new InputStreamReader(new FileInputStream(file), encoding);
bufRead = new BufferedReader(read);
while ((lineString = bufRead.readLine()) != null) {
if (!"--".equals(lineString.trim())) {
if (lineString.contains("/system1/memory")) {
map.put("mem_id", lineString.trim());
map.put("mem_name", lineString.split("/")[2]);
}
if (lineString.contains("size")) {
map.put("mem_cap", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("frequency")) {
map.put("mem_freq", getRightStrOfEqualSign(lineString));
}
if (lineString.contains("location")) {
map.put("mem_posit", getRightStrOfEqualSign(lineString));
}
} else {
cpuInfoVector.add(map);
map = new HashMap<String, String>();
}
}
} catch (UnsupportedEncodingException e) {
logger.info("编码不支持", e);
} catch (FileNotFoundException e) {
logger.info("没有找到该文件", e);
} catch (IOException e) {
logger.info("读取文件出错", e);
}
try {
bufRead.close();
read.close();
} catch (IOException e) {
logger.info("关闭流出错", e);
}
}
return cpuInfoVector;
}
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);
//kctune 系统参数变动监控
try{
logger.info("-------coll------kctune--------");
// 获得结果
Vector<String> netlogV = tt.getResultAsVector("kctune");
String host_name = deviceId;
// 得到unit_id中使用的主机名称
String neat_host_name = Formater.neatenunitid(host_name);
//文件名称
collResult.addKPI(UNIT_ID + "-20:" + neat_host_name+"-kctune", "CM-10-10-020-01", "kctune");
Boolean isChange = checkFileChange(netlogV,"kctune",deviceId);
//变动部分有结果,则生成告警指标
collResult.addKPI(UNIT_ID + "-20:" + neat_host_name+"-kctune", "FM-10-10-020-01",isChange.toString());
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");
}
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 Vector<String> transMSG(Vector<String> vec) {
Vector<String> vector = new Vector<String>();
int size = vec.size();
String tmp = "";
for (int i = 0; i < size; i++) {
String msg_1 = vec.get(i);
if (msg_1.indexOf("/dev/dsk") != -1 && tmp.indexOf("/dev/dsk") != -1) {
continue;
}
vector.addElement(msg_1);
tmp = msg_1;
}
return vector;
}
public static void main(String[] args){
// CollHPWithCMD cmd = new CollHPWithCMD();
// String s = "/dev/mapper/rootvg-lv_home 4128448 139336 3779400 4% /home";
// System.out.println("**"+cmd.split(s, 9)+"**");
System.out.println(" Status OK ".trim());
}
}