-
Notifications
You must be signed in to change notification settings - Fork 4
/
metraixbeat
5430 lines (4531 loc) · 239 KB
/
metraixbeat
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
#!/opt/bin/python3
# Python header
__author__ = "Benjamin Herson-Macarel"
#__copyright__ = ""
__credits__ = ["Who", "wants", "to", "be", "added", "???"]
__license__ = "GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007"
__version__ = "1.21.12"
__maintainer__ = "Benjamin Herson-Macarel"
__email__ = "[email protected]"
__status__ = "Stable"
# Imports
import os
import sys
import getopt
import time
import subprocess
import threading
import datetime
import socket
import ssl
import math
import json
import select
import re
import random
import signal
import traceback
import shutil
import logging
# The following are python packages from other developers. Dependencies need to be installed as a prerequisite
# requests for handling HTTP requets in efficient and simple way
import requests
from requests.exceptions import HTTPError
# Parsing ping results and get output in JSON (efficient and no time to waste developing the same...)
import pingparsing
# Classes
# Functions
def LoadDaemonConfig():
"""This function will get all the required parameters from config file and load them into vars
TODO: Describe the fcuntion, all vars and its content
"""
# Switching vars to global
global BaseDir
global LogFilePath
global ConfigFilePath
global ELKMonitoringVersion
global ECSVersion
global ElasticServers
global FilebeatServers
global LogstashServers
global ElasticPort
global FilebeatPort
global LogstashPort
global ELKUsername
global ELKPassword
global ELKWebProtocol
global ELKCertificate
global ElasticIndexName
global FilebeatIndexName
global ElasticServersAvailable
global FilebeatServersAvailable
global LogstashServersAvailable
global ElasticServersFailed
global FilebeatServersFailed
global LogstashServersFailed
global FQDN
global TailRefreshValue
global CycleSleepTime
global DiskSampleRate
global TopProcesses
global SystemProcessWaitValue
global SystemFilesystemAndFstatWaitValue
global SystemDiskIOWaitValue
global SystemProcessSummaryWaitValue
global SystemLoadWaitValue
global SystemFcWaitValue
global SystemSocketSummaryWaitValue
global SystemSocketWaitValue
global SystemMemoryWaitValue
global SystemNetworkWaitValue
global SystemCoreAndCpuWaitValue
global IfSystemHPMStatEnable
global IfSystemHypervisorEnable
global SystemHPMStatWaitValue
global SystemHypervisorWaitValue
global ErrptLogWaitValue
global PingPlotterTargets
global PingPlotterWaitValue
global PingSamples
global PingTimeout
global EntRestricted
global FcsRestricted
global HdiskRestricted
global Tags
global Tagz
global Labels
global BulkMaxSize
global NMONSeq
# Checking if Configuration file exists
if os.path.exists(ConfigFilePath):
# Executing with Try/Catch to handle any error in file
try:
with open(ConfigFilePath, 'r') as ConfigFile:
# Loading JSOn file content
JSONValues = json.load(ConfigFile)
# Set variables for ELK server.
ELKMonitoringVersion = JSONValues["ELKMonitoringVersion"]
ECSVersion = JSONValues["ECSVersion"]
ElasticServers = JSONValues["ElasticServers"]
FilebeatServers = JSONValues["FilebeatServers"]
LogstashServers = JSONValues["LogstashServers"]
# Checking if Filebeat output is empty
if len(FilebeatServers) == 0:
# Then defaulting to Metricbeat output
FilebeatServers = ElasticServers
# Checking if Logstash output is empty
if len(LogstashServers) == 0:
# Then defaulting to Metricbeat output
LogstashServers = ElasticServers
ELKUsername = JSONValues["ELKUsername"]
ELKPassword = JSONValues["ELKPassword"]
ELKCertificate = JSONValues["ELKCertificate"]
# Handling if ELKCertificate is empty
if(len(ELKCertificate) == 0):
ELKCertificate = "True"
ElasticPort = JSONValues["ElasticPort"]
FilebeatPort = JSONValues["FilebeatPort"]
LogstashPort = JSONValues["LogstashPort"]
ELKWebProtocol = JSONValues["ELKWebProtocol"]
# Duplicating *Servers to *ServersAvailable making all ELK servers failed by default
ElasticServersAvailable = ElasticServers[:]
ElasticServersFailed = []
FilebeatServersAvailable = FilebeatServers[:]
FilebeatServersFailed = []
LogstashServersAvailable = LogstashServers[:]
LogstashServersFailed = []
ElasticIndexName = JSONValues["ElasticIndexName"]
FilebeatIndexName = JSONValues["FilebeatIndexName"]
# Setting NMON sequence counter to 0
NMONSeq = 0
# Script functional variables
# Time to wait before refreshing tail's processes status (in seconds)
TailRefreshValue = int(JSONValues["TailRefreshValue"])
# Time to wait between two execution of the Main Loop (in seconds)
CycleSleepTime = int(JSONValues["CycleSleepTime"])
# How much time to run metric commands and get averaged results
DiskSampleRate = int(JSONValues["DiskSampleRate"])
# If different than 0, set the limit of processes that must be taken into account while checking TOP processes CPU activity
TopProcesses = int(JSONValues["TopProcesses"])
# Adding FQDN to the hostname if not existing, andd necessary...
FQDN = JSONValues["FQDN"]
# How much messages are sent within one connection to server
BulkMaxSize = int(JSONValues["BulkMaxSize"])
# Topic timers variables (in seconds)
# Time to wait before sending new metric values to ELK server
SystemProcessWaitValue = int(JSONValues["SystemProcessWaitValue"])
SystemFilesystemAndFstatWaitValue = int(JSONValues["SystemFilesystemAndFstatWaitValue"])
SystemDiskIOWaitValue = int(JSONValues["SystemDiskIOWaitValue"])
SystemProcessSummaryWaitValue = int(JSONValues["SystemProcessSummaryWaitValue"])
SystemLoadWaitValue = int(JSONValues["SystemLoadWaitValue"])
SystemFcWaitValue = int(JSONValues["SystemFcWaitValue"])
SystemSocketSummaryWaitValue = int(JSONValues["SystemSocketSummaryWaitValue"])
SystemSocketWaitValue = int(JSONValues["SystemSocketWaitValue"])
SystemMemoryWaitValue = int(JSONValues["SystemMemoryWaitValue"])
SystemNetworkWaitValue = int(JSONValues["SystemNetworkWaitValue"])
SystemCoreAndCpuWaitValue = int(JSONValues["SystemCoreAndCpuWaitValue"])
# Loading PingPlotter targets and configuration values
PingPlotterTargets = JSONValues["PingPlotterTargets"]
PingPlotterWaitValue = int(JSONValues["PingPlotterWaitValue"])
PingSamples = int(JSONValues["PingSamples"])
PingTimeout = JSONValues["PingTimeout"]
# Checking other JSON values linked to custom plugins
IfSystemHPMStatEnable = JSONValues["IfSystemHPMStatEnable"]
IfSystemHypervisorEnable = JSONValues["IfSystemHypervisorEnable"]
SystemHPMStatWaitValue = int(JSONValues["SystemHPMStatWaitValue"])
SystemHypervisorWaitValue = int(JSONValues["SystemHypervisorWaitValue"])
ErrptLogWaitValue = int(JSONValues["ErrptLogWaitValue"])
# Loading Tags
Tags = JSONValues["tags"]
# Generating tagz var for rollup purpose
Tagz = ""
for Tag in Tags:
Tagz += Tag + ','
Tagz = Tagz[:-1]
# Loading Labels
Labels = JSONValues["labels"]
# Loading some parameter that can restrict the number of devices checked for some cases
# Network Adapters
EntRestricted = JSONValues["EntRestricted"]
# Fiber Channel Adapters
FcsRestricted = JSONValues["FcsRestricted"]
# HDISK devices
HdiskRestricted = JSONValues["HdiskRestricted"]
# Checking if Proxy bypass is required
BypassProxy = JSONValues["bypassproxy"]
# Disabling proxy if requested
if BypassProxy == 'yes':
os.environ['no_proxy'] = '*'
except:
# problem encountered while loading JSON daemon configuration file, exiting
logging.info(" ==> Error while loading " + ConfigFilePath + " daemon config file !")
logging.info(" Please check the Configuration file JSON parameters, format and validity")
logging.info(str(traceback.print_exc()))
traceback.print_exc()
os._exit(2)
else:
# Daemon configuration file does not exist, exiting
logging.info(" ==> Error while loading " + ConfigFilePath + " daemon config file !")
logging.info(" Config file does not exist")
logging.info(str(traceback.print_exc()))
traceback.print_exc()
os._exit(2)
# Log
# Log
logging.info(" - Loading Daemon configuration... Done !")
# Debug
# print('\nDEBUG\n')
# print('<!> DEBUG ', ELKMonitoringVersion, 'ELKMonitoringVersion')
# print('<!> DEBUG ', ECSVersion, 'ECSVersion')
# print('<!> DEBUG ', BaseDir, 'BaseDir')
# print('<!> DEBUG ', Metricbeat_LogStash_HostName, 'Metricbeat_LogStash_HostName')
# print('<!> DEBUG ', Filebeat_LogStash_HostName, 'Filebeat_LogStash_HostName')
# print('<!> DEBUG ', Metricbeat_LogStash_PORT, 'Metricbeat_LogStash_PORT')
# print('<!> DEBUG ', Filebeat_LogStash_PORT, 'Filebeat_LogStash_PORT')
# print('<!> DEBUG ', FQDN, 'FQDN')
# print('<!> DEBUG ', TailRefreshValue, 'TailRefreshValue')
# print('<!> DEBUG ', CycleSleepTime, 'CycleSleepTime')
# print('<!> DEBUG ', DiskSampleRate, 'DiskSampleRate')
# print('<!> DEBUG ', TopProcesses, 'TopProcesses')
# print('<!> DEBUG ', SystemProcessWaitValue, 'SystemProcessWaitValue')
# print('<!> DEBUG ', SystemFilesystemAndFstatWaitValue, 'SystemFilesystemAndFstatWaitValue')
# print('<!> DEBUG ', SystemDiskIOWaitValue, 'SystemDiskIOWaitValue')
# print('<!> DEBUG ', SystemProcessSummaryWaitValue, 'SystemProcessSummaryWaitValue')
# print('<!> DEBUG ', SystemLoadWaitValue, 'SystemLoadWaitValue')
# print('<!> DEBUG ', SystemFcWaitValue, 'SystemFcWaitValue')
# print('<!> DEBUG ', SystemMemoryWaitValue, 'SystemMemoryWaitValue')
# print('<!> DEBUG ', SystemNetworkWaitValue, 'SystemNetworkWaitValue')
# print('<!> DEBUG ', SystemCoreAndCpuWaitValue, 'SystemCoreAndCpuWaitValue')
# print('\nFINDEBUG\n')
pass
def LoadPluginConfig():
"""This function will get all the required information from Plugin config files and load them into vars
All files analyzed need to be in the same folder than main Parameters.conf file and have specific naming convention
Please refer to README.md
TODO: Describe the function, all vars and its content
"""
# Log
logging.info(" - Loading Filebeat plugin's config files...")
# Using global FilebeatConfigsArray and CustomMetricsConfigsArray dictionary for follow up purpose
global FilebeatConfigsArray
global CustomMetricsConfigsArray
global PingPlotterArray
global TargetFileCurrentPosArray
# Switching vars to global
global ConfigFilePath
# Defining config path from ConfigFilePath
ConfigPathtmp = ConfigFilePath.split('/').pop()
ConfigPath = ConfigFilePath.replace(ConfigPathtmp,'')
# Loading filebeat plugin configs
for f_name in os.listdir(ConfigPath):
if f_name.endswith('filebeat.conf'):
# Log
logging.info(" " + f_name + ":")
# Generating full path name for current file
FullPathFileName = ConfigPath + f_name
# Loading JSON file content
# We load JSON content into try/catch to avoid failure if JSON formatting is not good.
try:
with open(FullPathFileName, 'r') as ConfigFile:
JSONValues = json.load(ConfigFile)
# Log
logging.info(" * Target file = " + JSONValues["TargetFile"])
logging.info(" * Patterns = " + str(JSONValues["Patterns"]))
logging.info(" * Multiline sparator REGEX = " + JSONValues["MultilineSeparator"])
logging.info(" * Output = " + JSONValues["Output"])
# Generating EGREP string from list of patterns
PatternMatch = ""
for Pattern in JSONValues["Patterns"]:
PatternMatch = PatternMatch + Pattern + "|"
PatternMatch = PatternMatch[:-1]
# Converting date format, if any, in target file
CurrentTargetFile = ConvertFileName(JSONValues["TargetFile"])
# Checking if file exists
try:
# Looking for corresponding file
OSCommand = "ls -lart " + CurrentTargetFile + " | tail -n 1 | awk '{print $NF}'"
CheckTargetFile = subprocess.Popen(OSCommand, shell=True, stdout=subprocess.PIPE, stderr = devnull).stdout
CheckTargetFile = CheckTargetFile.read().decode().split()
# Checking if file exists
if os.path.exists(str(CheckTargetFile[0])):
# If yes
CurrentTargetFile = str(CheckTargetFile[0])
# Storing the last line of the Target file to start tail on
with open(CurrentTargetFile, "r") as LastLine:
TargetFileLastLine = len(LastLine.readlines()) + 1
# Storing the inode and size of the Target file to start tail on
TargetFileInode = os.stat(CurrentTargetFile).st_ino
TargetFileSize = os.stat(CurrentTargetFile).st_size
else:
# If no
# File does not exists, rising a warning but loading config with 0 default values
LastLine = 0
TargetFileInode = 0
TargetFileSize = 0
TargetFileLastLine = 0
# Log
logging.info(" ==> Warning while loading " + f_name + " config file !")
logging.info(" File does not exists yet, daemon will retry later...")
# Initializing state value to start tail from line 1 when file will be available
TargetFileCurrentPosArray[f_name] = 0
except:
# File does not exists, rising a warning but loading config with 0 default values
LastLine = 0
TargetFileInode = 0
TargetFileSize = 0
TargetFileLastLine = 0
# Log
logging.info(" ==> Warning while loading " + f_name + " config file !")
logging.info(" File does not exists yet, daemon will retry later...")
# Initializing state value to start tail from line 1 when file will be available
TargetFileCurrentPosArray[f_name] = 0
# Storing results into FilebeatConfigsArray dictionnary
ConfigString = CurrentTargetFile + ',' + JSONValues["TargetFile"] + ',' + PatternMatch + ',' + str(TargetFileLastLine) + ',' + str(TargetFileInode) + ',' + str(TargetFileSize) + ',' + str(JSONValues["MultilineSeparator"] + ',' + str(JSONValues["Output"]))
FilebeatConfigsArray[f_name] = ConfigString
except:
# If error, bypassing this plugin
# Log
logging.info(" ==> Error while loading " + f_name + " config file !")
logging.info(" Please check JSON format and validity")
logging.info(str(traceback.print_exc()))
traceback.print_exc()
# pass
# All filebeat plugins loaded
# Log
logging.info(" ==> All Filebeat plugin's config files loaded !")
# Log
logging.info(" - Loading Custom Metric plugin's config files...")
# Loading custom exec plugin configs
for f_name in os.listdir(ConfigPath):
if f_name.endswith('custom.conf'):
# Log
logging.info(" " + f_name + ":")
# Generating full path name for current file
FullPathFileName = ConfigPath + f_name
# Loading JSON file content
# We load JSON content into try/catch to avoid failure if JSON formatting is not good.
try:
with open(FullPathFileName, 'r') as ConfigFile:
JSONValues = json.load(ConfigFile)
# Log
logging.info(" * OS Script = " + JSONValues["OSScript"])
logging.info(" * Refresh value in sec = " + str(JSONValues["Refresh"]))
logging.info(" * Output = " + JSONValues["Output"])
# Storing results into FilebeatConfigsArray dictionnary
ConfigString = JSONValues["OSScript"] + ',' + str(JSONValues["Refresh"]) + ',' + JSONValues["Output"]
CustomMetricsConfigsArray[f_name] = ConfigString
except:
# If error, bypassing this plugin
# Log
logging.info(" ==> Error while loading " + f_name + " config file !")
logging.info(" Please check that target file is existing, JSON format and validity")
logging.info(str(traceback.print_exc()))
traceback.print_exc()
os._exit(2)
# Debug
# print('\nDEBUG\n')
# print('<!> DEBUG ', 'CustomMetricsConfigsArray[f_name]', CustomMetricsConfigsArray[f_name])
# print('<!> DEBUG ', 'f_name ', f_name)
# print('<!> DEBUG ', 'OSScript ', JSONValues["OSScript"])
# print('<!> DEBUG ', 'Refresh ', str(JSONValues["Refresh"]))
# print('\nFINDEBUG\n')
# All Custom Metric plugins loaded
# Log
logging.info(" ==> All Custom Metric plugin's config files loaded !")
# Loading PingPlotter plugin configs
# Log
logging.info(" Ping check:")
for ping_dest in PingPlotterTargets.split(','):
# Log
logging.info(" * " + ping_dest)
# Log
logging.info(" ==> All Ping Check destinations are loaded !")
pass
def GenerateEphemeralID():
""" Generate specific format of random number for ELK internal purpose.
Generating Ephemeral ID for current daemon execution
or new LPAR id file creation (random string format 8-4-4-4-12).
"""
# Generating Ephemeral ID
# IMPROVEMENT / urandom can be converted into python style
ShortRandom2 = subprocess.Popen("tr -dc a-z0-9 </dev/urandom | head -c 4", shell=True, stdout=subprocess.PIPE).stdout
ShortRandom2 = ShortRandom2.read().decode().replace("\n","")
ShortRandom1 = subprocess.Popen("tr -dc a-z0-9 </dev/urandom | head -c 4", shell=True, stdout=subprocess.PIPE).stdout
ShortRandom1 = ShortRandom1.read().decode().replace("\n","")
ShortRandom3 = subprocess.Popen("tr -dc a-z0-9 </dev/urandom | head -c 4", shell=True, stdout=subprocess.PIPE).stdout
ShortRandom3 = ShortRandom3.read().decode().replace("\n","")
MediumRandom = subprocess.Popen("tr -dc a-z0-9 </dev/urandom | head -c 8", shell=True, stdout=subprocess.PIPE).stdout
MediumRandom = MediumRandom.read().decode().replace("\n","")
LongRandom = subprocess.Popen("tr -dc a-z0-9 </dev/urandom | head -c 12", shell=True, stdout=subprocess.PIPE).stdout
LongRandom = LongRandom.read().decode().replace("\n","")
# Formating string
global EphemeralID
EphemeralID = MediumRandom + "-" + ShortRandom1 + "-" + ShortRandom2 + "-" + ShortRandom3 + "-" + LongRandom
def GetLPARInformations():
""" Get necessary LPAR informations.
All those values are used to format JSON messages sent to ELK.
FQDN:
Adding DNS suffix on hostname which doesn't have one.
LPARArch and AIXVersion:
Get LPAR AIX version and Power architecture (Power8/7/6+).
NetworkCards:
List of network cards is taken from "ifconfig -a" OS command.
FcCards:
List of Fiber Channel cards which are correctly connected and linked.
IDs:
LPARRndID is fixed across reboot. Defined one time if ID file does not exist.
AgentID is fixed across reboot. Defined one time if ID file does not exist.
EphemeralID is generated on each daemon execution and generated by 'GenerateEphemeralID' method.
NumProc:
Define the number of CPU threads available on LPAR.
"""
# Switching vars to global
global BaseDir
global LPARName
global LPARSMTMode
global LPARArch
global LPARHost
global AIXVersion
global LPARRndID
global AgentID
global NetworkCards
global FcCards
# FcCards list need to be formated before being used
FcCards = []
global NumProc
global NumProcString
global IfVIOS
global Tags
global Tagz
global Labels
# Checking if LPAR name contains DNS suffix. Adding if not
# Checking first if var FQDN is not null
if FQDN != "":
if not FQDN in LPARName:
LPARName = LPARName + FQDN
# Log
logging.info(" - Checking LPAR hostname... Done !")
# Get LPAR hardware architecture
CmdLine = "prtconf | egrep \"Processor Type|Serial Number\" | awk '{print $NF}'"
LPARPrtConf = subprocess.Popen(CmdLine, shell=True, stdout=subprocess.PIPE).stdout
LPARPrtConf = LPARPrtConf.read().decode().split('\n')
LPARArch = LPARPrtConf[1]
LPARHost = LPARPrtConf[0]
# Disabled for now as hosting frame has been moved to labels
# Tags.append(LPARHost)
# Tagz = Tagz + ',' + LPARHost
# Adding hosting frame to Labels list
LabelHostStr = 'powersn:' + str(LPARHost)
Labels.append(LabelHostStr)
# Log
logging.info(" - Checking LPAR Architecture... Done !")
# Get LPAR AIX OS Version
AIXVersion = subprocess.Popen("oslevel -s", shell=True, stdout=subprocess.PIPE).stdout
AIXVersion = AIXVersion.read().decode().replace("\n","")
# Checking if LPAR or VIOS
if os.path.exists("/usr/ios/cli/ioscli"):
IfVIOS = True
else:
IfVIOS = False
# Log
logging.info(" - Checking LPAR AIX version ... Done !")
# Get current SMT mode
LPARSMTModeCmdLine = "smtctl | grep has | awk '{print $3}' | head -1"
LPARSMTMode = subprocess.Popen(LPARSMTModeCmdLine, shell=True, stdout=subprocess.PIPE).stdout
LPARSMTMode = LPARSMTMode.read().decode().replace("\n","")
# Defining config path from ConfigFilePath
ConfigPathtmp = ConfigFilePath.split('/').pop()
ConfigPath = ConfigFilePath.replace(ConfigPathtmp,'')
# Defining LPAR ID file name
RandomIDFile = ConfigPath + 'Host.ID'
# If LPAR ID file exists, let's get content as defined scripts vars
if os.path.exists(RandomIDFile):
# Get LPAR Unique ID
# IMPROVEMENT / Can be converted into python style
LPARRndIDCmd = "cat " + RandomIDFile + " | grep LPARRndID | awk '{print $2}'"
LPARRndID = subprocess.Popen(LPARRndIDCmd, shell=True, stdout=subprocess.PIPE).stdout
LPARRndID = LPARRndID.read().decode().replace('\r','')
LPARRndID = LPARRndID.replace('\n','')
# Get LPAR ephemeral ID
# IMPROVEMENT / Can be converted into python style
AgentIDCmd = "cat " + RandomIDFile + " | grep AgentID | awk '{print $2}'"
AgentID = subprocess.Popen(AgentIDCmd, shell=True, stdout=subprocess.PIPE).stdout
AgentID = AgentID.read().decode().replace('\r','')
AgentID = AgentID.replace('\n','')
# If not, let's create it, fill it and define scripts vars
else:
# Generating LPAR ID in specific format
# IMPROVEMENT / Can be converted into python style
LPARRndID = subprocess.Popen("cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 32 | head -n 1", shell=True, stdout=subprocess.PIPE).stdout
LPARRndID = LPARRndID.read().decode().replace("\n","")
# Generating unique formated ID for uniqueAgent ID value
# as it is same format than ephemeral ID
GenerateEphemeralID()
AgentID = EphemeralID
# Creating the LPAR ID file
OpenedFile = open(RandomIDFile,"w+")
# Filling it with data
OpenedFile.write("LPARRndID ")
OpenedFile.write(LPARRndID)
OpenedFile.write("\r\n")
OpenedFile.write("AgentID ")
OpenedFile.write(AgentID)
OpenedFile.write("\r\n")
# Close the LPAR ID file
OpenedFile.close()
# Generating unique and ephemeral ID for current script execution
GenerateEphemeralID()
# Log
logging.info(" - Checking LPAR Metricbeat unique ID... Done !")
# Defining the name of network adapters
if EntRestricted == 'all':
# No restriction, taking all network adapters
NetworkCards = subprocess.Popen("ifconfig -a | grep ': ' | awk -F ':' '{print $1}' | grep -v 'lo0'", shell=True, stdout=subprocess.PIPE).stdout
NetworkCards = NetworkCards.read().decode().split('\n')
if IfVIOS:
# Detecting SEA adapters
NetworkCardsSEA = subprocess.Popen("lsdev -Cc adapter | grep 'Shared Ethernet Adapter' | awk '{print $1}'", shell=True, stdout=subprocess.PIPE).stdout
NetworkCardsSEA = NetworkCardsSEA.read().decode().split('\n')
# Adding SEA to the list of monitored adapters
NetworkCards = NetworkCards + NetworkCardsSEA
else:
# Restriction are specified. Setting Network card list to the given list
NetworkCards = []
NetworkCards = EntRestricted.split(',')
# Log
logging.info(" - Checking LPAR Network interface list ... Done !")
# Defining the name of FC adapters
if FcsRestricted == 'all':
FCCardsTemp = subprocess.Popen("lsdev -Cc adapter | grep fcs | awk '{print $1}'", shell=True, stdout=subprocess.PIPE).stdout
FCCardsTemp = FCCardsTemp.read().decode().split('\n')
else:
# Restriction are specified. Setting Network card list to the given list
FCCardsTemp = []
FCCardsTemp = FcsRestricted.split(',')
# Log
logging.info(" - Checking LPAR FC interface list ... Done !")
# Checking FC link status and exclude unlinked cards
for CurrLine in FCCardsTemp:
if(len(CurrLine) != 0):
FCCardFcStatCmd = "fcstat " + CurrLine
FCCardFcStatState = subprocess.Popen(FCCardFcStatCmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
stdout, stderr = FCCardFcStatState.communicate()
# If link is ok, adding the FC card into definitive array
if(FCCardFcStatState.returncode == 0):
FcCards.append(CurrLine)
# Log
logging.info(" - Checking LPAR FC link status... Done !")
# Defining number of CPU threads
NumProc = subprocess.Popen("bindprocessor -q | awk '{print $NF}'", shell=True, stdout=subprocess.PIPE).stdout
NumProc = NumProc.read().decode().split()
NumProc = int(NumProc[0]) + 1
NumProcString = str(NumProc)
# Log
logging.info(" - Checking LPAR CPU configuration... Done !")
# Generate fix JSON values for LPAR
GenerateStaticJSON()
def CompareTimer(TimedTopic, MetricsWaitValue, CustomMetric = ''):
""" This function compare the last execution time and the specific timer for an element.
If Timer is reached, the function return True and will trigger the underlying function.
- TimedTopic is the metric on which the timer needed to be checked
- MetricsWaitValue is the number of seconds to wait before work for metric is triggered
"""
# Using global ExecutionTimers dictionary for follow up purpose
global ExecutionTimers
global devnull
# Get current timestamp
CurrentTimer = datetime.datetime.now()
# Try/Catch to avoid errors on non defined dictionary entrie / First execution
try:
# Dictionary entrie is not empty
# Get last execution date/time
LastTopicExecTime = ExecutionTimers[TimedTopic]
# Comparing current and last execution date/time to get actual delay
TimerLatency = CurrentTimer - LastTopicExecTime
# Converting TimerLatency in seconds
TimerLatency = TimerLatency.total_seconds()
except:
# Dictionary entrie is empty
# We set TimerLatency very high (3600) to force the work for this first execution
TimerLatency = 3600
# Comparing last execution value with current timestamp
# and take decision to schedule the work or not
if TimerLatency > MetricsWaitValue:
ExecutionTimers[TimedTopic] = datetime.datetime.now()
# Log
LogString = "==> " + TimedTopic + " " + CustomMetric + " : New execution triggered ! (" + str(round(TimerLatency,2)) + " sec elapsed for " + str(MetricsWaitValue) + " seconds wait time)."
logging.info(LogString)
# print('YES ExecutionTimers[TimedTopic] and TimerLatency and MetricsWaitValue: ' + str(ExecutionTimers[TimedTopic]) + ' ' + str(round(TimerLatency,2)) + ' ' + str(MetricsWaitValue))
return str(TimerLatency).replace('.', '')
else:
RemainingTime = MetricsWaitValue - TimerLatency
# Log
LogString = " ! (" + str(round(RemainingTime,2)) + "/" + str(MetricsWaitValue) + " sec) " + TimedTopic + CustomMetric + " has NOT reached timer value."
logging.info(LogString)
# print('NO ExecutionTimers[TimedTopic] and TimerLatency and MetricsWaitValue: ' + str(ExecutionTimers[TimedTopic]) + ' ' + str(round(TimerLatency,2)) + ' ' + str(MetricsWaitValue))
return devnull
def ConvertFileName(FileName):
"""This function convert date time for easy use and tracking while making tail on log files
TODO: Describe the function, all vars and its content
"""
# Depending of the config file, TargetFile name may contain reference to date. Let's convert it !
# We will ad new conversion if required by users...
FileNameC = str(FileName.replace('%a', datetime.datetime.now().strftime("%a")))
FileNameC = FileNameC.replace('%A', datetime.datetime.now().strftime("%A"))
FileNameC = FileNameC.replace('%w', datetime.datetime.now().strftime("%w"))
FileNameC = FileNameC.replace('%d', datetime.datetime.now().strftime("%d"))
FileNameC = FileNameC.replace('%-d', datetime.datetime.now().strftime("%-d"))
FileNameC = FileNameC.replace('%b', datetime.datetime.now().strftime("%b"))
FileNameC = FileNameC.replace('%B', datetime.datetime.now().strftime("%B"))
FileNameC = FileNameC.replace('%m', datetime.datetime.now().strftime("%m"))
FileNameC = FileNameC.replace('%-m', datetime.datetime.now().strftime("%-m"))
FileNameC = FileNameC.replace('%y', datetime.datetime.now().strftime("%y"))
FileNameC = FileNameC.replace('%-y', datetime.datetime.now().strftime("%-y"))
FileNameC = FileNameC.replace('%Y', datetime.datetime.now().strftime("%Y"))
FileNameC = FileNameC.replace('%YY', datetime.datetime.now().strftime("%YY"))
FileNameC = FileNameC.replace('%H', datetime.datetime.now().strftime("%H"))
FileNameC = FileNameC.replace('%-H', datetime.datetime.now().strftime("%-H"))
FileNameC = FileNameC.replace('%I', datetime.datetime.now().strftime("%I"))
FileNameC = FileNameC.replace('%-I', datetime.datetime.now().strftime("%-I"))
FileNameC = FileNameC.replace('%p', datetime.datetime.now().strftime("%p"))
FileNameC = FileNameC.replace('%M', datetime.datetime.now().strftime("%M"))
FileNameC = FileNameC.replace('%-M', datetime.datetime.now().strftime("%-M"))
FileNameC = FileNameC.replace('%S', datetime.datetime.now().strftime("%S"))
FileNameC = FileNameC.replace('%-S', datetime.datetime.now().strftime("%-S"))
FileNameC = FileNameC.replace('%f', datetime.datetime.now().strftime("%f"))
FileNameC = FileNameC.replace('%z', datetime.datetime.now().strftime("%z"))
FileNameC = FileNameC.replace('%j', datetime.datetime.now().strftime("%j"))
FileNameC = FileNameC.replace('%-j', datetime.datetime.now().strftime("%-j"))
FileNameC = FileNameC.replace('%U', datetime.datetime.now().strftime("%U"))
FileNameC = FileNameC.replace('%W', datetime.datetime.now().strftime("%W"))
FileNameC = FileNameC.replace('%c', datetime.datetime.now().strftime("%c"))
FileNameC = FileNameC.replace('%x', datetime.datetime.now().strftime("%x"))
FileNameC = FileNameC.replace('%X', datetime.datetime.now().strftime("%X"))
FileNameC = FileNameC.replace('%%', datetime.datetime.now().strftime("%%"))
# Returning converted string
# print('\nconverted: ', FileNameC,'\n')
return FileNameC
def GenerateStaticJSON():
"""This function generate a static JSON message containing the pieces that will remain unchange until daemon restart
Please refer to README.md
TODO: Describe the function, all vars and its content
"""
global StaticJSON
global StaticJSONFilebeat
# Define tags for metricbeat
JSONTags=(''
'\"tags\": ' + str(Tags).replace('\'','"') + ','
'\"rollup\":{\"tagz\": \"' + str(Tagz) + '\",\"hostname\":\"' + LPARName + '\"},')
# Define rollup tags for filebeat (adding extra tagz and hostname field with rolled-up naming convention for easy use in dashboard)
JSONTagsFilebeat=(''
'\"tags\": ' + str(Tags).replace('\'','"') + ','
'\"rollup\":{\"tagz\":{\"terms\":{\"value\": \"' + str(Tagz) + '\"}},\"hostname\":{\"terms\":{\"value\": \"' + LPARName + '\"}}},')
# Define Agent JSON for metricbeat
JSONAgent = (''
'\"agent\":{'
'\"version\":\"' + ELKMonitoringVersion + '\",'
'\"type\":\"metricbeat\",'
'\"ephemeral_id\":\"' + EphemeralID + '\",'
'\"hostname\":\"' + LPARName + '\",'
'\"id\":\"' + AgentID + '\"'
'},')
# Define Agent JSON for filebeat
JSONAgentFilebeat = (''
'\"agent\":{'
'\"version\":\"' + ELKMonitoringVersion + '\",'
'\"type\":\"filebeat\",'
'\"ephemeral_id\":\"' + EphemeralID + '\",'
'\"hostname\":\"' + LPARName + '\",'
'\"id\":\"' + AgentID + '\"'
'},')
# Checking if LPAR is a VIOS
if IfVIOS:
OSFamily = 'VIOS'
else:
OSFamily = 'AIX'
# Define Host JSON for metricbeat
JSONHost = (''
'\"host\":{'
'\"name\":\"' + LPARName + '\",'
'\"hostname\":\"' + LPARName + '\",'
'\"architecture\":\"' + LPARArch + '\",'
'\"id\":\"' + LPARRndID + '\",'
'\"containerized\":false,'
'\"os\":{'
'\"platform\":\"AIX\",'
'\"version\":\"' + AIXVersion + '\",'
'\"family\":\"' + OSFamily + '\",'
'\"name\":\"AIX\",'
'\"kernel\":\"' + AIXVersion + '\",'
'\"codename\":\"AIX\"'
'}},')
# Define ECS JSON
JSONEcs = (''
'\"ecs\":{'
'\"version\":\"' + ECSVersion + '\"'
'},')
# Generating labels JSON with key/value pairs
LabelString = '\"labels\":{'
for Label in Labels:
if len(Label) != 0:
LabelString += '\"' + Label.replace(':','\":\"') + '\",'
LabelString = LabelString[:-1]
LabelString += '}'
StaticJSON = JSONTags + JSONAgent + JSONHost + JSONEcs + LabelString
StaticJSONFilebeat = JSONTagsFilebeat + JSONAgentFilebeat + JSONHost + JSONEcs + LabelString
# print(StaticJSON)
pass
def GenerateDynamicJson(EventDataset, ServiceType, MetricSet, ComparisonTimer):
"""This function generate a static JSON message containing the pieces that will change for each message
Please refer to README.md
TODO: Describe the function, all vars and its content
"""
JSONServiceType = (''
'\"service\":{'
'\"type\":\"' + ServiceType + '\"'
'},')
JSONEventDataset = (''
'\"event\":{'
'\"module\":\"' + ServiceType + '\",'
'\"duration\":' + ComparisonTimer + ','
'\"dataset\":\"' + EventDataset + '\"'
'},')
JSONMetricSet = (''
'\"metricset\":{'
'\"name\":\"' + MetricSet + '\",'
'\"period\":1'
'}')
DynamicJSON = JSONServiceType + JSONEventDataset + JSONMetricSet
return DynamicJSON
def CheckServers():
""" This function check the state of the Metricbeat Elasticsearch server.
It also handles the retransmit queues for Metricbeat and Filebeat items.
On each script loop execution, it will resend some queued messages up to a given number.
Please refer to README.md
TODO: Describe the function, all vars and its content
"""
# Setting global vars
global SendQueueArray
global FilebeatSendQueueArray
global LogstashSendQueueArray
global ELKUsername
global ELKPassword
global ElasticServers
global FilebeatServers
global LogstashServers
global ElasticPort
global FilebeatPort
global LogstashPort
global ELKCertificate
global ElasticServersAvailable
global ElasticServersFailed
global FilebeatServersAvailable
global FilebeatServersFailed
global LogstashServersAvailable
global LogstashServersFailed
global ElasticIndexName
global FilebeatIndexName
global ELKUsername
global ELKPassword
global ElasticServerCnx
global FilebeatServerCnx
global LogstashServerCnx
global AllElasticServersFailedDate
global AllFilebeatServersFailedDate
global AllLogstashServersFailedDate
global MetricbeatQueueFlushed
global FilebeatQueueFlushed
global LogstashQueueFlushed
global BulkMaxSize
# Checking for unavailable Elastic servers
if len(ElasticServersFailed) != 0:
# Choosing randomly one Elastic server in the failed pool
ElasticServer = random.choice(ElasticServersFailed)
# If ElasticServer server is unavailable, we send a get request
try:
# Defining URL and credentials for web request
ELKCreds = (ELKUsername, ELKPassword)
ElasticServerURL = ELKWebProtocol + '://' + ElasticServer + ':' + ElasticPort + '/'
# Connect and send encoded JSON message
ElasticServerCnx = requests.session()
ELKAnswer = ElasticServerCnx.get(ElasticServerURL, auth=ELKCreds, timeout=5, verify=ELKCertificate)
# If the response was successful, no Exception will be raised
ELKAnswer.raise_for_status()
except HTTPError as http_err:
# ELK server is still unavailable
# Log
logging.info("WARNING ==> " + ElasticServer + " is unavailable for Metricbeat messages")
# Creating the error stack file and filling error stack informations
# with open(CrashDumpCheckLog, 'a') as f:
# f.write('\n\n')
# f.write(str(datetime.datetime.now()))
# f.write(':\n')
# f.write(str(http_err))
# f.write(traceback.format_exc())
# f.write('\n')
# Print and log error stack for debug purpose
# logging.info('WARNING ==> Please check ' + CrashDumpCheckLog + ' for more informations on HTTP errors')
# traceback.print_exc()
except Exception as err:
# ELK server is still unavailable
# Log
logging.info("WARNING ==> " + ElasticServer + " is unavailable for Metricbeat messages")
# Creating the error stack file and filling error stack informations
# with open(CrashDumpCheckLog, 'a') as f:
# f.write('\n\n')
# f.write(str(datetime.datetime.now()))
# f.write(':\n')
# f.write(str(err))
# f.write(traceback.format_exc())
# f.write('\n')
# Print and log error stack for debug purpose
# logging.info('WARNING ==> Please check ' + CrashDumpCheckLog + ' for more informations on HTTP errors')
# traceback.print_exc()
else:
# ELK server is available, let's add it into the Available pool
# Into a try/catch because some background processes can modify these value
try:
ElasticServersFailed.remove(ElasticServer)
ElasticServersAvailable.append(ElasticServer)
logging.info("INFO ==> " + ElasticServer + " is Online ! Processing Metricbeat messages on this server")
except:
# Nothing to do
pass
# Checking for unavailable Filebeat servers
if len(FilebeatServersFailed) != 0:
# Choosing randomly one Filebeat server in the failed pool
FilebeatServer = random.choice(FilebeatServersFailed)
# If FilebeatServer server is unavailable, we send a get request
try:
# Defining URL and credentials for web request
ELKCreds = (ELKUsername, ELKPassword)
FilebeatServerURL = ELKWebProtocol + '://' + FilebeatServer + ':' + FilebeatPort + '/'