CollLinuxWithCMD.java
123 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
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
package com.sitech.ismp.coll.centercoll;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import com.tongweb.server.logging.SystemOutandErrHandler;
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.JSONUtil;
import com.sitech.util.upload.RomoteController;
import com.sitech.util.upload.SSHThread;
import com.sitech.util.upload.TelnetThread;
/**
* @author maozr 修改版本: 与IBM、HP主机采集指标的度量单位一致,将内存大小指标(CM-00-01-001-07)采集到的值升级到M
*/
public class CollLinuxWithCMD {
private static Logger logger = Logger.getLogger("COLL");
String PRE_UNITID = "10-10-24"; // linux主机的标识
RomoteController tt = null;
String neat_host_name = "";
String hostname = "";
String ipAddr;
Vector result = new Vector();
TblATO_KPIDETAIL record = null;
String value = null;
boolean isConnect = false;
static private String data_path;
DecimalFormat df = new DecimalFormat("#.###");
boolean flag = false;
public String split(String str, int pos) {
StringTokenizer st = new StringTokenizer(str);
Vector values = new Vector();
while (st.hasMoreTokens()) {
values.add(st.nextToken());
}
if (pos >= 0 && pos < values.size()) {
return (String) values.elementAt(pos);
}
return "";
}
public void init(HashMap params) {
String user = null;
String passwd = null;
String protol = null;
if (this.flag) {
ipAddr = (String)params.get("PING_IP_ADDR");
user = (String)params.get("PING_USERNAME");
passwd = (String)params.get("PING_PASSWORD");
protol = (String)params.get("PING_PROTOCOL");
} else {
ipAddr = (String)params.get("IP_ADDR");
user = (String)params.get("USERNAME");
passwd = (String)params.get("PASSWORD");
protol = (String)params.get("PROTOCOL");
}
passwd = DES3.decrypt(passwd);
hostname = (String) params.get("HOSTNAME");
this.neat_host_name = Formater.neatenunitid(hostname);
String protocolPort = null;
if (params.get("PROTOCOL_PORT") != null) {
protocolPort = ((String) params.get("PROTOCOL_PORT")).trim();
}
if (protol != null && protol.equals("telnet")) {
if (null != protocolPort && !"".equals(protocolPort)) {
tt = new TelnetThread(ipAddr, Integer.parseInt(protocolPort), user, passwd);
} else {
tt = new TelnetThread(ipAddr, 23, user, passwd);
}
} else {
if (null != protocolPort && !"".equals(protocolPort)) {
tt = new SSHThread(ipAddr, Integer.parseInt(protocolPort), user, passwd);
} else {
tt = new SSHThread(ipAddr, 22, user, passwd);
}
}
tt.initial();
this.isConnect = tt.isAuthorized();
}
public Vector collLinux(HashMap params) {
try {
init(params);
} catch (Exception e) {
logger.error("Exception while init Linux Coll:" + JSONUtil.toJSON(params), e);
} finally {
this.release();
}
neat_host_name = Formater.neatenunitid(this.hostname);
if (isConnect) {
result.addAll(getConfig(params));
// result.addAll(getCpu(params));
// result.addAll(getMemory(params));
// result.addAll(getDiskForIOstat(params));
// //result.addAll(getDisk(params));
// result.addAll(getFileSystem(params));
// //result.addAll(getSpecProcess(params));
// //result.addAll(getSpecUserProNum(params));
// result.addAll(getUserProNum(params));
// result.addAll(getDmesg(params));
}
return result;
}
/**
* @return 采集时间
*/
private String getCollTime(){
try{
return Formater.datetimeToString(new Date());
}catch (Exception e) {
logger.error("Exception while getCollTime()", e);
}
return null;
}
public Vector getConfig(HashMap params) {
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-10"开头,代表Total数据
String config_PRE_UNITID = PRE_UNITID + "-10"; // total值
// 获取主机名称
Vector host = tt.getResultAsVector("uname -a");
String realHostName = split((String) host.elementAt(0), 1);
String os_version = split((String) host.elementAt(0), 2);
System.out.println("host_type : "+split((String) host.elementAt(0), 0));
String host_type = split((String) host.elementAt(0), 0);
// 增加采集时间指标
// collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name + "-total", "CM-00-01-001-22", getCollTime());
// 常用ip,用于告警标题
/*collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-50", (String) params
.get("IP_ADDR"));*/
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-02", (String) params
.get("IP_ADDR"));
// 主机名称
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-01", realHostName);
// // 主机类型
// collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
// + "-total", "CM-00-01-001-03", "Linux");
// 主机操作系统版本 CM-00-01-001-08
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-08", host_type + " " + os_version);
//zhangdj-add
//主机操作系统类型
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-010", host_type);
//主机型号
String host_model = "uname -i";
Vector vc = tt.getResultAsVector(host_model);
host_model = split((String) vc.elementAt(0), 0);
System.out.println("host_model : "+host_model);
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-011", host_model);
// ----cpu信息 , CM-00-01-001-04(个数)/05(型号)/06(主频)-----
// Vector cpunumV = tt.getResultAsVector("sh linux/cpucount.sh");
// 1 CM-00-01-001-04 cpu个数
// cat /proc/cpuinfo |grep "physical id"|sort -u
String cupcount_cmd = "cat /proc/cpuinfo |grep \"physical id\"|sort -u";
Vector cpunumV = tt.getResultAsVector(cupcount_cmd);
String cpu_size = String.valueOf(cpunumV.size());
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-04", Formater
.formatDecimalKpivalue(cpu_size));
// 2 CM-00-01-001-05 cpu类型
// Vector cputypeV = tt.getResultAsVector("sh linux/cpuinfo.sh");
// cat /proc/cpuinfo |grep "model name"|sort -u
//cat /proc/cpuinfo|grep \"model name\"|awk '{print $4,$5,$6,$7,$8,$9,$10}'|sort -u
String cuptype_cmd = "cat /proc/cpuinfo|grep \"model name\"|awk '{print $4,$5,$6,$7,$8,$9,$10}'|sort -u";
Vector cputypeV = tt.getResultAsVector(cuptype_cmd);
if (cputypeV != null && cputypeV.size() != 0) {
String cpu_type = (String) cputypeV.elementAt(0);
System.out.println("linux cpu type:"+cpu_type);
// int index_split = cpu_type.indexOf(":");
// if (index_split >= 0 && index_split + 1 < cpu_type.length()) {
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-05", cpu_type
// .substring(index_split + 1)
);
// }
}
//cpu主频
Vector cpu_freq = tt.getResultAsVector("cat /proc/cpuinfo|grep 'cpu MHz'|awk '{print int($4)}'|sort -u");
if(cpu_freq!=null){
String freq = (String) cpu_freq.elementAt(0);
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-06", freq
);
}
// 系统运行时长 PM-20-20-001-52
Vector uptime = tt.getResultAsVector("export LANG=en_US.UTF-8;uptime | awk '{print $3\" \"$4\" \"$5}'");
if (uptime != null) {
String up_time = (String) uptime.elementAt(0);
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name + "-total", "PM-20-20-001-52", up_time);
}
/*
* 交换分区大小
* 交换分区使用率
*/
String swap_String = "/sbin/swapon -s";
Vector swap_value = tt.getResultAsVector(swap_String);
int swapSize = swap_value.size();
// System.out.println("swapSize:"+swapSize);
if (swapSize > 0) {
System.out.println("value : " + swap_value.get(0));
long swap_total = Long.parseLong(split((String) swap_value.elementAt(1), 2).trim()) / 1024;
Double swap_free = Double.parseDouble(split((String) swap_value.elementAt(1), 3).trim()) / 1024;
Double rate = swap_free * 100 / swap_total;
//系统交换区大小CM-00-01-001-13
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-13", Long.toString(swap_total));
//交换分区使用率PM-00-01-004-02
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "PM-00-01-004-02", df.format(Double.parseDouble(Formater.realyRate(String.valueOf(rate)))));
// System.out.println("total:"+swap_total+"M");
// System.out.println("free:"+swap_free+"M");
// System.out.println("rate:"+String.valueOf(rate)+"%");
}
/*
* 文件系统大小
* 文件系统使用率
*/
/*
* Vector filerate_result = tt.getResultAsVector("sh linux/mem.sh");
* String filerate_string = (String) filerate_result
* .elementAt(filerate_result.size() - 1);
*
* String sub_msg[] = this.split2Array(filerate_string, " "); String
* sum = sub_msg[0].trim(); float value = Float.parseFloat(sum) /
* 1000; // 2009-1-17,
*/
// maozr有改,单位升级到M
/*
* collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name +
* "-total", "CM-00-01-001-07", Formater
* .formatDecimalKpivalue(Float.toString(value)));
*/
// free -m
// get total real memory of the host
String memory_cmd = "cat /proc/meminfo |grep MemTotal|awk '{print int($2/1024)}'";
Vector memoryV = tt.getResultAsVector(memory_cmd);
if (memoryV != null && memoryV.size() != 0) {
String memoryInfo = (String) memoryV.elementAt(0);
float memTotal = Float.parseFloat(memoryInfo.trim());
// float memTotal = Float.parseFloat(memoryInfo.trim()) / 1024;
// while (memoryInfo.indexOf(" ") >= 0) {
// memoryInfo.replaceAll(" ", " ");
// }
// String[] memory = memoryInfo.split(" ");
// if (memory != null && memory.length >= 2) {
// String total_memory = memory[1];
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name
+ "-total", "CM-00-01-001-07", Formater.formatDecimalByScale(String.valueOf(memTotal), 2));
// }
}
Vector<String> vSwap = tt.getResultAsVector("free -m");
for(String swap : vSwap){
if (swap.indexOf("buffers/cache:") > -1) {
Double buffers_used = Double.parseDouble(split(swap, 2).trim());
Double buffers_free = Double.parseDouble(split(swap, 3).trim());
Double rate = buffers_used * 100 / (buffers_used + buffers_free);
String sRate = Formater.formatDecimalKpivalue(String.valueOf(rate));
collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name + "-total", "PM-00-01-002-08", sRate);
}
}
// try {
// String memory_type = "dmidecode|grep -P -A5 \"Memory Device\" | grep Size | grep -v \"No Module\" | head -1 | awk -F\" \" '{ print $2 }'";
// Vector memoryTypeV = tt.getResultAsVector(memory_type);
// if (memoryTypeV != null && memoryTypeV.size() != 0) {
// String memoryTypeInfo = (String) memoryTypeV.elementAt(0);
// if(Pattern.compile("[0-9]*").matcher(memoryTypeInfo).matches()){//如果memoryTypeInfo为数字,则表示采集成功
// collResult.addKPI(config_PRE_UNITID + ":" + neat_host_name + "-total",
// "CM-00-01-001-45", memoryTypeInfo);
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
String username = (String) params.get("USERNAME");
Vector<String> ulimitV = tt.getResultAsVector("ulimit -a");
for (String ulimit : ulimitV) {
if (ulimit.indexOf("open files") > -1) {
String _ulimit = split(ulimit, 3).trim();
collResult.addKPI(PRE_UNITID + "-71:" + neat_host_name + "-" + username, "CM-00-01-900-16", username);
collResult.addKPI(PRE_UNITID + "-71:" + neat_host_name + "-" + username, "PM-00-01-004-13", _ulimit);
}
}
Vector<String> chageV = tt.getResultAsVector("chage -l " + username);
for (String chage : chageV) {
if (chage.indexOf("Password expires") > -1) {
String _chage = split(chage, 3).trim();
collResult.addKPI(PRE_UNITID + "-73:" + neat_host_name + "-" + username, "CM-00-01-900-16", username);
collResult.addKPI(PRE_UNITID + "-73:" + neat_host_name + "-" + username, "FM-00-01-026-02", _chage);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
release();
}
return collResult.getKPISet();
}
public Vector getNet(HashMap params) {
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if (!tt.isAuthorized()) {
return collResult.KPISet;
}
/*
* 主机网卡采集,共采集三个指标:
* 系统网络接口IP(CM-00-01-001-11),
* 系统网络接口物理地址(CM-00-01-001-12),
* 主机网卡状态(FM-00-01-001-03)
* unit_id为:10-10-21-16:主机名-网卡名
*/
// first coll
Vector vLan = tt.getResultAsVector("/sbin/ifconfig -a");
Date firstDate = new Date();
int size = vLan.size();
String net_unit = "10-10-24-16:" + neat_host_name;
String ip_addr = "<none>";
String phy_addr = "<none>";
String state = "down";
String network_name = "";
boolean phy_pass = true;
boolean ip_pass = true;
boolean state_pass = true;
boolean hard_pass = true;
int sleepSeconds = 2;
String networkName = "";
String serviceIp = "";
Map<String, Map<String, String>> networkMap = new HashMap<String, Map<String, String>>();
for (Object _network : vLan) {
Map<String, String> map = null;
String network = (String) _network;
if (network.indexOf("Link encap:") >= 0) {
map = new HashMap<String, String>();
networkName = network.substring(0, network.indexOf("Link encap:")).trim();
String networkType = "unknown";
if(network.indexOf("HWaddr")!=-1){
networkType = network.substring(network.indexOf("Link encap:") + "Link encap:".length(), network.indexOf("HWaddr")).trim();
}else{
networkType = network.substring(network.indexOf("Link encap:") + "Link encap:".length()).trim();
}
map.put("Link encap:", networkType);
} else {
map = networkMap.get(networkName);
}
if (network.indexOf("HWaddr") >= 0) {
String macaddr = network.substring(network.indexOf("HWaddr") + "HWaddr".length()).trim();
map.put("HWaddr", macaddr);
}
if (network.indexOf("inet addr") >= 0) {
int index1 = network.indexOf("Bcast");
int index2 = network.indexOf("Mask");
int tmp = (index1 == -1) ? index2 : index1;
String ipaddr = network.substring(network.indexOf(":") + 1, tmp).trim();
map.put("inet addr", ipaddr);
}
if (network.indexOf("RX packets") >= 0){
String packets = network.substring(network.indexOf("RX") + 2).trim();
String[] temps = packets.split(" ");
for(String temp:temps){
map.put("rx_" + temp.split(":")[0].trim(), temp.split(":")[1].trim());
}
}
if (network.indexOf("TX packets") >= 0){
String packets = network.substring(network.indexOf("TX") + 2).trim();
String[] temps = packets.split(" ");
for(String temp:temps){
map.put("tx_" + temp.split(":")[0].trim(), temp.split(":")[1].trim());
}
}
if (network.indexOf("RX bytes") >= 0) {
String rx_bytes = network.substring(network.indexOf("RX bytes:") + "RX bytes:".length(), network.indexOf("(")).trim();
String tx_bytes = network.substring(network.indexOf("TX bytes:") + "TX bytes:".length(), network.lastIndexOf("(")).trim();
map.put("rx_bytes", rx_bytes);
map.put("tx_bytes", tx_bytes);
System.out.println(networkName + " 1 " + Long.parseLong(map.get("rx_bytes")) + " " + Long.parseLong(map.get("tx_bytes")));
}
networkMap.put(networkName, map);
}
for(String key : networkMap.keySet()) {
Map<String, String> map = networkMap.get(key);
if(!map.containsKey("inet addr")) {
map.put("inet addr", "N/A");
}
if(!map.containsKey("HWaddr")) {
map.put("HWaddr", "N/A");
}
// RX packets:0 errors:0 dropped:0 overruns:0 frame:0
// TX packets:0 errors:0 dropped:478644 overruns:0 carrier:0
long int_rxpackets = Long.parseLong(map.get("rx_packets"));
long int_rxerrors = Long.parseLong(map.get("rx_errors"));
long int_rxdropped = Long.parseLong(map.get("rx_dropped"));
long int_rxoverruns = Long.parseLong(map.get("rx_overruns"));
long int_rxframe = Long.parseLong(map.get("rx_frame"));
long int_txpackets = Long.parseLong(map.get("tx_packets"));
long int_txerrors = Long.parseLong(map.get("tx_errors"));
long int_txdropped = Long.parseLong(map.get("tx_dropped"));
long int_txoverruns = Long.parseLong(map.get("tx_overruns"));
long int_txcarrier = Long.parseLong(map.get("tx_carrier"));
if(int_rxpackets > 0 || int_rxerrors > 0 || int_rxdropped > 0 || int_rxoverruns > 0 || int_rxframe > 0 ||
int_txpackets > 0 || int_txerrors > 0 || int_txdropped > 0 || int_txoverruns > 0 || int_txcarrier > 0) {
map.put("networkState", "UP");
} else {
map.put("networkState", "DOWN");
}
}
// sleep 2 seconds
try {
Thread.sleep(sleepSeconds * 1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
vLan = tt.getResultAsVector("export LANG=en_US.UTF-8;sar -n DEV 3 3|grep '^Average'|grep -v 'rxpck/s'");
Map<String, String> speedMap = new HashMap<String, String>();
for (Object networkSpeed : vLan) {
String averageSpeed = (String) networkSpeed;
speedMap.put(split(averageSpeed,1),averageSpeed);
}
// second coll
vLan = tt.getResultAsVector("/sbin/ifconfig -a");
Date secondDate = new Date();
long tempSeconds =(secondDate.getTime() - firstDate.getTime())/1000;
if (vLan == null || vLan.size() == 0) {
return collResult.KPISet;
}
for (Object _network : vLan) {
String network = (String) _network;
Map<String, String> map = null;
String key = "";
String firstCollStr = "";
String secondCollStr = "";
if (network.indexOf("Link encap:") >= 0) {
networkName = network.substring(0, network.indexOf("Link encap:")).trim();
map = networkMap.get(networkName);
} else {
map = networkMap.get(networkName);
}
if (network.indexOf("RX packets") >= 0){
String packets = network.substring(network.indexOf("RX") + 2).trim();
String[] temps = packets.split(" ");
for(String temp:temps){
key = "rx_" + temp.split(":")[0].trim();
if(map.containsKey(key)){
firstCollStr = map.get(key);
secondCollStr = temp.split(":")[1].trim();
map.put(key, String.valueOf(Long.parseLong(secondCollStr)-Long.parseLong(firstCollStr)));
}
}
}
if (network.indexOf("TX packets") >= 0){
String packets = network.substring(network.indexOf("TX") + 2).trim();
String[] temps = packets.split(" ");
for(String temp:temps){
key = "tx_" + temp.split(":")[0].trim();
if(map.containsKey(key)){
firstCollStr = map.get(key);
secondCollStr = temp.split(":")[1].trim();
map.put(key, String.valueOf(Long.parseLong(secondCollStr)-Long.parseLong(firstCollStr)));
}
}
}
if (network.indexOf("RX bytes") >= 0) {
String rx_bytes = network.substring(network.indexOf("RX bytes:") + "RX bytes:".length(), network.indexOf("(")).trim();
String tx_bytes = network.substring(network.indexOf("TX bytes:") + "TX bytes:".length(), network.lastIndexOf("(")).trim();
if(map.containsKey("rx_bytes")){
firstCollStr = map.get("rx_bytes");;
map.put("rx_bytes", String.valueOf(Long.parseLong(rx_bytes)-Long.parseLong(firstCollStr)));
}
if(map.containsKey("tx_bytes")){
firstCollStr = map.get("tx_bytes");;
map.put("tx_bytes", String.valueOf(Long.parseLong(tx_bytes)-Long.parseLong(firstCollStr)));
}
}
}
// create coll kpi
Double rx_total=0D;
Double tx_total=0D;
for(String key : networkMap.keySet()){
Map<String,String> map = networkMap.get(key);
String unitId = net_unit + "-" + Formater.neatenunitid(key);
// ifname CM-00-01-001-40
collResult.addKPI(unitId, "CM-00-01-001-40", key);
// macaddr
collResult.addKPI(unitId, "CM-00-01-001-12", map.get("HWaddr"));
// ipaddr
String inetAddr = map.get("inet addr");
collResult.addKPI(unitId, "CM-00-01-001-11", inetAddr);
if(!inetAddr.equals("N/A")) {
serviceIp += inetAddr + ",";
}
// network status
collResult.addKPI(unitId, "FM-00-01-001-03", map.get("networkState"));
// network use kbps
String speedInfo = speedMap.get(key);
if(StringUtils.isNotBlank(speedInfo)){
String rx_bytes=split(speedInfo,4);
String tx_bytes=split(speedInfo,5);
collResult.addKPI(unitId, "PM-00-01-900-04", df.format(Double.parseDouble(rx_bytes)+Double.parseDouble(tx_bytes)));
System.out.println(networkName + " 2 " + Long.parseLong(map.get("rx_bytes")) + " " + Long.parseLong(map.get("tx_bytes")));
collResult.addKPI(unitId, "PM-00-02-001-24", rx_bytes);
collResult.addKPI(unitId, "PM-00-02-001-25", tx_bytes);
rx_total = rx_total+ Double.parseDouble(rx_bytes);
tx_total = tx_total+ Double.parseDouble(tx_bytes);
// }else {
//
// String rx_bytes=Formater.formatDecimalByScale(String.valueOf(Math.abs(Long.parseLong(map.get("rx_bytes")) / 1024.0 / tempSeconds)), 2);
// String tx_bytes=Formater.formatDecimalByScale(String.valueOf(Math.abs(Long.parseLong(map.get("rx_bytes")) / 1024.0 / tempSeconds)), 2);
// collResult.addKPI(unitId, "PM-00-01-900-04", String.valueOf(Double.parseDouble(rx_bytes)+Double.parseDouble(tx_bytes)));
//
// System.out.println(networkName + " 2 " + Long.parseLong(map.get("rx_bytes")) + " " + Long.parseLong(map.get("tx_bytes")));
// collResult.addKPI(unitId, "PM-00-02-001-24", rx_bytes);
// collResult.addKPI(unitId, "PM-00-02-001-25", tx_bytes);
}
collResult.addKPI(unitId, "PM-00-01-900-01", Formater.formatDecimalByScale(String.valueOf((Long.parseLong(map.get("rx_bytes")) + Long.parseLong(map.get("rx_bytes"))) / 1024.0 / sleepSeconds), 2));
long long_packets = Long.parseLong(map.get("rx_packets")) + Long.parseLong(map.get("tx_packets"));
long long_dropped = Long.parseLong(map.get("rx_dropped")) + Long.parseLong(map.get("tx_dropped"));
long long_errors = Long.parseLong(map.get("rx_errors")) + Long.parseLong(map.get("tx_errors"));
String dropped = "";
String errors = "";
if (long_packets == 0) {
if (long_dropped > 0) {
dropped = "1.00";
} else {
dropped = "0.00";
}
if (long_errors > 0) {
errors = "1.00";
} else {
errors = "0.00";
}
} else {
dropped = Formater.formatDecimalByScale(String.valueOf(long_dropped / long_packets), 2);
errors = Formater.formatDecimalByScale(String.valueOf(long_errors / long_packets), 2);
}
collResult.addKPI(unitId, "PM-00-01-900-06", dropped);
collResult.addKPI(unitId, "PM-00-01-900-07", errors);
}
collResult.addKPI(net_unit + "-NET", "CM-00-01-001-40", "NET");
collResult.addKPI(net_unit + "-NET", "PM-00-02-001-24", Formater.formatDecimalByScale(rx_total.toString(),2));
collResult.addKPI(net_unit + "-NET", "PM-00-02-001-25", Formater.formatDecimalByScale(tx_total.toString(),2));
// 根据字符串标志位进行指标获取
// for (int i = 0; i < size; i++) {
// String network = (String) lan.elementAt(i);
// // 网卡名称
// int hard_flag = network.indexOf("Link encap");
// if (hard_flag != -1 && hard_pass) {
// network_name = network.substring(0, network.indexOf("Link encap")).trim();
// net_unit = net_unit + "-" + network_name;
// hard_pass = false;
// }
//
// // 网卡物理地址获取
// int phy_flag = network.indexOf("HWaddr");
// if (phy_flag != -1 && phy_pass) {
// phy_addr = network.substring(network.indexOf("HWaddr") + 6).trim();
// phy_pass = false;
// }
//
// // 获取网卡绑定的IP地址
// int ip_flag = network.indexOf("inet addr");
// if (ip_flag != -1 && ip_pass) {
// int index = network.indexOf("Bcast");
// int inde1 = network.indexOf("Mask");
// int tmp = (index == -1) ? inde1 : index;
// ip_addr = network.substring(network.indexOf(":") + 1, tmp);
// ip_pass = false;
// }
//
// int metri_flag = network.indexOf("Metric:");
// if(metri_flag!=-1&& state_pass){
// if(network.indexOf("UP")>-1){
// state = "up";
// }
// state_pass = false;
// }
// if (("".equals(network) && hard_pass == false) || (network.trim().length() == 0 && hard_pass == false) || (i == size - 1 && hard_pass == false)) {
// //if ("".equals(network) || network.trim().length() == 0) {
// // 网卡名称
// collResult.addKPI(net_unit, "CM-00-01-001-40", network_name);
// // 生成网卡物理地址指标
// collResult.addKPI(net_unit, "CM-00-01-001-12", phy_addr);
// // 生成网卡ip地址指标
// collResult.addKPI(net_unit, "CM-00-01-001-11", ip_addr);
// // 网卡状态
// collResult.addKPI(net_unit, "FM-00-01-001-03", state);
// phy_pass = true;
// ip_pass = true;
// state_pass = true;
// hard_pass = true;
// ip_addr = "<none>";
// phy_addr = "<none>";
// state = "down";
// network_name = "";
// net_unit = "10-10-24-16:" + neat_host_name;
// }
// }
String username = (String) params.get("USERNAME");
Vector<String> ulimitV = tt.getResultAsVector("ulimit -a");
for (String ulimit : ulimitV) {
if (ulimit.indexOf("open files") > -1) {
String _ulimit = split(ulimit, 3).trim();
collResult.addKPI(PRE_UNITID + "-71:" + neat_host_name + "-" + username, "CM-00-01-900-16", username);
collResult.addKPI(PRE_UNITID + "-71:" + neat_host_name + "-" + username, "PM-00-01-004-13", _ulimit);
}
}
Vector<String> chageV = tt.getResultAsVector("chage -l " + username);
for (String chage : chageV) {
if (chage.indexOf("Password expires") > -1) {
String _chage = split(chage, 3).trim();
collResult.addKPI(PRE_UNITID + "-73:" + neat_host_name + "-" + username, "CM-00-01-900-16", username);
collResult.addKPI(PRE_UNITID + "-73:" + neat_host_name + "-" + username, "FM-00-01-026-02", _chage);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
release();
}
return collResult.getKPISet();
}
/**
* 采集cpu指标
*/
public Vector getCpu(HashMap params) {
logger.info("begin getCpu");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
String totalUnitId = "";
if(!tt.isAuthorized()){
totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-11"开头,代表cpu数据
String cpu_PRE_UNITID = PRE_UNITID + "-11"; // total值
// 增加采集时间指标
String pattern = "yyyy-MM-dd-HH-mm-ss";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
// collResult.addKPI(cpu_PRE_UNITID + ":" + neat_host_name + "-cpu", "CM-00-01-001-22", dateFormat.format(new java.util.Date()));
String value = ""; // 临时变量
Vector cpuout = tt.getResultAsVector("vmstat 1 3");
String cpurun = (String) cpuout.elementAt(cpuout.size() - 1);
// CPU时间:空闲百分比
collResult
.addKPI(cpu_PRE_UNITID + ":" + neat_host_name + "-cpu",
"PM-00-01-001-01", Formater
.formatDecimalKpivalue(collResult.split(
cpurun, 14)));
// CPU时间:系统百分比
collResult
.addKPI(cpu_PRE_UNITID + ":" + neat_host_name + "-cpu",
"PM-00-01-001-02", Formater
.formatDecimalKpivalue(collResult.split(
cpurun, 13)));
// CPU时间:用户百分比
collResult
.addKPI(cpu_PRE_UNITID + ":" + neat_host_name + "-cpu",
"PM-00-01-001-03", Formater
.formatDecimalKpivalue(collResult.split(
cpurun, 12)));
// cpu利用率, 100-idle
value = this.getCPU_Rate(3, 3);
collResult.addKPI(cpu_PRE_UNITID + ":" + neat_host_name + "-cpu", "PM-00-01-001-05", Formater.realyRate(value));
// 剩余可使用主机CPU PM-00-01-001-07
Vector totalCpuMHZ = tt.getResultAsVector("cat /proc/cpuinfo | grep 'cpu MHz' | awk '{print int($4)}' | awk '{sum+=$1}END{print sum}'");
String cpuMHZ = (String) totalCpuMHZ.elementAt(0);
Float lessCpuMHZ = Integer.parseInt(cpuMHZ) * (1 - Float.parseFloat(value) / 100);
collResult.addKPI(cpu_PRE_UNITID + ":" + neat_host_name + "-cpu",
"PM-00-01-001-07", Formater.formatDecimalKpivalue(String.valueOf(lessCpuMHZ)));
// CPU运行队列中进程个数
Vector vmstat_result = tt.getResultAsVector("vmstat 2 2");
String vmstat_string = (String) vmstat_result
.elementAt(vmstat_result.size() - 1);
value = collResult.split(vmstat_string, 0);
collResult.addKPI(cpu_PRE_UNITID + ":" + neat_host_name + "-cpu",
"PM-00-01-001-06", Formater.formatDecimalKpivalue(value));
// CPU时间:等待百分比
try {
Vector sar_cpuout = tt.getResultAsVector("sar -u 1 3");
String sar_cpurun = (String) sar_cpuout.elementAt(sar_cpuout.size() - 1);
value = split(sar_cpurun, 5);
collResult.addKPI(cpu_PRE_UNITID + ":" + neat_host_name + "-cpu",
"PM-00-01-001-04", Formater.formatDecimalKpivalue(value));
} catch (Exception e) {
logger.info("cpu采集可能没有sar命令!");
}
//网络接收速率及发送速率 sar -n DEV 1 10 |grep ':'
Vector netRate = tt.getResultAsVector("sar -n DEV 1 10 |grep ':'");//linux中文操作系统适合用此命令
boolean netflag = false;
for (int i = 0; i < netRate.size(); i++) {
String vs = netRate.get(i).toString();
if (vs.indexOf("Average") > -1) {
netflag = true;
}
}
if (netflag) {
//如果linux操作系统是英文的,则用以下命令sar -n DEV 1 10 | sed -n '/Average/p'
netRate = tt.getResultAsVector("sar -n DEV 1 10 | sed -n '/Average/p'");
}
String rxValue = ""; // 临时变量
String txValue = ""; // 临时变量
//网络接收速率
rxValue = this.get_rxValue(netRate);
collResult.addKPI(totalUnitId, "PM-00-01-006-14", rxValue);
//网络发送速率
txValue = this.get_txValue(netRate);
collResult.addKPI(totalUnitId, "PM-00-01-006-15", txValue);
//网络连接数 State为TIME_WAIT,CLOSE_WAIT,ESTABLISHED,LISTEN等 之和
Vector net_number = tt.getResultAsVector("netstat -an | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'");
int number_net = 0;
if(!net_number.isEmpty()){
for(int i =0;i<net_number.size();i++){
String str_net_number = net_number.get(i).toString();
number_net += Integer.parseInt(split(str_net_number,1));
}
}
collResult.addKPI(totalUnitId,"PM-00-01-006-17",Integer.toString(number_net));
// lsof文件句柄 PRE_UNITID + "-71:" + neat_host_name + "-" + username
Vector lsofV = tt.getResultAsVector("/usr/sbin/lsof | awk '{print $3}' | awk '{a[$1]++} END{for(i in a){print i,a[i]}}'");
if (!lsofV.isEmpty()) {
for (int i = 0; i < lsofV.size(); i++) {
String _lsof = (String) lsofV.elementAt(i);
String user = _lsof.split(" ")[0];
String openfile = _lsof.split(" ")[1];
// lsof用户名 进程用户
collResult.addKPI(PRE_UNITID + "-71:" + neat_host_name + "-" + user, "CM-00-01-900-16", user);
// 实际打开文件数
collResult.addKPI(PRE_UNITID + "-71:" + neat_host_name + "-" + user, "PM-00-01-004-12", openfile);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
release();
}
logger.info("end collCpu");
return collResult.getKPISet();
}
private String get_rxValue(Vector<String>netRate){
double rxRate = 0;
//计算eth0 eth1 eth2 等端口之和
for(int i=netRate.size()-1;i>=2;i--){
String rx = netRate.get(i);
rxRate += Double.parseDouble(split(rx, 4));
}
rxRate=rxRate*8;//单位从kBps转换为kbps
return Formater.formatDecimalKpivalue(Double.toString(rxRate));
}
private String get_txValue(Vector<String>netRate){
double txRate = 0;
//计算eth0 eth1 eth2 等端口之和
for(int i=netRate.size()-1;i>=2;i--){
String tx = netRate.get(i);
txRate += Double.parseDouble(split(tx, 5));
}
txRate=txRate*8;//单位从kBps转换为kbps
return Formater.formatDecimalKpivalue(Double.toString(txRate));
}
public Vector getDiskForIOstat(HashMap params) {
CollBase collResult = new CollBase();
try {
init(params);
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-13"开头,代表disk数据
String disk_PRE_UNITID = PRE_UNITID + "-13";
// 增加采集时间指标
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 = "";// 临时变量
// 从出现Average的这行开始,每一行表示一个磁盘的数据
try {
Vector diskV = tt.getResultAsVector("/usr/bin/iostat -xd");
Set sarDiskSet = new HashSet(); // 保存所有sar命令能取到的io设备名称
for (int i = 1; i < diskV.size(); i++) {
String disk_value = (String) diskV.elementAt(i);
if(disk_value!=null&&!disk_value.trim().equals("")&&disk_value.indexOf("rsec/s")==-1){
try{
String neat_disk_name = "";
String device_name ="";
String busy = "";
String svctm = "";
String rs = "";
String ws = "";
String kws = "";
String krs ="";
device_name=split(disk_value,0);
neat_disk_name =Formater.neatenunitid(device_name);
busy = split(disk_value,9);
rs = split(disk_value,3);
ws = split(disk_value,4);
krs = split(disk_value,7);
kws = split(disk_value,8);
svctm = split(disk_value,10);
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name
+ "-" + neat_disk_name, "CM-00-01-001-20",
neat_disk_name);
// 磁盘物理IO操作速率
double krs_d = 0;
double kws_d = 0;
try{
krs_d = Double.valueOf(krs).longValue();
kws_d = Double.valueOf(kws).longValue();
}catch(Exception e){
e.printStackTrace();
}
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name
+ "-" + neat_disk_name, "PM-00-01-003-01", String.valueOf(krs_d+kws_d));
// 每秒读请求
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name
+ "-" + neat_disk_name, "PM-00-01-003-04", rs);
// 每秒写请求
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name
+ "-" + neat_disk_name, "PM-00-01-003-05", ws);
// PM-00-01-003-06
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name
+ "-" + neat_disk_name, "PM-00-01-003-06", busy);
collResult.addKPI(disk_PRE_UNITID + ":"
+ neat_host_name + "-" + neat_disk_name,
"PM-00-01-003-07", svctm);
}catch(Exception e){
e.printStackTrace();
}
}
}
} catch (Exception e) {
logger.debug("disk 采集时没有sar命令");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
release();
}
return collResult.getKPISet();
}
public Vector getDisk(HashMap params) {
logger.info("begin getActiveDisk");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-13"开头,代表disk数据
String disk_PRE_UNITID = PRE_UNITID + "-13";
// 增加采集时间指标
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 = "";// 临时变量
String pwd = tt.getResultAsStr("pwd");
System.out.println(pwd);
// 从出现Average的这行开始,每一行表示一个磁盘的数据
try {
Vector diskV = tt.getResultAsVector("sar -d -p 1 3");
Set sarDiskSet = new HashSet(); // 保存所有sar命令能取到的io设备名称
Double read_total=0D;
Double write_total=0D;
Double kbps_total=0D;
for (int i = 0; i < diskV.size(); i++) {
String disk_value = (String) diskV.elementAt(i);
// if (disk_value.indexOf("Average") > -1 || disk_value.indexOf("平均时间") > -1)
// continue;
//
// if (disk_value.indexOf("DEV") != -1)
// continue;
if((disk_value.indexOf("Average") >= 0 || disk_value.indexOf("平均时间") >= 0) && disk_value.indexOf("DEV") == -1)
{
String disk_name = split(disk_value, 1);
sarDiskSet.add(disk_name);
String neat_disk_name = Formater.neatenunitid(disk_name);
String unitId = disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name;
collResult.addKPI(unitId, "CM-00-01-001-20", neat_disk_name);
// 每秒磁盘读请求 PM-00-01-003-04
value = split(disk_value, 3);
collResult.addKPI(unitId, "PM-00-01-003-04", Formater.formatDecimalKpivalue(value));
// 每秒磁盘写请求 PM-00-01-003-05
value = split(disk_value, 4);
collResult.addKPI(unitId, "PM-00-01-003-05", Formater.formatDecimalKpivalue(value));
// 磁盘忙百分比 PM-00-01-003-03
value = split(disk_value, 9);
collResult.addKPI(unitId, "PM-00-01-003-03", Formater.formatDecimalKpivalue(value));
// 等待进程线程数 PM-00-01-003-02
value = split(disk_value, 6);
collResult.addKPI(unitId, "PM-00-01-003-02", Formater.formatDecimalKpivalue(value));
// 磁盘I/O速率
double kbps = 0;
try {
// 每秒读速率 PM-00-01-003-17
String sRdSec = split(disk_value, 3);
Double rdSec = Double.parseDouble(sRdSec)/2;//扇区大小512byte,sRdSec为每秒扇区读数量,所以除以2之后是读速率k/s。
collResult.addKPI(unitId, "PM-00-01-003-17", Formater.formatDecimalKpivalue(rdSec.toString()));
read_total = read_total+rdSec;
// 每秒写速率 PM-00-01-003-18
String sWrSec = split(disk_value, 4);
Double wdSec = Double.parseDouble(sWrSec)/2;//扇区大小512byte,sRdSec为每秒扇区读数量,所以除以2之后是读速率k/s。
collResult.addKPI(unitId, "PM-00-01-003-18", Formater.formatDecimalKpivalue(wdSec.toString()));
write_total = write_total+wdSec;
kbps = (Double.parseDouble(sRdSec) + Double.parseDouble(sWrSec)) ;
} catch (Exception e) {
kbps = -1;
logger.error("Error", e);
}
String sKbps = Formater.formatDecimalKpivalue(kbps + "");
// 磁盘命令时延
String await = split(disk_value, 7);
// PM-00-01-003-16 每秒磁盘I/O命令数量 数量
// PM-00-01-003-07 磁盘访问平均等待时间(磁盘命令时延)
collResult.addKPI(unitId, "PM-00-01-003-16", Formater.formatDecimalKpivalue(sKbps));
collResult.addKPI(unitId, "PM-00-01-003-07", Formater.formatDecimalKpivalue(await));
// 磁盘物理IO操作速率 k/s
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-" + neat_disk_name, "PM-00-01-003-01", Formater.formatDecimalKpivalue(Double.toString(kbps/2)));
kbps_total = kbps_total+kbps/2;
}
}
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-DISK", "CM-00-01-001-20", "DISK");
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-DISK", "PM-00-01-003-17", Formater.formatDecimalKpivalue(Double.toString(read_total)));
collResult.addKPI(disk_PRE_UNITID + ":" + neat_host_name + "-DISK", "PM-00-01-003-18", Formater.formatDecimalKpivalue(Double.toString(write_total)));
} catch (Exception e) {
logger.debug("disk 采集时没有sar命令");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
release();
}
return collResult.getKPISet();
}
public Vector<TblATO_KPIDETAIL> getFileSystem(HashMap<String, String> params) {
logger.info("Begin getFileSystem[IP=" + params.get("IP_ADDR") + "]");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
// 采集各文件系统占用率
String command = "export LANG=en_US.UTF-8;df -kP|sed -n '2,$p'|awk '{print $1 A OFS $2 A OFS $3 A OFS $4 A OFS $5 A OFS $6}'";
Vector<String> vFilsSystem = tt.getResultAsVector(command);
long size = vFilsSystem.size();
long totalSize = 0;
Double usedSize = 0D;
try {
for (String line : vFilsSystem) {
if (line.indexOf("Permission") >= 0) {
continue;
}
String file_sys_name = split(line, 0);
String rate = split(line, 4).trim();
// 去除百分号
rate = rate.substring(0, rate.length()-1);
String disk_name = split(line, 5).trim();
String max_size = split(line, 1).trim();
String used_size = split(line, 2).trim();
String available = split(line, 3).trim();
usedSize = usedSize + Double.parseDouble(split(line, 2).trim())/1024;
float avaliavle_tmp = Float.parseFloat(available.trim()) / 1024;
totalSize = totalSize + Long.parseLong(max_size.trim())/1024;
String unitId;
if (disk_name != null && disk_name.equals("/")) {
unitId = PRE_UNITID + "-14:" + neat_host_name + "-//";
} else {
unitId = PRE_UNITID + "-14:" + neat_host_name + "-" + Formater.neatenunitid(disk_name);
}
collResult.addKPI(unitId, "CM-00-01-001-16", disk_name);
// CM-00-01-001-17 文件系统配置大小
collResult.addKPI(unitId, "CM-00-01-001-17", Formater.formatDecimalKpivalue(Double.toString(Double.parseDouble(max_size) / 1024)));
// 文件系统已使用大小
collResult.addKPI(unitId, "PM-00-01-004-21", Formater.formatDecimalKpivalue(Double.toString(Double.parseDouble(used_size) / 1024)));
collResult.addKPI(unitId, "PM-00-01-004-03", Formater.realyRate(Formater.formatDecimalKpivalue(rate)));
collResult.addKPI(unitId, "PM-00-01-004-04", Formater.formatDecimalKpivalue(Float.toString(avaliavle_tmp)));
collResult.addKPI(unitId, "CM-00-01-001-42", file_sys_name);
}
} catch (Exception e) {
logger.error("Exception while getFileSystem()", e);
}
Double rate= totalSize==0? 0:usedSize * 100 / totalSize;
String totalUnitId = PRE_UNITID + "-10:" + neat_host_name
+ "-total";
// PM-00-01-004-01 文件系统总占用率需要计算
if (rate != 0) {
collResult.addKPI(totalUnitId, "PM-00-01-004-01", Formater.realyRate(Formater.formatDecimalKpivalue(String.valueOf(rate))));
}
// totalSize = totalSize/1000;
collResult.addKPI(totalUnitId, "CM-00-01-001-17", String.valueOf(totalSize));
// 已分配文件句柄的数目、已使用文件句柄的数目、文件句柄的最大数目
// $ cat /proc/sys/fs/file-nr
// 7168 0 1607133
String strUserRate = "cat /proc/sys/fs/file-nr";
Vector<String> listUserRate = tt.getResultAsVector(strUserRate);
if (listUserRate != null && listUserRate.size() > 0) {
String strMsg = listUserRate.get(0);
String strTotal = split(strMsg, 0);
String strUsed = split(strMsg, 1);
String strMaxed = split(strMsg, 2);
String unitId = PRE_UNITID + "-10:" + neat_host_name + "-total";
// 允许打开文件数
collResult.addKPI(unitId, "PM-00-01-004-13", strTotal);
// 实际打开文件数
collResult.addKPI(unitId, "PM-00-01-004-12", strUsed);
// 最大打开文件数 PM-00-01-004-17
collResult.addKPI(unitId, "PM-00-01-004-17", strMaxed);
}
// netstat -n | awk '/^tcp/ {++state[$NF]} END {for(key in state) print key,"\t",state[key]}'
// TIME_WAIT 1
// SYN_SENT 4
// ESTABLISHED 8
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 + "-59:" + neat_host_name + "-" + Formater.neatenunitid(strType);
// 网络连接类型 CM-00-01-001-74
collResult.addKPI(unitId, "CM-00-01-001-74", strType);
// 网络连接情况 PM-00-01-900-10
collResult.addKPI(unitId, "PM-00-01-900-10", strNum);
}
}
// 采集各文件系统inode
String commandInode = "export LANG=en_US.UTF-8;df -iP|sed -n '2,$p'|awk '{print $1 A OFS $2 A OFS $3 A OFS $4 A OFS $5 A OFS $6}'";
Vector<String> vInode = tt.getResultAsVector(commandInode);
try {
for (String line : vInode) {
if (line.indexOf("Permission") >= 0) {
continue;
}
String disk_name = split(line, 5).trim();
String inodeIused = split(line, 4).trim();
String unitId;
if (disk_name != null && disk_name.equals("/")) {
unitId = PRE_UNITID + "-14:" + neat_host_name + "-//";
} else {
unitId = PRE_UNITID + "-14:" + neat_host_name + "-" + Formater.neatenunitid(disk_name);
}
// PM-00-01-004-23 inode使用率
collResult.addKPI(unitId, "PM-00-01-004-23", inodeIused);
}
} catch (Exception e) {
logger.error("Exception while getFileSystem()", e);
}
//增加文件系统索引使用情况统计
String commandStr = "df -iP|sed -n '2,$p'|grep -v .iso|awk '{print $1 A OFS $2 A OFS $3 A OFS $4 A OFS $5 A OFS $6}'";
Vector<String> fileSysIndexRate = tt.getResultAsVector(commandStr);
for(String indexRate : fileSysIndexRate){
String theRate = split(indexRate, 4).trim();
theRate = theRate.substring(0, theRate.length()-1);
String diskName = split(indexRate, 5);
String unitId = PRE_UNITID + "-10:" + neat_host_name + "-" + Formater.neatenunitid(diskName);
collResult.addKPI(unitId, "PM-00-01-004-40", Formater.formatDecimalKpivalue(theRate));
}
//打开文件的句柄数 lsof |wc -l
String fileHandle = "/usr/sbin/lsof | wc -l";
Vector<String> vHandle = tt.getResultAsVector(fileHandle);
try {
for (String line : vHandle) {
String fileHandleNum = split(line, 0).trim();
String unitId;
unitId = PRE_UNITID + "-10:" + neat_host_name + "-total";
// PM-00-01-004-24 打开文件的句柄数
collResult.addKPI(unitId, "PM-00-01-004-24", fileHandleNum);
}
} catch (Exception e) {
logger.error("Exception while getFileSystem()", e);
}
} catch (Exception e) {
logger.error("Exception while getFileSystem()", e);
} finally {
release();
}
logger.info("End getFileSystem[IP=" + params.get("IP_ADDR") + "]");
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_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 + ",";
}
}
/**
*
* 获取所有用户用户进程数
*
* @param params
* @return
*/
public Vector getUserProNum(HashMap params) {
logger.info("begin getUserProNum ");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
// 得到所有用户的列表,该用户名出现多少次,就表明ps出来有多少行,即有多少进程
Vector userV = new Vector();
String process_cmd = "ps -ef|grep -v UID";
// Vector processV = tt.getResultAsVector("sh linux/process.sh");
Vector processV = tt.getResultAsVector(process_cmd);
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();
if("".equals(userName)){continue;}
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));
}
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-10"开头,代表Total数据
String pro_PRE_UNITID = PRE_UNITID + "-15"; // total值
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 {
release();
}
return collResult.getKPISet();
}
/**
* 采集内存指标
*/
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:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
String memUnitId = PRE_UNITID + "-12:" + neat_host_name + "-memory";
/**用这个命令执行之后的结果为:vmstat 2 2 | awk '{print $7,$8}'
* procs -----------memory---------- ---swap-- -----io---- --system-- -----cpu------
r b swpd free buff cache si so bi bo in cs us sy id wa st
1 0 240 1685884 919504 2095656 0 0 1 117 0 0 14 1 84 0 0
1 0 240 1686140 919516 2095516 0 0 0 744 11520 22153 19 3 78 0 0
* 我们获取第七个和第八个数 si so
* si:读取时的内存交换数 7
* so:写入时的内存交换数 8
*/
String swap_read = "vmstat 2 2 | awk '{print $7,$8,$2}'";
Vector<String> memory_swap = tt.getResultAsVector(swap_read);
if (memory_swap == null || memory_swap.size() == 0) {
logger.error("vmstat's result is null, exit!!");
return collResult.KPISet;
}
String swap_read_string = memory_swap.elementAt(memory_swap.size()-1);
// PM-00-01-002-20 读取时的内存交换数
collResult.addKPI(memUnitId, "PM-00-01-002-20", split(swap_read_string, 0));
// PM-00-01-002-21 写入时的内存交换数
collResult.addKPI(memUnitId, "PM-00-01-002-21", split(swap_read_string, 1));
// 等待内存的进程或线程数量 PM-00-01-002-05
collResult.addKPI(memUnitId, "PM-00-01-002-05", split(swap_read_string, 2));
//PM-00-01-002-01内存使用率
String cmdFree = "free | grep 'Mem:'";
Vector<String> vFreeResult = tt.getResultAsVector(cmdFree);
if (vFreeResult != null && vFreeResult.size() > 0) {
String temp = vFreeResult.get(0);
double total = Double.parseDouble(split(temp, 1));
double used = Double.parseDouble(split(temp, 2));
double free = Double.parseDouble(split(temp, 3));
double shared = Double.parseDouble(split(temp, 4));
double buffers = Double.parseDouble(split(temp, 5));
double cached = Double.parseDouble(split(temp, 6));
logger.info("-- Memory total=" + total + ", used=" + used + ", free=" + free
+ ", buffers=" + buffers + ", shared=" + shared + ", cached=" + cached);
double memoryUsage = (1 - (free + buffers + cached) / total) * 100;
String memoryUsageStr = String.valueOf(memoryUsage);
memoryUsageStr = Formater.formatDecimalKpivalue(memoryUsageStr);
logger.info("-- Memory usage=" + memoryUsageStr);
collResult.addKPI(memUnitId, "PM-00-01-002-01", Formater.realyRate(memoryUsageStr));
// 剩余可使用主机内存 PM-00-01-002-14
collResult.addKPI(memUnitId, "PM-00-01-002-14", Formater.formatDecimalKpivalue(String.valueOf((free + buffers + cached) / 1024)));
}
// 系统内存使用率 PM-00-01-002-06
String sysMem = "ps aux | grep ^root | awk '{print $4}' | awk '{sum+=$1}END{print sum}'";
Vector<String> sys_mem = tt.getResultAsVector(sysMem);
if (sys_mem == null || sys_mem.size() == 0 || sys_mem.isEmpty()) {
logger.error("(ps aux grep root)'s result is null, exit!!");
return collResult.KPISet;
}
String _sysmem = sys_mem.elementAt(0);
collResult.addKPI(memUnitId, "PM-00-01-002-06", _sysmem);
// 用户内存使用率 PM-00-01-002-07
String userMem = "ps aux | grep -v ^root | grep -v %MEM | awk '{print $4}' | awk '{sum+=$1}END{print sum}'";
Vector<String> user_mem = tt.getResultAsVector(userMem);
if (user_mem == null || user_mem.size() == 0 || user_mem.isEmpty()) {
logger.error("(ps aux grep -v root)'s result is null, exit!!");
return collResult.KPISet;
}
String _usermem = user_mem.elementAt(0);
collResult.addKPI(memUnitId, "PM-00-01-002-07", _usermem);
} catch (Exception e) {
logger.error("Exception while getMemory().", e);
} finally {
release();
}
logger.info("end getMemory");
return collResult.getKPISet();
}
public Vector getSpecProcess(HashMap params) {
logger.info("begin getSpecProcess : " + params.get("PROCESS_NAME"));
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
String process_name = (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;
}
// 本方法得到的kpi值的unit_id,均以PRE_UNITID + "-10"开头,代表Total数据
String pro_PRE_UNITID = PRE_UNITID + "-15"; // total值
// 获取进程开始时间PM-00-01-005-04,所属用户PM-00-01-005-07,
// 时间中没有 ":" , 那么把后面的一位也算上
String cmd1 = "ps -ef | grep -v grep | grep -v 'PPID' |grep '"
+ process_name + "' | 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(cmd1);
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 {
release();
}
logger.info("end getSpecProcess : " + params.get("PROCESS_NAME"));
return collResult.getKPISet();
}
public Vector getPortListenings(HashMap params) {
logger.info("begin getPortListenings : "+ params.get("IP_ADDR") + ":" + params.get("LISTENING_PORT"));
System.out.println("begin getPortListenings : "+ params.get("IP_ADDR") + ":" + params.get("LISTENING_PORT"));
String pro_PRE_UNITID = PRE_UNITID + "-26";
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
String linteningHost = (String) params.get("IP_ADDR");
String listeningPorts = (String) params.get("LISTENING_PORT");
String correctListening = (String) params.get("CORRECT_LISTENING");
String[] arrayListeningPorts = listeningPorts.split(",");
String[] arrayCorrectListening = correctListening.split(",");
for (int i = 0; i < arrayListeningPorts.length; i++) {
int count = 0;
String _listeningAddr = linteningHost + ":" + arrayListeningPorts[i];
int _correntListenings = new Integer(StringUtils.isNotBlank(arrayCorrectListening[i])? arrayCorrectListening[i]:"0").intValue();
String listeningStatus = "Normal";
String cmd = "netstat -an | grep " + _listeningAddr + " | grep ESTABLISHED";
System.out.println(cmd);
Vector vec = tt.getResultAsVector(cmd);
String _unitID = pro_PRE_UNITID + ":" + neat_host_name + "-"
+ Formater.neatenunitid(arrayListeningPorts[i]);
// 网络连接监听地址 CM-00-01-001-55
collResult.addKPI(_unitID, "CM-00-01-001-55", _listeningAddr);
// 监听地址正常连接个数 CM-00-01-001-56
collResult.addKPI(_unitID, "CM-00-01-001-56", _correntListenings + "");
if (vec == null || vec.equals("") || vec.equals("null") || vec.isEmpty()) {
// 监听地址当前连接个数 PM-00-01-001-55
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-"
+ Formater.neatenunitid(arrayListeningPorts[i]), "PM-00-01-001-55", "0");
// 监听地址当前连接个数是否正常 FM-00-01-026-01
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-"
+ Formater.neatenunitid(arrayListeningPorts[i]), "FM-00-01-026-01", listeningStatus);
} else {
count = new Integer(String.valueOf(vec.size())).intValue();
// 监听地址当前连接个数 PM-00-01-001-55
collResult.addKPI(_unitID, "PM-00-01-001-55", count + "");
if (count != _correntListenings) {
listeningStatus = "Unnormal";
}
// 监听地址当前连接个数是否正常 FM-00-01-026-01
collResult.addKPI(_unitID, "FM-00-01-026-01", listeningStatus);
}
// 提供给安徽移动云平台同步用KPI指标 CM-00-01-001-57
String res = _listeningAddr + ":" + _correntListenings + ":" + count + ":" + listeningStatus;
collResult.addKPI(_unitID, "CM-00-01-001-57", res);
}
} catch (Exception e) {
logger.error("getPortListenings error", e);
} finally {
release();
}
logger.info("end getPortListenings : " + params.get("LISTENING_PORT"));
return collResult.getKPISet();
}
public Vector getBusiProcess(HashMap params) {
logger.info("begin getBusiProcess : " + params.get("PROCESS_NAME"));
System.out.println("begin getBusiProcess : " + params.get("PROCESS_NAME"));
String pro_PRE_UNITID = PRE_UNITID + "-25";
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if (isConnect) {
String processName = (String) params.get("PROCESS_NAME");
if(StringUtils.isNotBlank(processName)){
String[] processNames = processName.split(",");
for (String _processName : processNames) {
String secondProcessName = _processName;
if(StringUtils.isBlank(_processName.trim())){
continue;
}
//若每个参数包含特殊符号~,则说明,进程关键字要拼接,进行多重筛选
String[] subProcessName = _processName.split("~");
_processName = "";
for(String _subProcessName : subProcessName){
_processName += _subProcessName + "'|grep '";
}
_processName = _processName.substring(0,_processName.lastIndexOf("|")-1);
String cmd = "ps aux | grep -v grep | grep '" + _processName + "'";
System.out.println(cmd);
Vector vec = tt.getResultAsVector(cmd);
_processName = secondProcessName;
if (tt.isAuthorized()) {
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 + ":" + neat_host_name + "-"
+ Formater.neatenunitid(_processName), "CM-00-01-005-10", _processName);
// 更新时间 CM-00-03-002-10
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-"
+ 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 + ":" + neat_host_name + "-"
+ 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 + ":" + neat_host_name + "-"
+ Formater.neatenunitid(_processName), "CM-00-01-005-08", "");
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-005-12", "0");
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-000-01", "0");
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-002-01", "0");
} else {
// 借用进程指令行KPI CM-00-01-005-08
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-"
+ Formater.neatenunitid(_processName), "CM-00-01-005-08", temp.substring(0, temp.length() - 1));
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-005-12", count + "");
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-000-01", BigDecimal.valueOf(cpu_usage).divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP).toString());
collResult.addKPI(pro_PRE_UNITID + ":" + neat_host_name + "-"
+ Formater.neatenunitid(_processName), "PM-00-01-002-01", BigDecimal.valueOf(mem_usage).divide(BigDecimal.ONE, 2, BigDecimal.ROUND_HALF_UP).toString());
}
}else {
logger.error("fail getBusiProcess:" + _processName + "! SSH session is down!! isAuthorized=" + tt.isAuthorized());
if (!_processName.equals(processNames[processNames.length - 1])) {
init(params);
}
}
}
}
}else {
logger.error("getBusiProcess has error:ssh session Failed!! isConnect=" + isConnect);
}
} catch (Exception e) {
logger.error("getBusiProcess has error", e);
} finally {
release();
}
logger.info("end getBusiProcess : " + params.get("PROCESS_NAME"));
return collResult.getKPISet();
}
public Vector getProcessTop5Mem(HashMap params) {
logger.info("begin getProcessTop5Mem");
System.out.println("begin getProcessTop5Mem");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
String pro_PRE_UNITID = PRE_UNITID + "-27:" + neat_host_name;
String cmd = "ps aux | grep -v %CPU | sort -k4 | tail -5";
System.out.println(cmd);
Vector<String> vec = tt.getResultAsVector(cmd);
if (vec == null || vec.equals("") || vec.equals("null")) {
//
} else {
int i = 5;
for (String processInfo : vec) {
String processUser = split(processInfo, 0);
String processPid = split(processInfo, 1);
String processCpu = split(processInfo, 2);
String processMem = split(processInfo, 3);
String processCmd = split(processInfo, 10);
System.out.println(processUser + "#@#" + processPid + "#@#" + processCpu + "#@#" + processMem);
String unitId = pro_PRE_UNITID + "-" + i--;
// 进程用户 CM-00-01-005-06
collResult.addKPI(unitId, "CM-00-01-005-06", processUser);
// 进程ID CM-00-01-005-01
collResult.addKPI(unitId, "CM-00-01-005-01", processPid);
// 进程占用CPU百分比 PM-00-01-005-10
collResult.addKPI(unitId, "PM-00-01-005-10", processCpu);
// 进程占用MEM百分比 PM-00-01-005-11
collResult.addKPI(unitId, "PM-00-01-005-11", processMem);
// 进程指令行 CM-00-01-005-08
collResult.addKPI(unitId, "CM-00-01-005-08", processCmd);
// 更新时间 CM-00-03-002-10
collResult.addKPI(unitId, "CM-00-03-002-10", Formater.datetimeToString(new Date()));
}
}
} catch (Exception e) {
logger.error("getProcessTop5Mem has error", e);
} finally {
release();
}
logger.info("end getProcessTop5Mem");
return collResult.getKPISet();
}
public Vector getProcessTop5Cpu(HashMap params) {
logger.info("begin getProcessTop5Cpu");
System.out.println("begin getProcessTop5Cpu");
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
if(!tt.isAuthorized()){
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", tt.getError());
return collResult.KPISet;
}else{
String totalUnitId = this.PRE_UNITID + "-10:" + neat_host_name + "-total";
// collResult.addKPI(totalUnitId, "FM-00-01-001-01", "UP");
}
String pro_PRE_UNITID = PRE_UNITID + "-28:" + neat_host_name;
String cmd = "ps aux --sort=-pcpu | grep -v %CPU | head -5";
System.out.println(cmd);
Vector<String> vec = tt.getResultAsVector(cmd);
if (vec == null || vec.equals("") || vec.equals("null")) {
//
} else {
int i = 1;
for (String processInfo : vec) {
String processUser = split(processInfo, 0);
String processPid = split(processInfo, 1);
String processCpu = split(processInfo, 2);
String processMem = split(processInfo, 3);
String processCmd = split(processInfo, 10);
System.out.println(processUser + "#@#" + processPid + "#@#" + processCpu + "#@#" + processMem);
String unitId = pro_PRE_UNITID + "-" + i++;
// 进程用户 CM-00-01-005-06
collResult.addKPI(unitId, "CM-00-01-005-06", processUser);
// 进程ID CM-00-01-005-01
collResult.addKPI(unitId, "CM-00-01-005-01", processPid);
// 进程占用CPU百分比 PM-00-01-005-10
collResult.addKPI(unitId, "PM-00-01-005-10", processCpu);
// 进程占用MEM百分比 PM-00-01-005-11
collResult.addKPI(unitId, "PM-00-01-005-11", processMem);
// 进程指令行 CM-00-01-005-08
collResult.addKPI(unitId, "CM-00-01-005-08", processCmd);
// 更新时间 CM-00-03-002-10
collResult.addKPI(unitId, "CM-00-03-002-10", Formater.datetimeToString(new Date()));
}
}
} catch (Exception e) {
logger.error("getProcessTop5Cpu has error", e);
} finally {
release();
}
logger.info("end getProcessTop5Cpu");
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 -i warning /var/log/syslog | 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;
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-26-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 {
release();
}
return collResult.getKPISet();
}
public void release() {
if (tt != null){
tt.close();
tt=null;
}
System.gc();
}
public Vector getDmesg(HashMap params) {
/**
* KPI1=CM-00-01-900-04 #事件id KPI2=CM-00-01-900-05 #发生的时间
* KPI3=CM-00-01-900-06 #事件类型 KPI4=CM-00-01-900-07 #事件来源
* KPI5=CM-00-01-900-08 #错误的资源的名称 KPI6=CM-00-01-900-09 #错误汇总
*/
CollBase collResult = new CollBase();
String host_ip = (String) params.get("IP_ADDR");
String now_filename = "now_" + host_ip + ".mesg";
String tmp_filename = "tmp_" + host_ip + ".mesg";
String diff_filename = "diff_" + host_ip + ".mesg";
String keywords = (String) params.get("KEYWORDS");
String sys_log_path = (String)params.get("SYSLOG_PATH");
if(sys_log_path==null||sys_log_path.trim().equals("")){
sys_log_path = "/var/log/";
}else{
if(!sys_log_path.startsWith("/")){
sys_log_path = "/" + sys_log_path;
}
if(!sys_log_path.endsWith("/")){
sys_log_path = sys_log_path + "/";
}
}
String[] keyword = null;
if(keywords==null||keywords.equals("")){
keywords ="error,ERROR,Error,warning,Warning,WARNING";
}
keyword = keywords.split(",");
try {
init(params);
String now =null;
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(host_ip.equals("192.168.3.180")){
// logger.info(" the now file is too long "+host_ip+" : "+now.toString());
// }
try {
// 日志解析
if (tmp_file.exists() && tmp_file.length() > 0) {// 非第一次采集
// write_now.close();
// 读取上周期日志文件(tmp)
FileReader tmp_reader = new FileReader(tmp_file);
BufferedReader tmp = new BufferedReader(tmp_reader);
String line;
//StringBuffer tmp_file_string = new StringBuffer();
HashSet set = new HashSet();
while ((line = tmp.readLine()) != null) {
//tmp_file_string.append(line + "\n");
set.add(line.trim());
}
try {
tmp.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
tmp_reader.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
write_tmp = new PrintWriter(new OutputStreamWriter(
new FileOutputStream(tmp_file), "GB2312"));
for(int i=0;i<keyword.length;i++){
now = tt.getResultAsStr("cat "+sys_log_path+"messages | grep '"+keyword[i]+"'");
write_now.write(now+"\n");
write_tmp.write(now+"\n");
}
write_now.flush();
write_tmp.flush();
// tmp.close();
// tmp_reader.close();
// 读取本周期日志文件(now),生成差异文件(diff)
FileReader now_reader = new FileReader(now_file);
BufferedReader br = new BufferedReader(now_reader);
try {
while ((line = br.readLine()) != null) {
/*if (tmp_file_string.indexOf(line) == -1)
write_diff.write(line);
else
continue;*/
if(!set.contains(line.trim())){
write_diff.write(line+"\n");
}else{
continue;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
now_reader.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
}
write_diff.flush();
// write_diff.close();
// write_tmp.close();
} else {// 第一次采集
for(int i=0;i<keyword.length;i++){
now = tt.getResultAsStr("cat "+sys_log_path+"messages | grep '"+keyword[i]+"'");
write_diff.write(now+"\n");
write_tmp.write(now+"\n");
}
write_tmp.flush();
write_diff.flush();
}
} catch (Throwable th) {
th.printStackTrace();
} finally {
try {
write_now.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
write_diff.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
write_tmp.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
}
try {
// 生成指标
FileReader diff_reader = new FileReader(diff_file);
BufferedReader diff = new BufferedReader(diff_reader);
String line1;
// example{tg3: eth0: Link is up at 100 Mbps, full duplex.}
try {
while ((line1 = diff.readLine()) != null) {
// 判断该行是否存在错误关键字
boolean isError = false;
String error_words = "";
if (keyword != null) {
for (int j = 0; j < keyword.length; j++) {
if (line1.indexOf(keyword[j]) != -1) {
isError = true;
error_words = keyword[j];
break;
}
}
} else {
if (line1.indexOf("error") != -1
|| line1.indexOf("ERROR") != -1
|| line1.indexOf("Error") != -1) {
isError = true;
error_words = "ERROR";
} else if (line1.indexOf("warning") != -1
|| line1.indexOf("Warning") != -1
|| line1.indexOf("WARNING") != -1) {
error_words = "WARNING";
isError = true;
}
}
// 如果包含错误关键字 则生成KPI
if (isError == true) {
/*
* String device = ""; String msg = ""; if
* (line1.indexOf(":") != -1) { device =
* line1.substring(0, line1.indexOf(":")); } String
* unitid = "10-10-22-17:" + neat_host_name +
* "-syslog-" + device; collResult .addKPI(unitid,
* "CM-00-01-900-08", device);
* collResult.addKPI(unitid, "CM-00-01-900-09",
* line1); if (line1.indexOf("error") != -1 ||
* line1.indexOf("ERROR") != -1 ||
* line1.indexOf("Error") != -1) {
* collResult.addKPI(unitid, "FM-00-01-900-04",
* "ERROR"); } else { collResult.addKPI(unitid,
* "FM-00-01-900-04", "WARING"); }
*/
String unitid = PRE_UNITID+"-17:" + neat_host_name
+ "-dmesg-" + error_words;
collResult.addKPI(unitid, "CM-00-01-900-08", error_words);
if(line1.length()<200){
collResult.addKPI(unitid, "CM-00-01-900-09", line1);
}else{
collResult.addKPI(unitid, "CM-00-01-900-09", line1.substring(0,200));
}
collResult.addKPI(unitid, "CM-00-01-001-30",Formater.datetimeToString(new Date()));
//collResult.addKPI(unitid, "CM-00-01-990-10","YES");
}
}
} catch (Throwable th4) {
} finally {
try {
if (diff != null) {
diff.close();
}
} catch (Exception e3) {
e3.printStackTrace();
}
try {
if (diff != null) {
diff_reader.close();
}
} catch (Exception e3) {
e3.printStackTrace();
}
}
} catch (Throwable th2) {
th2.printStackTrace();
}
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
} catch (Error er) {
logger.error(er);
} finally {
release();
}
return collResult.getKPISet();
}
public Vector getSyslogBylogPath(HashMap params) {
/**
* KPI1=CM-00-01-900-04 #事件id KPI2=CM-00-01-900-05 #发生的时间
* KPI3=CM-00-01-900-06 #事件类型 KPI4=CM-00-01-900-07 #事件来源
* KPI5=CM-00-01-900-08 #错误的资源的名称 KPI6=CM-00-01-900-09 #错误汇总
*/
CollBase collResult = new CollBase();
String host_ip = (String) params.get("IP_ADDR");
String now_filename = "now_" + host_ip + ".syslog";
String tmp_filename = "tmp_" + host_ip + ".syslog";
String diff_filename = "diff_" + host_ip + ".syslog";
String keywords = (String) params.get("KEYWORDS");
String log_path = (String) params.get("SYSLOG_PATH");
if(log_path==null||log_path.equals("")){
return collResult.getKPISet();
}
try {
init(params);
String now = tt.getResultAsStr("cat "+log_path);
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);
try {
// 日志解析
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);
try {
while ((line = br.readLine()) != null) {
if (tmp_file_string.indexOf(line) == -1)
write_diff.write(line);
else
continue;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
tmp.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
tmp_reader.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
br.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
now_reader.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
}
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();
}
} catch (Throwable th) {
th.printStackTrace();
} finally {
try {
write_now.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
write_diff.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
write_tmp.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
}
try {
// 生成指标
FileReader diff_reader = new FileReader(diff_file);
BufferedReader diff = new BufferedReader(diff_reader);
String line1;
// example{tg3: eth0: Link is up at 100 Mbps, full duplex.}
String[] keyword = null;
keyword = keywords.split(",");
try {
while ((line1 = diff.readLine()) != null) {
// 判断该行是否存在错误关键字
boolean isError = false;
String error_words = "";
if (keyword != null) {
for (int j = 0; j < keyword.length; j++) {
if (line1.indexOf(keyword[j]) != -1) {
isError = true;
error_words = keyword[j];
break;
}
}
} else {
if (line1.indexOf("error") != -1
|| line1.indexOf("ERROR") != -1
|| line1.indexOf("Error") != -1) {
isError = true;
error_words = "ERROR";
} else if (line1.indexOf("waring") != -1
|| line1.indexOf("Waring") != -1
|| line1.indexOf("WARING") != -1) {
error_words = "WARING";
isError = true;
}
}
// 如果包含错误关键字 则生成KPI
if (isError == true) {
/*
* String device = ""; String msg = ""; if
* (line1.indexOf(":") != -1) { device =
* line1.substring(0, line1.indexOf(":")); } String
* unitid = "10-10-22-17:" + neat_host_name +
* "-syslog-" + device; collResult .addKPI(unitid,
* "CM-00-01-900-08", device);
* collResult.addKPI(unitid, "CM-00-01-900-09",
* line1); if (line1.indexOf("error") != -1 ||
* line1.indexOf("ERROR") != -1 ||
* line1.indexOf("Error") != -1) {
* collResult.addKPI(unitid, "FM-00-01-900-04",
* "ERROR"); } else { collResult.addKPI(unitid,
* "FM-00-01-900-04", "WARING"); }
*/
String unitid = PRE_UNITID+"-17:" + neat_host_name
+ "-dmesg-" + error_words;
collResult
.addKPI(unitid, "CM-00-01-900-08", error_words);
if(line1.length()<200){
collResult.addKPI(unitid, "CM-00-01-900-09", line1);
}else{
collResult.addKPI(unitid, "CM-00-01-900-09", line1.substring(0,200));
}
collResult.addKPI(unitid, "FM-00-01-900-04",error_words);
}
}
} catch (Throwable th4) {
} finally {
try {
if (diff != null) {
diff.close();
}
} catch (Exception e3) {
e3.printStackTrace();
}
try {
if (diff != null) {
diff_reader.close();
}
} catch (Exception e3) {
e3.printStackTrace();
}
}
} catch (Throwable th2) {
th2.printStackTrace();
}
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
} catch (Error er) {
logger.error(er);
} finally {
release();
}
return collResult.getKPISet();
}
public Vector getSyslogBylogPathUseGrep(HashMap params) {
CollBase collResult = new CollBase();
String host_ip = (String) params.get("IP_ADDR");
String now_filename = "now_" + host_ip + ".syslog";
String tmp_filename = "tmp_" + host_ip + ".syslog";
String diff_filename = "diff_" + host_ip + ".syslog";
String keywords = (String) params.get("KEYWORDS");
String log_path = (String) params.get("SYSLOG_PATH");
if(log_path==null||log_path.equals("")){
return collResult.getKPISet();
}
String[] keyword ={"error","ERROR","Error","waring","Waring","WARING"};
if(keywords!=null){
keyword = keywords.split(",");
}
try {
init(params);
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);
try {
String now = "";
// 日志解析
if (tmp_file.exists() && tmp_file.length() > 0) {// 非第一次采集
StringBuffer tmp_file_string = new StringBuffer();
// write_now.close();
// 读取上周期日志文件(tmp)
FileReader tmp_reader = new FileReader(tmp_file);
BufferedReader tmp = new BufferedReader(tmp_reader);
String line;
while ((line = tmp.readLine()) != null) {
tmp_file_string.append( line + "\n");
}
for(int i=0;i<keyword.length;i++){
now = tt.getResultAsStr("grep "+keyword[i]+" "+log_path);
write_now.write(now);
}
write_now.flush();
// tmp.close();
// tmp_reader.close();
// 读取本周期日志文件(now),生成差异文件(diff)
FileReader now_reader = new FileReader(now_file);
BufferedReader br = new BufferedReader(now_reader);
try {
while ((line = br.readLine()) != null) {
if (tmp_file_string.indexOf(line) == -1)
write_diff.write(line);
else
continue;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
tmp.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
tmp_reader.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
br.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
now_reader.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
}
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 {
// 第一次采集
for(int i=0;i<keyword.length;i++){
now = tt.getResultAsStr("grep "+keyword[i]+" "+log_path);
write_tmp.write(now);
write_tmp.flush();
// write_tmp.close();
write_diff.write(now);
write_diff.flush();
// write_diff.close();
}
}
} catch (Throwable th) {
th.printStackTrace();
} finally {
try {
write_now.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
write_diff.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
try {
write_tmp.close();
} catch (Throwable th1) {
th1.printStackTrace();
}
}
try {
// 生成指标
FileReader diff_reader = new FileReader(diff_file);
BufferedReader diff = new BufferedReader(diff_reader);
String line1;
// example{tg3: eth0: Link is up at 100 Mbps, full duplex.}
try {
while ((line1 = diff.readLine()) != null) {
// 判断该行是否存在错误关键字
boolean isError = false;
String error_words = "";
if (keyword != null) {
for (int j = 0; j < keyword.length; j++) {
if (line1.indexOf(keyword[j]) != -1) {
isError = true;
error_words = keyword[j];
break;
}
}
}
// 如果包含错误关键字 则生成KPI
if (isError == true) {
/*
* String device = ""; String msg = ""; if
* (line1.indexOf(":") != -1) { device =
* line1.substring(0, line1.indexOf(":")); } String
* unitid = "10-10-22-17:" + neat_host_name +
* "-syslog-" + device; collResult .addKPI(unitid,
* "CM-00-01-900-08", device);
* collResult.addKPI(unitid, "CM-00-01-900-09",
* line1); if (line1.indexOf("error") != -1 ||
* line1.indexOf("ERROR") != -1 ||
* line1.indexOf("Error") != -1) {
* collResult.addKPI(unitid, "FM-00-01-900-04",
* "ERROR"); } else { collResult.addKPI(unitid,
* "FM-00-01-900-04", "WARING"); }
*/
String unitid = PRE_UNITID+"-17:" + neat_host_name
+ "-syslog-" + error_words;
collResult
.addKPI(unitid, "CM-00-01-900-08", error_words);
if(line1.length()<200){
collResult.addKPI(unitid, "CM-00-01-900-09", line1);
}else{
collResult.addKPI(unitid, "CM-00-01-900-09", line1.substring(0,200));
}
collResult.addKPI(unitid, "FM-00-01-900-04",error_words);
}
}
} catch (Throwable th4) {
} finally {
try {
if (diff != null) {
diff.close();
}
} catch (Exception e3) {
e3.printStackTrace();
}
try {
if (diff != null) {
diff_reader.close();
}
} catch (Exception e3) {
e3.printStackTrace();
}
}
} catch (Throwable th2) {
th2.printStackTrace();
}
} catch (Exception e) {
e.getMessage();
e.printStackTrace();
} catch (Error er) {
logger.error(er);
} finally {
release();
}
return collResult.getKPISet();
}
public Vector getPing(HashMap<String, String> params) {
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
if ((params.get("PING_IP_ADDR") != null && !"".equals(params.get("PING_IP_ADDR").toString())) &&
(params.get("PING_USERNAME") != null && !"".equals(params.get("PING_USERNAME").toString())) &&
(params.get("PING_PASSWORD") != null && !"".equals(params.get("PING_PASSWORD").toString())) &&
(params.get("PING_PROTOCOL") != null) && !"".equals(params.get("PING_PROTOCOL").toString())){
this.flag = true;
init(params);
if (isConnect) {
String net_unit = PRE_UNITID + "-35:" + neat_host_name;
List<String> ips = split(params.get("POINT_IPS"), ",");
for (String ip : ips) {
String pingResult = "ping -c 5 " + ip + "|grep -E 'transmitted|pipe|rtt'";
Vector pingV = tt.getResultAsVector(pingResult);
if (tt.isAuthorized()) {
if (!pingV.isEmpty()) {
String unitid = net_unit + "-" + ip;
String packageLoss = "";
String responseAvgTime = "";
String responseMaxTime = "";
String lossInfo = pingV.get(0).toString();
String respInfo = "";
if (pingV.size() == 2) {
respInfo = pingV.get(1).toString();
packageLoss = StringUtils.remove(split(lossInfo, 5), "%");
responseAvgTime = split(respInfo, "/").get(4).toString();
responseMaxTime = split(respInfo, "/").get(5).toString();
} else {
packageLoss = "100";
responseAvgTime = "∞";
responseMaxTime = "∞";
}
collResult.addKPI(unitid, "CM-00-01-006-01", (String)params.get("PING_IP_ADDR"));
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", responseAvgTime);
collResult.addKPI(unitid, "PM-00-01-006-16", responseMaxTime);
}
}else{
logger.error("fail getPing:" + ip + "! SSH session is down!! isAuthorized=" + tt.isAuthorized());
if (!ip.equals(ips.get(ips.size()-1))) {
init(params);
}
}
}
}else{
logger.error("getPing has error:ssh session Failed!! isConnect=" + isConnect);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
release();
}
return collResult.getKPISet();
}
/**
* 获取demsg信息,过滤关键字
* PM-00-01-001-25 demsg异常记录数
*/
public Vector getDemsg(HashMap<String, String> params) {
logger.info("begin getDemsg : " + params.get("DEMSG_KEY"));
// 保存采集结果,并返回值
CollBase collResult = new CollBase();
try {
init(params);
String demsg_key = (String) params.get("DEMSG_KEY");
String pro_PRE_UNITID = PRE_UNITID + "-10:" + neat_host_name + "-total";
String cmd = "dmesg | grep -E '" + demsg_key + "'";
// [ssdbomc@kfapp ~]$ dmesg | grep Disabled
// SELinux: Disabled at runtime.
// lo: Disabled Privacy Extensions
Vector demsgV = tt.getResultAsVector(cmd);
if (!demsgV.isEmpty() && !"".equals(demsgV.get(0))) {
collResult.addKPI(pro_PRE_UNITID, "PM-00-01-001-25", demsgV.size() + "");
return collResult.getKPISet();
} else {
collResult.addKPI(pro_PRE_UNITID, "PM-00-01-001-25", "0");
return collResult.getKPISet();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
release();
}
logger.info("end getDemsg : " + params.get("DEMSG_KEY"));
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:" + neat_host_name + "-";
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, neat_host_name);
//文件名称
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());
List<List<String>> resultList = analyticalResult(netlogV);
for(List list:resultList){
if(list.size() ==2){
//添加采集路径
// CM-20-21-027-21关键路径
collResult.addKPI(UNIT_ID + "-74:"+neat_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:"+neat_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();
}
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;
}
// 采集cpu利用率,共采集times次,每次采集间隔interval秒
private String getCPU_Rate(int times, int interval) {
CollBase collResult = new CollBase();
float cpu_value = 0;
for (int i = 0; i < times; i++) {
Vector cpuout = this.tt.getResultAsVector("vmstat 1 3");
String cpurun = (String) cpuout.elementAt(cpuout.size() - 1);
cpu_value = (100 - Integer.parseInt(collResult.split(cpurun, 14)))
+ cpu_value;
try {
Thread.sleep(interval * 1000L);
} catch (Exception e) {
e.printStackTrace();
}
}
cpu_value = cpu_value / times;
return Formater.formatDecimalKpivalue(Float.toString(cpu_value));
}
public String[] split2Array(String str, String sp) {
ArrayList al = split(str, sp);
Object[] os = al.toArray();
String[] ss = new String[os.length];
for (int i = 0; i < os.length; i++) {
ss[i] = (String) os[i];
}
return ss;
}
public static void main(String[] args) {
HashMap params = new HashMap();
System.out.print(BigDecimal.valueOf(1.05599999999999).divide(BigDecimal.ONE,2,BigDecimal.ROUND_HALF_UP));
// params.put("IP_ADDR", "172.18.30.32");
// params.put("USERNAME", "basd");
// params.put("PASSWORD",
// "c88b4daa9cefa1803e45d3905008c490aa1a0278bff3c367");
// params.put("PROTOCOL", "ssh");
// params.put("PROCESS_NAME", "");
// params.put("MAX_COUNT", "2");
// params.put("HOSTNAME", "yf-ys2");
// params.put("MIN_COUNT", "1");
if(args.length<6){
System.exit(0);
}
params.put("IP_ADDR", args[0]);
params.put("USERNAME", args[1]);
String pass = args[2];
pass = DES3.encrypt(pass);
System.out.println("password:"+pass);
params.put("PASSWORD",pass);
params.put("PROTOCOL", args[3]);
// params.put("PROCESS_NAME", "");
// params.put("MAX_COUNT", "2");
params.put("HOSTNAME", args[4]);
params.put("KEYWORDS", args[5]);
CollLinuxWithCMD coll = new CollLinuxWithCMD();
// Vector lst = coll.getDiskForIOstat(params);
Vector lst = coll.getDmesg(params);
System.out.println("lst.size() is " + lst.size());
for (int i = 0; i < lst.size(); i++) {
TblATO_KPIDETAIL kpidetail = (TblATO_KPIDETAIL) lst.get(i);
System.out.println(kpidetail.UNIT_ID + "|" + kpidetail.KPI_ID + "|"
+ kpidetail.CLL_TIME + "|" + kpidetail.KPI_VALUE);
}
}
}