-
Notifications
You must be signed in to change notification settings - Fork 17
/
monitofi.py
executable file
·162 lines (135 loc) · 5.64 KB
/
monitofi.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
# // Copyright (c) Microsoft Corporation.
# // Licensed under the MIT license.
import logging
import time
import sys
import os
import urllib3
import requests
import json
import json_log_formatter
from requests_pkcs12 import get, post
from applicationinsights.logging import LoggingHandler
from applicationinsights.exceptions import enable
from influxdb import InfluxDBClient
from datetime import datetime
API_URL = os.getenv('API_URL', "http://localhost:8080/nifi-api/").split(',') # Comma separated list of nifi cluster api urls in case of multiple clusters.
ENDPOINT_LIST = os.getenv('ENDPOINT_LIST', "controller/cluster,flow/cluster/summary,flow/process-groups/root,flow/status,counters,system-diagnostics?nodewise=true").split(',')
MODE = os.getenv('MODE', "unlimited") # In limited mode, only NUMBEROFITERATIONS API calls are made before exiting.
NUMBER_OF_ITERATIONS = int(os.getenv('NUMBER_OF_ITERATIONS', 2))
IKEY = os.getenv('IKEY', "REPLACE_ME")
SLEEP_INTERVAL = int(os.getenv('SLEEP_INTERVAL', 300))
SECURE = os.getenv('SECURE', False) # Is NiFi Cluster Secure
CERT_FILE = os.getenv('CERT_FILE', '/opt/monitofi/cert.pkcs12')
CERT_PASS = os.getenv('CERT_PASS', 'REPLACE_ME')
INFLUXDB_SERVER = os.getenv('INFLUXDB_SERVER', "127.0.0.1") # IP or hostname to InfluxDB server
INFLUXDB_PORT = int(os.getenv('INFLUXDB_PORT', 8086)) # Port on InfluxDB server
INFLUXDB_USERNAME = os.getenv('INFLUXDB_USERNAME', "root")
INFLUXDB_PASSWORD = os.getenv('INFLUXDB_PASSWORD', "root")
INFLUXDB_DATABASE = os.getenv('INFLUXDB_DATABASE', "nifi")
count = 0
urllib3.disable_warnings()
conditions = {
"limited": lambda: count < NUMBER_OF_ITERATIONS,
"unlimited": lambda: True
}
# Sysout Logging Setup
logger = logging.getLogger("monitofi")
logger.setLevel(logging.INFO)
syshandler = logging.StreamHandler(sys.stdout)
syshandler.setLevel(logging.INFO)
formatter = json_log_formatter.JSONFormatter()
syshandler.setFormatter(formatter)
logger.addHandler(syshandler)
if IKEY != "REPLACE_ME":
# Logging unhandled exceptions with Appinsights
enable(IKEY)
# Applications Insights Logging Setup
handler = LoggingHandler(IKEY)
handler.setFormatter(formatter)
logger.addHandler(handler)
iclient = InfluxDBClient(INFLUXDB_SERVER, INFLUXDB_PORT, INFLUXDB_USERNAME, INFLUXDB_PASSWORD, INFLUXDB_DATABASE)
iclient.create_database(INFLUXDB_DATABASE)
def flattening(nested, prefix, ignore_list):
field = {}
flatten(True, nested, field, prefix, ignore_list)
return field
def flatten(top, nested, flatdict, prefix, ignore_list):
def assign(newKey, data, toignore):
if toignore:
if isinstance(data, (dict, list, tuple,)):
json_data = json.dumps(data)
flatdict[newKey] = json_data
else:
flatdict[newKey] = data
else:
if isinstance(data, (dict, list, tuple,)):
flatten(False, data, flatdict, newKey, ignore_list)
else:
flatdict[newKey] = data
if isinstance(nested, dict):
for key, value in nested.items():
ok = match_key(ignore_list, key)
if ok and prefix == "":
assign(key, value, True)
elif ok and prefix != "":
newKey = create_key(top, prefix, key)
assign(newKey, value, True)
else:
newKey = create_key(top, prefix, key)
assign(newKey, value, False)
elif isinstance(nested, (list, tuple,)):
for index, value in enumerate(nested):
if isinstance(value, dict):
for key1, value1 in value.items():
ok = match_key(ignore_list, key1)
if ok:
subkey = str(index) + "." + key1
newkey = create_key(top, prefix, subkey)
assign(newkey, value1, True)
else:
newkey = create_key(top, prefix, str(index))
assign(newkey, value, False)
else:
newkey = create_key(top, prefix, str(index))
assign(newkey, value, False)
else:
return ("Not a Valid input")
def create_key(top, prefix, subkey):
key = prefix
if top:
key += subkey
else:
key += "." + subkey
return key
def match_key(ignorelist, value):
for element in ignorelist:
if element == value:
return True
return False
while conditions[MODE]():
try:
for AURL in API_URL:
for ENDPOINT in ENDPOINT_LIST:
r = requests.get(url=AURL + ENDPOINT) if SECURE == False else get(url=AURL + ENDPOINT, headers={
'Content-Type': 'application/json'}, verify=False, pkcs12_filename=CERT_FILE, pkcs12_password=CERT_PASS)
received_response = r.json()
flat_response = flattening(received_response, "", [])
current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
points = [{
"measurement": ENDPOINT,
"tags": {'APIURL':AURL},
"time": current_time,
"fields": flat_response
}]
logger.info(ENDPOINT, extra=received_response)
iclient.write_points(points)
if IKEY != "REPLACE_ME":
handler.flush()
count += 1
except Exception as e:
# this will send an exception to the Application Insights Logs
logging.exception("Code ran into an unforseen exception!", sys.exc_info()[0])
time.sleep(SLEEP_INTERVAL)
# logging shutdown will cause a flush of all un-sent telemetry items
logging.shutdown()