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
|
import time
import threading
import schedule
import queue
import json
import redis
import os
import pynetbox
import random
import netaddr
import requests
from requests.auth import HTTPBasicAuth
from dotenv import load_dotenv
load_dotenv()
cache = redis.Redis(
connection_pool=redis.ConnectionPool(
host=os.environ.get("REDIS_HOST", "localhost"),
port=os.environ.get("REDIS_PORT", 6379),
db=os.environ.get("REDIS_DB", 0),
decode_responses=True,
)
)
nb = pynetbox.api(
os.environ.get("NETBOX_URL"), token=os.environ.get("NETBOX_TOKEN"), threading=True
)
def get_devices():
devices = {}
for device in nb.dcim.devices.filter(
role=[
"access-switch",
"distro",
"firewall",
"internett-ruter",
"leaf",
"oob-switch",
"spine",
]
):
# print(device.name)
distro = None
uplink = None
mgmt_vlan = None
traffic_vlan = None
lag_id = None
# Find distro and distro port through the cable connected on uplink ae.
# interfaces = list(nb.dcim.interfaces.filter(device_id=device.id))
# for interface in interfaces:
# if interface["type"]["value"] == "lag":
# lag_id = interface["id"]
# if len(interface["tagged_vlans"]) > 0:
# mgmt_vlan = interface["tagged_vlans"][0]["name"]
# if len(interface["tagged_vlans"]) > 1:
# traffic_vlan = interface["tagged_vlans"][1]["name"]
# break
# if lag_id is not None:
# # get first lag member
# for interface in interfaces:
# if interface["lag"] is not None and interface["lag"]["id"] == lag_id:
# distro = interface["lag"]["device"]["name"]
# #print(distro)
# uplink = interface["name"]
# #print(uplink)
# break
if device.custom_fields["gondul_placement"] is None:
placement = {
"height": 16,
"x": random.randrange(50, 1400, 20),
"y": random.randrange(50, 600, 20),
"width": 120,
}
else:
placement = device.custom_fields["gondul_placement"]
if "x" not in placement or placement["x"] is None:
placement["x"] = random.randrange(50, 1400, 20)
if "y" not in placement or placement["y"] is None:
placement["y"] = random.randrange(50, 600, 20)
if "height" not in placement or placement["height"] is None:
placement["height"] = 16
if "width" not in placement or placement["width"] is None:
placement["width"] = 120
devices.update(
{
device.name: {
"sysname": device.name,
"mgmt_v4_addr": (
str(netaddr.IPNetwork(device.primary_ip4.address).ip)
if device.primary_ip4 is not None
else None
),
"mgmt_v6_addr": (
str(netaddr.IPNetwork(device.primary_ip6.address).ip)
if device.primary_ip6 is not None
else None
),
"mgmt_vlan": mgmt_vlan,
"traffic_vlan": traffic_vlan,
"last_updated": device.last_updated,
"distro_name": distro,
"distro_phy_port": uplink,
"tags": [tag.slug for tag in list(device.tags)],
"placement": placement,
"serial": device.serial,
"platform": (
device.platform.slug if device.platform is not None else None
),
}
}
)
return devices
def generateDevices():
start_time = time.time()
print("Updating device cache")
cache.set("devices:updated", round(time.time()))
cache.set("devices:data", json.dumps(get_devices()))
print("Device cache updated")
print("--- %s seconds ---" % (time.time() - start_time))
# {
# "ifInErrors":"0",
# "ifInDiscards":"0",
# "ifHCInOctets":"0",
# "ifOutDiscards":"0",
# "ifName":"ge-0/0/36.0",
# "ifAdminStatus":"up",
# "ifOperStatus":"lowerLayerDown",
# "ifIndex":"588",
# "ifOutQLen":"0",
# "ifAlias":"",
# "ifInUnknownProtos":"0",
# "ifOutErrors":"0",
# "ifType":"propVirtual",
# "ifPhysAddress":"44:f4:77:69:38:67",
# "ifHighSpeed":"0",
# "ifDescr":"ge-0/0/36.0",
# "ifHCOutOctets":"0",
# "ifLastChange":"6312"
# }
def getSnmpPorts():
switches = {}
basic = HTTPBasicAuth(os.environ.get("PROM_USER"), os.environ.get("PROM_PASSWORD"))
prom_url = os.environ.get("PROM_URL")
ifIndex = requests.get(
prom_url + "/api/v1/query",
params={"query": "ifType_info"},
auth=basic
)
if ifIndex.ok and ifIndex.json()["status"] == "success":
for metric in ifIndex.json()["data"]["result"]:
if metric["metric"]["sysname"] not in switches:
switches[metric["metric"]["sysname"]] = {"ports": {}}
if metric["metric"]["ifName"] not in switches[metric["metric"]["sysname"]]["ports"]:
switches[metric["metric"]["sysname"]]["ports"][metric["metric"]["ifName"]] = {}
switches[metric["metric"]["sysname"]]["ports"][metric["metric"]["ifName"]].update({
"ifIndex": metric["metric"]["ifIndex"] if "ifIndex" in metric["metric"] else None,
"ifAlias": metric["metric"]["ifAlias"] if "ifAlias" in metric["metric"] else None,
"ifName": metric["metric"]["ifName"] if "ifName" in metric["metric"] else None,
"ifDescr": metric["metric"]["ifDescr"] if "ifDescr" in metric["metric"] else None,
"ifType": metric["metric"]["ifType"] if "ifType" in metric["metric"] else None,
})
ifAdminStatusMapping = {"1": "up", "2": "down"}
ifAdminStatus = requests.get(
prom_url + "/api/v1/query",
params={"query": "ifAdminStatus"},
auth=basic
)
if ifAdminStatus.ok and ifAdminStatus.json()["status"] == "success":
for metric in ifAdminStatus.json()["data"]["result"]:
if metric["metric"]["sysname"] not in switches:
switches[metric["metric"]["sysname"]] = {"ports": {}}
if metric["metric"]["ifName"] not in switches[metric["metric"]["sysname"]]["ports"]:
switches[metric["metric"]["sysname"]]["ports"][metric["metric"]["ifName"]] = {}
switches[metric["metric"]["sysname"]]["ports"][metric["metric"]["ifName"]].update({
"ifAdminStatus": ifAdminStatusMapping[str(metric["value"][1])]
})
# 1-up, 2-down, 3-testing, 4-unknown, 5-dormant, 6-notPresent, 7-lowerLayerDown
ifOperStatusMapping = {"1": "up", "2": "down", "3": "testing", "4": "unknown", "5": "dormant", "6": "notPresent", "7": "lowerLayerDown"}
ifOperStatus = requests.get(
prom_url + "/api/v1/query",
params={"query": "ifOperStatus"},
auth=basic
)
if ifOperStatus.ok and ifOperStatus.json()["status"] == "success":
for metric in ifOperStatus.json()["data"]["result"]:
if metric["metric"]["sysname"] not in switches:
switches[metric["metric"]["sysname"]] = {"ports": {}}
if metric["metric"]["ifName"] not in switches[metric["metric"]["sysname"]]["ports"]:
switches[metric["metric"]["sysname"]]["ports"][metric["metric"]["ifName"]] = {}
switches[metric["metric"]["sysname"]]["ports"][metric["metric"]["ifName"]].update({
"ifOperStatus": ifOperStatusMapping[str(metric["value"][1])]
})
ifHighSpeed = requests.get(
prom_url + "/api/v1/query",
params={"query": "ifHighSpeed"},
auth=basic
)
if ifHighSpeed.ok and ifHighSpeed.json()["status"] == "success":
for metric in ifHighSpeed.json()["data"]["result"]:
if metric["metric"]["sysname"] not in switches:
switches[metric["metric"]["sysname"]] = {"ports": {}}
if metric["metric"]["ifName"] not in switches[metric["metric"]["sysname"]]["ports"]:
switches[metric["metric"]["sysname"]]["ports"][metric["metric"]["ifName"]] = {}
switches[metric["metric"]["sysname"]]["ports"][metric["metric"]["ifName"]].update({
"ifHighSpeed": metric["value"][1]
})
cache.set("snmp:ports:updated", round(time.time()))
cache.set("snmp:ports:data", json.dumps(switches))
def getSnmp():
output = {}
basic = HTTPBasicAuth(os.environ.get("PROM_USER"), os.environ.get("PROM_PASSWORD"))
prom_url = os.environ.get("PROM_URL")
sysUpTime = requests.get(
prom_url + "/api/v1/query",
params={"query": "sysUpTime"},
auth=basic,
)
if sysUpTime.ok and sysUpTime.json()["status"] == "success":
for metric in sysUpTime.json()["data"]["result"]:
if metric["metric"]["sysname"] not in output:
output[metric["metric"]["sysname"]] = {}
if metric["value"][1] == "0":
output[metric["metric"]["sysname"]].update(
{
f'{metric["metric"]["__name__"]}_time': metric["value"][0],
f'{metric["metric"]["__name__"]}': None,
}
)
else:
output[metric["metric"]["sysname"]].update(
{
f'{metric["metric"]["__name__"]}_time': metric["value"][0],
f'{metric["metric"]["__name__"]}': metric["value"][1],
}
)
sysName = requests.get(
prom_url + "/api/v1/query",
params={"query": "sysName"},
auth=basic,
)
if sysName.ok and sysName.json()["status"] == "success":
for metric in sysName.json()["data"]["result"]:
if metric["metric"]["sysname"] not in output:
output[metric["metric"]["sysname"]] = {}
if metric["value"][1] == "0":
output[metric["metric"]["sysname"]].update(
{
f'{metric["metric"]["__name__"]}_time': metric["value"][0],
f'{metric["metric"]["__name__"]}': None,
}
)
else:
output[metric["metric"]["sysname"]].update(
{
f'{metric["metric"]["__name__"]}_time': metric["value"][0],
f'{metric["metric"]["__name__"]}': metric["metric"]["sysName"],
}
)
sysDescr = requests.get(
prom_url + "/api/v1/query",
params={"query": "sysDescr"},
auth=basic,
)
if sysDescr.ok and sysDescr.json()["status"] == "success":
for metric in sysDescr.json()["data"]["result"]:
if metric["metric"]["sysname"] not in output:
output[metric["metric"]["sysname"]] = {}
if metric["value"][1] == "0":
output[metric["metric"]["sysname"]].update(
{
f'{metric["metric"]["__name__"]}_time': metric["value"][0],
f'{metric["metric"]["__name__"]}': None,
}
)
else:
output[metric["metric"]["sysname"]].update(
{
f'{metric["metric"]["__name__"]}_time': metric["value"][0],
f'{metric["metric"]["__name__"]}': metric["metric"]["sysDescr"],
}
)
entPhysicalSerialNum = requests.get(
prom_url + "/api/v1/query",
params={"query": "entPhysicalSerialNum"},
auth=basic,
)
if entPhysicalSerialNum.ok and entPhysicalSerialNum.json()["status"] == "success":
for metric in entPhysicalSerialNum.json()["data"]["result"]:
if metric["metric"]["sysname"] not in output:
output[metric["metric"]["sysname"]] = {}
if metric["value"][1] == "0":
output[metric["metric"]["sysname"]].update(
{
f'{metric["metric"]["__name__"]}_time': metric["value"][0],
f'{metric["metric"]["__name__"]}': None,
}
)
else:
output[metric["metric"]["sysname"]].update(
{
f'{metric["metric"]["__name__"]}_time': metric["value"][0],
f'{metric["metric"]["__name__"]}': metric["metric"][
"entPhysicalSerialNum"
],
}
)
cache.set("snmp:updated", round(time.time()))
cache.set("snmp:data:data", json.dumps(output))
def getPing():
output = {}
basic = HTTPBasicAuth(os.environ.get("PROM_USER"), os.environ.get("PROM_PASSWORD"))
prom_url = os.environ.get("PROM_URL")
probe_icmp_duration_seconds = requests.get(
prom_url + "/api/v1/query",
params={
"query": 'probe_icmp_duration_seconds{phase="rtt"}',
"latency_offset": "1ms",
},
auth=basic,
)
if (
probe_icmp_duration_seconds.ok
and probe_icmp_duration_seconds.json()["status"] == "success"
):
for metric in probe_icmp_duration_seconds.json()["data"]["result"]:
if metric["metric"]["sysname"] not in output:
output[metric["metric"]["sysname"]] = {}
if metric["value"][1] == "0":
output[metric["metric"]["sysname"]].update(
{
f'{metric["metric"]["type"]}_time': metric["value"][0],
f'{metric["metric"]["type"]}_{metric["metric"]["phase"]}': None,
}
)
else:
output[metric["metric"]["sysname"]].update(
{
f'{metric["metric"]["type"]}_time': metric["value"][0],
f'{metric["metric"]["type"]}_{metric["metric"]["phase"]}': float(
metric["value"][1]
),
}
)
cache.set("ping:updated", round(time.time()))
cache.set("ping:data", json.dumps(output))
# DCIM
def dcim_main():
while 1:
job_func = dcim_jobqueue.get()
job_func()
dcim_jobqueue.task_done()
dcim_jobqueue = queue.Queue()
dcim_scheduler = schedule.Scheduler()
dcim_scheduler.every(60).seconds.do(dcim_jobqueue.put, generateDevices)
dcim_worker_thread = threading.Thread(daemon=True, target=dcim_main)
dcim_worker_thread.start()
# Ping
def ping_main():
while 1:
job_func = ping_jobqueue.get()
job_func()
ping_jobqueue.task_done()
ping_jobqueue = queue.Queue()
ping_scheduler = schedule.Scheduler()
ping_scheduler.every(1).seconds.do(ping_jobqueue.put, getPing)
ping_worker_thread = threading.Thread(daemon=True, target=ping_main)
ping_worker_thread.start()
# Snmp
def snmp_main():
while 1:
job_func = snmp_jobqueue.get()
job_func()
snmp_jobqueue.task_done()
snmp_jobqueue = queue.Queue()
snmp_scheduler = schedule.Scheduler()
snmp_scheduler.every(5).seconds.do(snmp_jobqueue.put, getSnmp)
snmp_scheduler.every(5).seconds.do(snmp_jobqueue.put, getSnmpPorts)
snmp_worker_thread = threading.Thread(daemon=True, target=snmp_main)
snmp_worker_thread.start()
# Main loop
while 1:
dcim_scheduler.run_pending()
ping_scheduler.run_pending()
snmp_scheduler.run_pending()
time.sleep(1)
|