-
Notifications
You must be signed in to change notification settings - Fork 0
/
standalone-es-service-export.py
3319 lines (2705 loc) · 166 KB
/
standalone-es-service-export.py
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
import os
import requests
import time
from prometheus_client import start_http_server, Enum, Histogram, Counter, Summary, Gauge, CollectorRegistry
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from prometheus_client.core import (
GaugeMetricFamily,
CounterMetricFamily,
REGISTRY
)
import datetime, time
import json
import argparse
from threading import Thread
import logging
import socket
from config.log_config import create_log
import subprocess
import json
import copy
import jaydebeapi
import jpype
import re
from collections import defaultdict
# import paramiko
import base64
from dotenv import load_dotenv
import warnings
warnings.filterwarnings("ignore")
''' pip install python-dotenv'''
load_dotenv() # will search for .env file in local folder and load variables
# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
""" ---------------- """
""" Grafana Loki """
import logging
import logging_loki
logging_loki.emitter.LokiEmitter.level_tag = "level"
# assign to a variable named handler
handler = logging_loki.LokiHandler(
url="http://{}:3100/loki/api/v1/push".format(os.getenv("LOKI_HOST")),
version="1",
)
# create a new logger instance, name it whatever you want
logger = logging.getLogger("prometheus-logger")
logger.addHandler(handler)
""" ---------------- """
# Initialize & Inject with only one instance
logging = create_log()
hitl_server_health_status = Enum("hitl_server_health_status", "PSQL connection health", states=["healthy", "unhealthy"])
# kafka_broker_health_status = Enum("kafka_broker_health_status", "Kafka connection health", states=["green","yellow","red"])
hitl_server_health_request_time = Histogram('hitl_server_health_request_time', 'Server connection response time (seconds)')
kafka_brokers_gauge = Gauge("kafka_brokers", "the number of kafka brokers")
''' export application performance metric'''
es_service_jobs_performance_gauge_g = Gauge("es_service_jobs_performance_running_metrics", 'Metrics scraped from localhost', ["server_job"])
''' gauge with dict type'''
''' es_exporter_plugin'''
es_exporter_cpu_usage_gauge_g = Gauge("es_exporter_cpu_metrics", 'Metrics scraped from localhost', ["server_job", "type", "name", "cluster"])
es_exporter_jvm_usage_gauge_g = Gauge("es_exporter_jvm_metrics", 'Metrics scraped from localhost', ["server_job", "type", "name", "cluster"])
''' type : cluster/data_pipeline'''
all_envs_status_gauge_g = Gauge("all_envs_status_metric", 'Metrics scraped from localhost', ["server_job", "type"])
nodes_diskspace_gauge_g = Gauge("node_disk_space_metric", 'Metrics scraped from localhost', ["server_job", "category", "host", "name", "ip", "disktotal", "diskused", "diskavail", "diskusedpercent"])
nodes_free_diskspace_gauge_g = Gauge("node_free_disk_space_metric", 'Metrics scraped from localhost', ["server_job", "category", "name" ,"diskusedpercent"])
nodes_max_disk_used_gauge_g = Gauge("node_disk_used_metric", 'Metrics scraped from localhost', ["server_job", "category"])
es_nodes_gauge_g = Gauge("es_node_metric", 'Metrics scraped from localhost', ["server_job"])
es_nodes_basic_info_docs_gauge_g = Gauge("es_node_basic_docs_metric", 'Metrics scraped from localhost', ["server_job"])
es_nodes_basic_info_indices_gauge_g = Gauge("es_node_basic_indices_metric", 'Metrics scraped from localhost', ["server_job"])
es_nodes_health_gauge_g = Gauge("es_health_metric", 'Metrics scraped from localhost', ["server_job"])
kafka_nodes_gauge_g = Gauge("kafka_health_metric", 'Metrics scraped from localhost', ["server_job"])
kafka_connect_nodes_gauge_g = Gauge("kafka_connect_nodes_metric", 'Metrics scraped from localhost', ["server_job"])
kafka_connect_nodes_health_gauge_g = Gauge("kafka_connect_nodes_health_metric", 'Metrics scraped from localhost', ["server_job"])
kafka_connect_listeners_gauge_g = Gauge("kafka_connect_listeners_metric", 'Metrics scraped from localhost', ["server_job", "host", "name", "running"])
kafka_connect_health_gauge_g = Gauge("kafka_connect_health_metric", 'Metrics scraped from localhost', ["server_job"])
kafka_isr_list_gauge_g = Gauge("kafka_isr_list_metric", 'Metrics scraped from localhost', ["server_job", "topic", "partition", "leader", "replicas", "isr"])
zookeeper_nodes_gauge_g = Gauge("zookeeper_health_metric", 'Metrics scraped from localhost', ["server_job"])
spark_nodes_gauge_g = Gauge("spark_health_metric", 'Metrics scraped from localhost', ["server_job"])
kibana_instance_gauge_g = Gauge("kibana_health_metric", 'Metrics scraped from localhost', ["server_job"])
redis_instance_gauge_g = Gauge("redis_health_metric", 'Metrics scraped from localhost', ["server_job"])
es_configuration_instance_gauge_g = Gauge("es_configuration_writing_job_health_metric", 'Metrics scraped from localhost', ["server_job"])
es_configuration_api_instance_gauge_g = Gauge("es_configuration_api_health_metric", 'Metrics scraped from localhost', ["server_job"])
log_db_instance_gauge_g = Gauge("log_db_health_metric", 'Metrics scraped from localhost', ["server_job"])
alert_monitoring_ui_gauge_g = Gauge("alert_monitoring_ui_health_metric", 'Metrics scraped from localhost', ["server_job"])
loki_ui_gauge_g = Gauge("loki_ui_health_metric", 'Metrics scraped from localhost', ["server_job"])
loki_api_instance_gauge_g = Gauge("loki_api_health_metric", 'Metrics scraped from localhost', ["server_job"])
loki_agent_instance_gauge_g = Gauge("loki_agent_health_metric", 'Metrics scraped from localhost', ["server_job", "category"])
log_agent_instance_gauge_g = Gauge("log_agent_health_metric", 'Metrics scraped from localhost', ["server_job", "category"])
alert_state_instance_gauge_g = Gauge("alert_state_metric", 'Metrics scraped from localhost', ["server_job"])
logstash_instance_gauge_g = Gauge("logstash_health_metric", 'Metrics scraped from localhost', ["server_job"])
spark_jobs_gauge_g = Gauge("spark_jobs_running_metrics", 'Metrics scraped from localhost', ["server_job", "host", "id", "cores", "memoryperslave", "submitdate", "duration", "activeapps", "state"])
# db_jobs_gauge_g = Gauge("db_jobs_running_metrics", 'Metrics scraped from localhost', ["server_job", "processname", "cnt", "status", "addts", "dbid", "db_info"])
db_jobs_gauge_wmx_g = Gauge("db_jobs_wmx_running_metrics", 'Metrics scraped from localhost', ["server_job", "processname", "cnt", "status", "addts", "dbid", "db_info"])
db_jobs_gauge_kafka_offset_wmx_g = Gauge("db_jobs_wmx_kafka_offset_running_metrics", 'Metrics scraped from localhost', ["server_job", "topic", "partition_num", "offset", "addts", "addwho", "editts", "editwho", "dbid"])
db_jobs_gauge_omx_g = Gauge("db_jobs_omx_running_metrics", 'Metrics scraped from localhost', ["server_job", "processname", "cnt", "status", "addts", "dbid", "db_info"])
db_jobs_performance_WMx_gauge_g = Gauge("db_jobs_performance_running_metrics", 'Metrics scraped from localhost', ["server_job"])
db_jobs_performance_OMx_gauge_g = Gauge("db_jobs_performance2_running_metrics", 'Metrics scraped from localhost', ["server_job"])
''' export failure instance list metric'''
es_service_jobs_failure_gauge_g = Gauge("es_service_jobs_failure_running_metrics", 'Metrics scraped from localhost', ["server_job", "host", "reason"])
class oracle_database:
def __init__(self, db_url) -> None:
self.db_url = db_url
self.set_db_connection()
def set_init_JVM(self):
'''
Init JPYPE StartJVM
'''
if jpype.isJVMStarted():
return
jar = r'./ojdbc8.jar'
args = '-Djava.class.path=%s' % jar
# print('Python Version : ', sys.version)
# print('JAVA_HOME : ', os.environ["JAVA_HOME"])
# print('JDBC_Driver Path : ', JDBC_Driver)
# print('Jpype Default JVM Path : ', jpype.getDefaultJVMPath())
# jpype.startJVM("-Djava.class.path={}".format(JDBC_Driver))
jpype.startJVM(jpype.getDefaultJVMPath(), args, '-Xrs')
def set_init_JVM_shutdown(self):
jpype.shutdownJVM()
def set_db_connection(self):
''' DB Connect '''
print('connect-str : ', self.db_url)
StartTime = datetime.datetime.now()
# -- Init JVM
self.set_init_JVM()
# --
# - DB Connection
self.db_conn = jaydebeapi.connect("oracle.jdbc.driver.OracleDriver", self.db_url)
# --
EndTime = datetime.datetime.now()
Delay_Time = str((EndTime - StartTime).seconds) + '.' + str((EndTime - StartTime).microseconds).zfill(6)[:2]
print("# DB Connection Running Time - {}".format(str(Delay_Time)))
def set_db_disconnection(self):
''' DB Disconnect '''
self.db_conn.close()
print("Disconnected to Oracle database successfully!")
def get_db_connection(self):
return self.db_conn
def excute_oracle_query(self, sql):
'''
DB Oracle : Excute Query
'''
print('excute_oracle_query -> ', sql)
# Creating a cursor object
cursor = self.get_db_connection().cursor()
# Executing a query
cursor.execute(sql)
# Fetching the results
results = cursor.fetchall()
cols = list(zip(*cursor.description))[0]
# print(type(results), cols)
json_rows_list = []
for row in results:
# print(type(row), row)
json_rows_dict = {}
for i, row in enumerate(list(row)):
json_rows_dict.update({cols[i] : row})
json_rows_list.append(json_rows_dict)
cursor.close()
# logging.info(json_rows_list)
return json_rows_list
class ProcessHandler():
''' Get the process by the processname'''
def __init__(self) -> None:
pass
''' get ProcessID'''
def isProcessRunning(self, name):
''' Get PID with process name'''
try:
call = subprocess.check_output("pgrep -f '{}'".format(name), shell=True)
logging.info("Process IDs - {}".format(call.decode("utf-8")))
return True
except subprocess.CalledProcessError:
return False
''' get command result'''
def get_run_cmd_Running(self, cmd):
''' Get PID with process name'''
try:
logging.info("get_run_cmd_Running - {}".format(cmd))
call = subprocess.check_output("{}".format(cmd), shell=True)
output = call.decode("utf-8")
# logging.info("CMD - {}".format(output))
# logging.info(output.split("\n"))
output = [element for element in output.split("\n") if len(element) > 0]
return output
except subprocess.CalledProcessError:
return None
def transform_prometheus_txt_to_Json(response, metrics):
''' transform_prometheus_txt_to_Json '''
# filter_metrics_names = ['elasticsearch_process_cpu_percent', 'elasticsearch_jvm_memory_used_bytes']
body_list = [body for body in response.text.split("\n") if not "#" in body and len(body)>0]
'''
filterd_list = []
for each_body in body_list:
for filtered_metric in filter_metrics_names:
if filtered_metric in each_body:
filterd_list.append(str(each_body).replace(filtered_metric, ''))
'''
# logging.info(f"transform_prometheus_txt_to_Json - {body_list}")
prometheus_list_json = []
# loop = 0
for x in body_list:
json_key_pairs = x.split(" ")
# prometheus_json.update({json_key_pairs[0] : json_key_pairs[1]})
if metrics == 'es':
logging.info('es')
elif metrics == 'cpu_jvm':
if 'elasticsearch_process_cpu_percent' in json_key_pairs[0]:
json_key_pairs[0] = json_key_pairs[0].replace('elasticsearch_process_cpu_percent','')
extract_keys = json_key_pairs[0].replace("{","").replace("}","").replace("\"","").split(",")
json_keys_list = {each_key.split("=")[0] : each_key.split("=")[1] for each_key in extract_keys}
prometheus_list_json.append({'cluster' : json_keys_list.get('cluster'), 'name' : json_keys_list.get('name'), 'cpu_usage_percentage' : json_key_pairs[1], "category" : "cpu_usage"})
elif 'elasticsearch_jvm_memory_used_bytes' in json_key_pairs[0] and 'non-heap' not in json_key_pairs[0]:
json_key_pairs[0] = json_key_pairs[0].replace('elasticsearch_jvm_memory_used_bytes','')
extract_keys = json_key_pairs[0].replace("{","").replace("}","").replace("\"","").split(",")
json_keys_list = {each_key.split("=")[0] : each_key.split("=")[1] for each_key in extract_keys}
prometheus_list_json.append({'cluster' : json_keys_list.get('cluster'), 'name' : json_keys_list.get('name'), 'jvm_memory_used_bytes' : json_key_pairs[1], "category" : "jvm_memory_used_bytes"})
elif 'elasticsearch_jvm_memory_max_bytes' in json_key_pairs[0]:
json_key_pairs[0] = json_key_pairs[0].replace('elasticsearch_jvm_memory_max_bytes','')
extract_keys = json_key_pairs[0].replace("{","").replace("}","").replace("\"","").split(",")
json_keys_list = {each_key.split("=")[0] : each_key.split("=")[1] for each_key in extract_keys}
prometheus_list_json.append({'cluster' : json_keys_list.get('cluster'), 'name' : json_keys_list.get('name'), 'jvm_memory_max_bytes' : json_key_pairs[1], "category" : "jvm_memory_max_bytes"})
'''
[
{
"name": "logging-dev-node-4",
"cluster : "dev",
"cpu_usage_percentage": "4",
"category": "cpu_usage"
},
{
"name": "logging-dev-node-1",
"cluster : "dev",
"cpu_usage_percentage": "2",
"category": "cpu_usage"
},
{
"name": "logging-dev-node-2",
"cluster : "dev",
"cpu_usage_percentage": "8",
"category": "cpu_usage"
},
{
"name": "logging-dev-node-3",
"cluster : "dev",
"cpu_usage_percentage": "4",
"category": "cpu_usage"
}
]
'''
print(json.dumps(prometheus_list_json, indent=2))
return prometheus_list_json
''' save failure nodes into dict'''
saved_failure_dict, saved_failure_tasks_dict = {}, {}
''' expose this metric to see maximu disk space among ES/Kafka nodes'''
max_disk_used, max_es_disk_used, max_kafka_disk_used = 0, 0, 0
each_es_instance_cpu_history, each_es_instance_jvm_history = {}, {}
def get_metrics_all_envs(monitoring_metrics):
''' get metrics from custom export for the health of kafka cluster'''
global saved_failure_dict, max_disk_used, max_es_disk_used, max_kafka_disk_used
global each_es_instance_cpu_history, each_es_instance_jvm_history
global service_status_dict
global is_dev_mode
''' initialize global variables '''
max_disk_used, max_es_disk_used, max_kafka_disk_used = 0, 0, 0
def get_service_port_alive(monitoring_metrics):
''' get_service_port_alive'''
'''
socket.connect_ex( <address> ) similar to the connect() method but returns an error indicator of raising an exception for errors returned by C-level connect() call.
Other errors like host not found can still raise exception though
'''
response_dict = {}
for k, v in monitoring_metrics.items():
response_dict.update({k : ""})
response_sub_dict = {}
url_lists = v.split(",")
# logging.info("url_lists : {}".format(url_lists))
totalcount = 0
for idx, each_host in enumerate(url_lists):
each_urls = each_host.split(":")
# logging.info("urls with port : {}".format(each_urls))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((each_urls[0],int(each_urls[1])))
if result == 0:
# print("Port is open")
totalcount +=1
response_sub_dict.update({each_urls[0] + ":" + each_urls[1] : "OK"})
response_sub_dict.update({"GREEN_CNT" : totalcount})
else:
# print("Port is not open")
response_sub_dict.update({each_urls[0] + ":" + each_urls[1] : "FAIL"})
response_sub_dict.update({"GREEN_CNT" : totalcount})
''' save failure node with a reason into saved_failure_dict'''
if 'redis' not in str(k) and 'configuration' not in str(k) and 'loki_custom_promtail_agent_url' not in str(k) and 'log_aggregation_agent_url' not in str(k):
saved_failure_dict.update({each_urls[0] : "[Node #{}-{}] ".format(idx+1, str(k).upper()) + each_host + " Port closed"})
sock.close()
response_dict.update({k : response_sub_dict})
# logging.info(json.dumps(response_dict, indent=2))
logging.info(response_dict)
return response_dict
def get_kafka_connector_listeners(node_list_str):
''' get the state of each node's listener'''
''' 1) http://localhost:8083/connectors/ -> ["test_api",..]'''
'''
2) http://localhost:8083/connectors/test_api/status
->
"localhost" : [
{
"name": "test_api",
"connector": {
"state": "RUNNING",
"worker_id": "127.0.0.1:8083"
},
"tasks": [
{
"state": "RUNNING",
"id": 0,
"worker_id": "127.0.0.1:8083"
}
]
}
]
'''
global saved_failure_tasks_dict
''' clear '''
saved_failure_tasks_dict.clear()
try:
if not node_list_str:
return None, False
logging.info(f"get_kafka_connector_listeners - {node_list_str}")
master_node = node_list_str.split(",")[0].split(":")[0]
logging.info(f"get_kafka_connector_listeners #1- {master_node}")
node_hosts = node_list_str.split(",")
nodes_list = [node.split(":")[0] for node in node_hosts]
active_listner_list = {}
active_listner_connect = []
for each_node in nodes_list:
try:
# -- make a call to master node to get the information of activeapps
logging.info(each_node)
resp = requests.get(url="http://{}:8083/connectors".format(each_node), timeout=5, verify=False)
# logging.info(f"activeapps - {resp}, {resp.status_code}, {resp.json()}")
logging.info(f"activeconnectors/listeners - {resp}, {resp.status_code}")
if not (resp.status_code == 200):
continue
else:
# active_listner_connect.update({each_node : resp.json()})
active_listner_connect = resp.json()
break
except Exception as e:
pass
logging.info(f"active_listener_list - {json.dumps(active_listner_connect, indent=2)}")
''' add tracking logs and save failure node with a reason into saved_failure_dict'''
if not active_listner_connect:
saved_failure_dict.update({",".join(nodes_list): "http://{}:8083/connectors API do not reachable".format(nodes_list)})
return None, False
'''
# Master node
# -- make a call to master node to get the information of activeapps
resp = requests.get(url="http://{}:8083/connectors".format(master_node), timeout=5)
if not (resp.status_code == 200):
return None
else:
# logging.info("OK~@#")
active_listner_connect.update({master_node : resp.json()})
logging.info(f"active_listner_connect #1 - {json.dumps(active_listner_connect.get(master_node), indent=2)}")
'''
#-- with listeners_list
listener_apis_dict = {}
failure_check = False
all_listeners_is_empty = []
node_lists_loop = 0
for node in nodes_list:
listener_apis_dict.update({node : {}})
listeners_list = []
loop = 1
for listener in active_listner_connect:
try:
# loop +=1
"""
resp_each_listener = requests.get(url="http://{}:8083/connectors/{}".format(node, listener), timeout=5)
# logging.info(f"len(resp_each_listener['tasks']) - {node} -> { len(list(resp_each_listener.json()['tasks']))}")
''' If the “task” details are missing from the listener, then we probably are not processing data.'''
if len(list(resp_each_listener.json()["tasks"])) > 0:
# logging.info(f"listener_apis_dict make a call - {node} -> {listener}")
resp_listener = requests.get(url="http://{}:8083/connectors/{}/status".format(node, listener), timeout=5)
# logging.info(f"listeners - {resp_listener}, {resp_listener.json()}")
listeners_list.append(resp_listener.json())
else:
''' save failure node with a reason into saved_failure_dict'''
saved_failure_dict.update({"{}_{}".format(node, str(loop)) : "http://{}:8083/connectors/{} tasks are missing".format(node, listener)})
"""
resp_tasks = requests.get(url="http://{}:8083/connectors/{}".format(node, listener), timeout=5, verify=False)
if not (resp_tasks.status_code == 200):
continue
logging.info(f"get_kafka_connector_listeners [tasks] : {resp_tasks.json().get('tasks')}")
if len(list(resp_tasks.json().get('tasks'))) < 1:
''' save failure node with a reason into saved_failure_dict'''
logging.info(f"no [tasks] : {resp_tasks.json().get('tasks')}")
''' It works find if the status of listeners in base node is green'''
if node_lists_loop == 0:
saved_failure_dict.update({"{}_{}".format(node, str(loop)) : "http://{}:8083/connectors/{} tasks are missing".format(node, listener)})
else:
''' Except from audit message'''
saved_failure_tasks_dict.update({"{}_{}".format(node, str(loop)) : "http://{}:8083/connectors/{} tasks are missing".format(node, listener)})
''' tasks are empty on only base node'''
if node_lists_loop == 0:
all_listeners_is_empty.append(True)
continue
else:
''' tasks are empty on only base node'''
if node_lists_loop == 0:
all_listeners_is_empty.append(False)
resp_listener = requests.get(url="http://{}:8083/connectors/{}/status".format(node, listener), timeout=5, verify=False)
listeners_list.append(resp_listener.json())
loop +=1
except Exception as e:
''' save failure node with a reason into saved_failure_dict'''
saved_failure_dict.update({"{}_{}".format(node, str(loop)) : "http://{}:8083/connectors/[listeners]/status json API do not reachable".format(node, listener)})
# saved_failure_dict.update({"{}_{}".format(node, str(loop)) : "http://{}:8083/connectors/{}/status json API do not reachable".format(node, listener)})
# saved_failure_dict.update({"{}_{}".format(node, str(loop)) : "http://{}:8083/connectors/{}/status API{}".format(node, listener, str(e))})
''' master kafka connect is runnning correctly, it doesn't matter'''
if loop > 1:
failure_check = True
# failure_check = True
pass
listener_apis_dict.update({node : listeners_list})
node_lists_loop +=1
# logging.info(f"listener_apis_dict - {json.dumps(listener_apis_dict, indent=2)}")
logging.info(f"listener_apis_dict - {listener_apis_dict}")
''' result '''
'''
{
"localhost1": [{
"test_jdbc": {
"name": "test_jdbc",
"connector": {
"state": "RUNNING",
"worker_id": "localhost:8083"
},
"tasks": [
{
"state": "RUNNING",
"id": 0,
"worker_id": "localhost:8083"
}
]
}
},
"localhost2": {},
"localhost3": {}
}]
'''
failure_check = all(all_listeners_is_empty) or failure_check
# failure_check = all(all_listeners_is_empty)
return listener_apis_dict, failure_check
except Exception as e:
logging.error(e)
def get_spark_jobs(node):
''' get_spark_jobs '''
''' get_spark_jobs - localhost:9092,localhost:9092,localhost:9092 '''
''' first node of --kafka_url argument is a master node to get the number of jobs using http://localhost:8080/json '''
try:
''' clear spark nodes health'''
spark_nodes_gauge_g.clear()
if not node:
return None
logging.info(f"get_spark_jobs - {node}")
master_node = node.split(",")[0].split(":")[0]
logging.info(f"get_spark_jobs #1- {master_node}")
# -- make a call to master node to get the information of activeapps
resp = requests.get(url="http://{}:8080/json".format(master_node), timeout=60, verify=False)
logging.info(f"get_spark_jobs - response {resp.status_code}")
if not (resp.status_code == 200):
spark_nodes_gauge_g.labels(server_job=socket.gethostname()).set(0)
saved_failure_dict.update({node : "Spark cluster - http://{}:8080/json API do not reachable".format(master_node)})
return None
''' expose metrics spark node health is active'''
spark_nodes_gauge_g.labels(server_job=socket.gethostname()).set(1)
# logging.info(f"activeapps - {resp}, {resp.json()}")
resp_working_job = resp.json().get("activeapps", "")
# response_activeapps = []
if resp_working_job:
logging.info(f"activeapps - {resp_working_job}")
if len(resp_working_job) < 1:
saved_failure_dict.update({"{}:8080".format(master_node) : "Spark cluster - No Spark Custom Apps".format(master_node)})
logging.info(f"get_active_jobs [Yes] {resp_working_job}")
return resp_working_job
else:
logging.info(f"get_active_jobs [No] {resp_working_job}")
saved_failure_dict.update({"{}:8080".format(master_node) : "Spark cluster - http://{}:8080/json, no active jobs. Please run 'Spark Custom Apps'".format(master_node)})
# return resp.json().get("completedapps", "")
return []
except Exception as e:
''' add tracking logs and save failure node with a reason into saved_failure_dict'''
saved_failure_dict.update({node : "Spark cluster - http://{}:8080/json API do not reachable".format(master_node)})
logging.error(e)
return []
def get_Process_Id():
''' get_Process_Id'''
process_name = "/logstash-"
process_handler = ProcessHandler()
logging.info("Prcess - {}".format(process_handler.isProcessRunning(process_name)))
if process_handler.isProcessRunning(process_name):
return 1
''' save failure node with a reason into saved_failure_dict'''
saved_failure_dict.update({socket.gethostname() : "Logstash is not running.."})
return 0
def get_header():
''' get header for security pack'''
header = {
'Content-type': 'application/json',
'Authorization' : '{}'.format(os.getenv('BASIC_AUTH')),
'Connection': 'close'
}
return header
def get_elasticsearch_health(monitoring_metrics):
''' get cluster health with basic infomration such as the number of docs'''
''' return health json if one of nodes in cluster is acitve'''
def get_unassigned_shards_lookup(es_cluster_call_protocal, each_es_host):
"""
https://www.elastic.co/guide/en/elasticsearch/reference/current/diagnose-unassigned-shards.html
http://localhost:9200/_cat/shards?format=json&v=true&h=index,shard,prirep,state,node,unassigned.reason&s=state
[
{
"index": "test_reindex_wx_order_02072022_22_2_1",
"shard": "0",
"prirep": "r",
"state": "UNASSIGNED",
"node": null,
"unassigned.reason": "REPLICA_ADDED"
},
{
"index": "test_reindex_wx_order_02072022_22_2_1",
"shard": "3",
"prirep": "r",
"state": "INITIALIZING",
"node": "supplychain-logging-dev-node-2",
"unassigned.reason": "REPLICA_ADDED"
},
]
"""
try:
# -- make a call to cluster for checking the disk space on all nodes in the cluster
resp = requests.get(url="{}://{}/_cat/shards?format=json&v=true&h=index,shard,prirep,state,node,unassigned.reason&s=state".format(es_cluster_call_protocal, each_es_host), headers=get_header(), verify=False, timeout=5)
if not (resp.status_code == 200):
''' save failure node with a reason into saved_failure_dict'''
# saved_failure_dict.update({each_es_host.split(":")[0] : each_es_host + " Port closed"})
return None
''' Saved Gauge metrics'''
logging.info(f"# get_unassigned_shards_lookup")
unassgned_indics_list = []
for each_json in resp.json():
if "UNASSIGNED" == str(each_json.get("state")).upper():
if each_json.get("index") not in unassgned_indics_list:
unassgned_indics_list.append(each_json.get("index"))
logging.info(f"UNASSGNED SHARDS INDEX : {unassgned_indics_list}")
return unassgned_indics_list
except Exception as e:
logging.error(e)
pass
def retry_set_unassigned_shard(es_cluster_call_protocal, each_es_host, unassign_index_list):
"""
https://www.elastic.co/guide/en/elasticsearch/reference/current/diagnose-unassigned-shards.html
http://localhost:9200/_cat/shards?format=json&v=true&h=index,shard,prirep,state,node,unassigned.reason&s=state
-- reset the numer of replicas to 0 and retry set to 1
PUT test/_settings
{
"number_of_replicas": 0 --> "number_of_replicas": 1
}
"""
NUMBER_OF_REPLICAS = [0, 1]
for unassgned_indic in unassign_index_list:
try:
logging.info(f"UNASSGNED SHARDS INDEX [RESET REPLICAS]: {unassgned_indic}")
for number_of_replicas in NUMBER_OF_REPLICAS:
# -- make a call to cluster
payload = {
"number_of_replicas": int(number_of_replicas)
}
resp = requests.put(url="{}://{}/{}/_settings".format(es_cluster_call_protocal, each_es_host, unassgned_indic), headers=get_header(), json=payload, verify=False, timeout=5)
logging.info(f"# set_unassigned_shard : {es_cluster_call_protocal}://{each_es_host}/{unassgned_indic}/_settings")
if not (resp.status_code == 200):
''' save failure node with a reason into saved_failure_dict'''
# saved_failure_dict.update({each_es_host.split(":")[0] : each_es_host + " Port closed"})
logging.info(f"# set_unassigned_shard not 200 STATUS CODE")
logging.info(f"{resp.json()}")
return None
logging.info(resp.status_code, resp.json())
except Exception as e:
logging.error(e)
pass
try:
es_url_hosts = monitoring_metrics.get("es_url", "")
logging.info(f"get_elasticsearch_health hosts - {es_url_hosts}")
es_url_hosts_list = es_url_hosts.split(",")
''' default ES configuration API'''
es_cluster_call_protocal, disk_usage_threshold_es_config_api = get_es_configuration_api()
global global_es_shards_tasks_end_occurs_unassgined
for each_es_host in es_url_hosts_list:
es_basic_info = {}
try:
# -- make a call to node
''' export es metrics from ES cluster with Search Guard'''
resp = requests.get(url="{}://{}/_cluster/health".format(es_cluster_call_protocal, each_es_host), headers=get_header(), timeout=5, verify=False)
if not (resp.status_code == 200):
''' save failure node with a reason into saved_failure_dict'''
# saved_failure_dict.update({each_es_host.split(":")[0] : each_es_host + " Port closed"})
continue
logging.info(f"activeES - {resp}, {resp.json()}")
''' log if one of ES nodes goes down'''
if int(resp.json().get("relocating_shards")) > 0 or int(resp.json().get("initializing_shards")) > 0 or int(resp.json().get("unassigned_shards")) > 0:
saved_failure_dict.update({"{}_1".format(socket.gethostname()) : "[Elasticsearch] {} relocating_shards, {} unassigned shards, {} initializing shards".format(
resp.json().get("relocating_shards"),
resp.json().get("unassigned_shards"),
resp.json().get("initializing_shards"))
}
)
''' update status for the number of replicas'''
if int(resp.json().get("relocating_shards")) == 0 and int(resp.json().get("initializing_shards")) == 0:
''' still ES cluster has unassgned shards'''
if int(resp.json().get("unassigned_shards")) > 0:
if int(resp.json().get("number_of_nodes")) == len(es_url_hosts_list):
global_es_shards_tasks_end_occurs_unassgined = True
''' nedd to update '''
"""
PUT test/_settings
{
"number_of_replicas": 0 --> "number_of_replicas": 1
}
"""
unassgned_indics_list = get_unassigned_shards_lookup(es_cluster_call_protocal, each_es_host)
''' Insrted log'''
inserted_post_log(status="ES_RESET_REPLICA", message="[ES] Reset the number of replica to INDEX [{}]".format(",".join(unassgned_indics_list)))
''' PUT the number of replicas to 0 and set it back to 1'''
# retry_set_unassigned_shard(es_cluster_call_protocal, each_es_host, unassgned_indics_list)
''' update the message for the failed a list of index name'''
saved_failure_dict.update({"{}_2".format(socket.gethostname()) : "[Elasticsearch] Reset the number of replica to INDEX ['{}']".format(",".join(unassgned_indics_list))})
else:
global_es_shards_tasks_end_occurs_unassgined = False
else:
global_es_shards_tasks_end_occurs_unassgined = False
''' Call to get more information '''
resp_info = requests.get(url="{}://{}/_cat/indices?format=json".format(es_cluster_call_protocal, each_es_host), headers=get_header(), timeout=5, verify=False)
'''
[
{
"health": "green",
"status": "open",
"index": "wx_mbol_10052020_20_6_1",
"uuid": "2goOnXUpQNmV_w0WWKtg4w",
"pri": "5",
"rep": "1",
"docs.count": "172220",
"docs.deleted": "0",
"store.size": "228.2mb",
"pri.store.size": "117.8mb",
"dataset.size": "117.8mb"
},
...
]
'''
# logging.info(f"resp_basic_info - {resp_info}, {resp_info.json()}")
total_docs, total_indices = 0, 0
for each_json_info in list(resp_info.json()):
total_docs += int(each_json_info.get("docs.count"))
total_indices += 1
es_basic_info.update({"docs" : total_docs, "indices" : total_indices})
return resp.json(), es_basic_info
except Exception as e:
pass
return None, None
except Exception as e:
logging.error(e)
pass
def get_float_number(s):
''' get float/numbder from string'''
p = re.compile("\d*\.?\d+")
return float(''.join(p.findall(s)))
def get_es_configuration_api():
''' default ES configuration API'''
# logging.info(f"global configuration : {json.dumps(gloabl_configuration, indent=2)}")
disk_usage_threshold_es_config_api = 90
if gloabl_configuration:
disk_usage_threshold_es_config_api = gloabl_configuration.get("config").get("disk_usage_percentage_threshold")
logging.info(f"global configuration [disk_usage_threshold as default] : {disk_usage_threshold_es_config_api}")
''' default ES configuration API'''
es_cluster_call_protocal = "http"
if gloabl_configuration:
if gloabl_configuration.get("config").get("es_cluster_call_protocol_https"):
es_https_list = gloabl_configuration.get("config").get("es_cluster_call_protocol_https").split(",")
logging.info(f"socket.gethostname().split('.')[0] : {socket.gethostname().split('.')[0]}")
logging.info(f"es_https_list : {es_https_list}")
if socket.gethostname().split(".")[0] in es_https_list:
es_cluster_call_protocal = "https"
logging.info(f"global configuration [es_cluster_call_protocol as default] : {es_cluster_call_protocal}")
return es_cluster_call_protocal, disk_usage_threshold_es_config_api
def get_elasticsearch_disk_audit_alert(monitoring_metrics):
''' get nodes health/check the some metrics for delivering audit alert via email '''
''' https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-nodes.html'''
try:
global max_disk_used, max_es_disk_used
es_url_hosts = monitoring_metrics.get("es_url", "")
logging.info(f"get_elasticsearch_audit_alert hosts - {es_url_hosts}")
es_url_hosts_list = es_url_hosts.split(",")
''' default ES configuration API'''
es_cluster_call_protocal, disk_usage_threshold_es_config_api = get_es_configuration_api()
logging.info(f"get_elasticsearch_disk_audit_alert : es_cluster_call_protocal - {es_cluster_call_protocal}")
''' get hostname without domain'''
hostname = socket.gethostname().split(".")[0]
for each_es_host in es_url_hosts_list:
try:
# -- make a call to cluster for checking the disk space on all nodes in the cluster
resp = requests.get(url="{}://{}/_cat/nodes?format=json&h=name,ip,h,diskTotal,diskUsed,diskAvail,diskUsedPercent".format(es_cluster_call_protocal, each_es_host), headers=get_header(), verify=False, timeout=5)
if not (resp.status_code == 200):
''' save failure node with a reason into saved_failure_dict'''
# saved_failure_dict.update({each_es_host.split(":")[0] : each_es_host + " Port closed"})
continue
logging.info(f"get_elasticsearch_disk_audit_alert - {resp}, {resp.json()}")
''' Saved Gauge metrics'''
logging.info(f"# Metrics Check for ES Disk")
loop = 1
''' expose this varible to Server Active'''
is_over_free_Disk_space = False
for element_dict in resp.json():
for k, v in element_dict.items():
# logging.info(f"# k - {k}, # v for ES - {v}")
nodes_free_diskspace_gauge_g.labels(server_job=socket.gethostname(), category="Elastic Node", name=element_dict.get("name",""), diskusedpercent=element_dict.get("diskUsedPercent","")+"%").set(element_dict.get("diskUsedPercent",""))
''' disk usages is greater than 90%'''
# if float(element_dict.get("diskUsedPercent","-1")) >= int(os.environ["NODES_DISK_AVAILABLE_THRESHOLD"]):
''' just None for host name if app doesn't have host name from es-configuration api'''
if hostname not in gloabl_configuration.keys():
get_host_name = None
else:
get_host_name = gloabl_configuration.get(hostname).get(element_dict.get("name"))
if float(element_dict.get("diskUsedPercent","-1")) >= int(disk_usage_threshold_es_config_api):
nodes_diskspace_gauge_g.labels(server_job=socket.gethostname(), category="Elastic Node", host="{}{}".format(str(global_env_name).lower(), get_host_name), name=element_dict.get("name",""), ip=element_dict.get("ip",""), disktotal=element_dict.get("diskTotal",""), diskused=element_dict.get("diskUsed",""), diskavail=element_dict.get("diskAvail",""), diskusedpercent=element_dict.get("diskUsedPercent","")+"%").set(0)
else:
nodes_diskspace_gauge_g.labels(server_job=socket.gethostname(), category="Elastic Node", host="{}{}".format(str(global_env_name).lower(), get_host_name), name=element_dict.get("name",""), ip=element_dict.get("ip",""), disktotal=element_dict.get("diskTotal",""), diskused=element_dict.get("diskUsed",""), diskavail=element_dict.get("diskAvail",""), diskusedpercent=element_dict.get("diskUsedPercent","")+"%").set(1)
if k == "diskUsedPercent":
logging.info(f"ES Disk Used : {get_float_number(v)}")
if max_disk_used < get_float_number(v):
max_disk_used = get_float_number(v)
if max_es_disk_used < get_float_number(v):
max_es_disk_used = get_float_number(v)
# if get_float_number(v) >= int(os.environ["NODES_DISK_AVAILABLE_THRESHOLD"]):
if get_float_number(v) >= int(disk_usage_threshold_es_config_api):
''' save failure node with a reason into saved_failure_dict'''
saved_failure_dict.update({"{}_{}".format(each_es_host.split(":")[0], str(loop)) : "[host : {}, name : {}]".format(each_es_host.split(":")[0], element_dict.get("name","")) + " Disk Used : " + element_dict.get("diskUsedPercent","") + "%" + ", Disk Threshold : " + str(disk_usage_threshold_es_config_api) + "%" })
is_over_free_Disk_space = True
loop += 1
return is_over_free_Disk_space
except Exception as e:
logging.error(e)
pass
except Exception as e:
logging.error(e)
disk_space_memory_list = []
def get_kafka_disk_audit_alert(monitoring_metrics):
''' get kafka nodes' disk space for delivering audit alert via email '''
''' du -hs */ | sort -n | head '''
"""
def ssh_connection(host, username, password, path, host_number):
try:
global disk_space_list
client = paramiko.client.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, password=base64.b64decode(password))
print(f"create new session ssh..")
''' excute command line'''
_stdin, _stdout,_stderr = client.exec_command("df -h {}".format(path))
response = _stdout.read().decode()
# print("cmd : ", response, type(response))
# print('split#1 ', str(response.split('\n')[1]))
disk_space_list = [element for element in str(response.split('\n')[1]).split(' ') if len(element) > 0]
# print('split#2 ', disk_space_list)
# logging.info(f"Success : {host}")
disk_space_dict = {}
''' split#2 disk_space_list - > ['/dev/mapper/software-Vsfw', '100G', '17G', '84G', '17%', '/apps'] '''
disk_space_dict.update({
"host" : host,
"name" : "supplychain-logging-kafka-node-{}".format(host_number),
"diskTotal" : disk_space_list[1],
"diskused" : disk_space_list[2],
"diskAvail" : disk_space_list[3],
"diskUsedPercent" : disk_space_list[4].replace('%',''),
"folder" : disk_space_list[5]
}
)
disk_space_memory_list.append(disk_space_dict)
except Exception as error:
logging.error(f"Failed : {host}")
finally:
client.close()
print(f"close session ssh..")
"""
def socket_connection(host, path, host_number):
''' gather metrics from Kafka each node'''
global disk_space_list
# Create a connection to the server application on port 81
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, 1234))
try:
data = str.encode(path)
client_socket.sendall(data)
received = client_socket.recv(1024)
print(f"# socket client received.. {received}")
disk_space_list = [element for element in str(received.decode('utf-8').split('\n')[1]).split(' ') if len(element) > 0]
# print('split#2 ', disk_space_list)
# logging.info(f"Success : {host}")
disk_space_dict = {}
''' split#2 disk_space_list - > ['/dev/mapper/software-Vsfw', '100G', '17G', '84G', '17%', '/apps'] '''