netglass/netglass/netglass.py

112 lines
3.5 KiB
Python
Executable File

#!flask/bin/python3
import re
import os
from flask import Flask, jsonify
import pynetbox
import json
from datetime import datetime
box = pynetbox.api(
os.environ.get('NETBOX_URL'),
token=os.environ['NETBOX_TOKEN']
)
netglass = Flask(__name__)
@netglass.route('/graph.json')
def net_graph():
links = []
nodes = []
dcim_port_types = ['dcim.interface','dcim.frontport','dcim.rearport']
def _isdevice(device):
if isinstance(device, pynetbox.models.dcim.Devices):
return device
for wire in box.dcim.cables.all():
term_a = wire.termination_a.device if wire.termination_a_type in dcim_port_types else None
term_b = wire.termination_b.device if wire.termination_b_type in dcim_port_types else None
for node in [term_a,term_b]:
if not _isdevice(node):
continue
if not next((n for n in nodes if n['node_id'] == str(node.id)), None):
nodes.append({
'node_id': str(node.id),
'id': str(node.id)
})
link = {
'bidirect': True,
'source': next((
i for i, item in enumerate(nodes)
if term_a and item['node_id'] == str(term_a.id)), None),
'target': next((
i for i, item in enumerate(nodes)
if term_b and item['node_id'] == str(term_b.id)), None),
'tq': 1,
}
if link['source'] != None and link['target'] != None:
links.append(link)
return jsonify({'batadv':{
'directed': True,
'graph': None,
'multigraph': True,
'links': links,
'nodes': nodes,
},
'version': 1})
@netglass.route('/nodes.json')
def net_nodes():
nodes = []
for node in [
n for n in box.dcim.devices.all()
if isinstance(n, pynetbox.models.dcim.Devices)]:
lastseen = datetime.now().replace(microsecond=0)
addresses = []
for primary_ip in [node.primary_ip4,node.primary_ip6]:
if primary_ip:
addresses.append(re.sub(r'/\d+', '', primary_ip.address))
nodes.append({
'flags': {'online': True, 'gateway': False},
'firstseen': lastseen.isoformat(),
'lastseen': lastseen.isoformat(),
'nodeinfo': {
'hostname': node.name if node.name else f"Unnamed Device ({node.id})",
'node_id': str(node.id),
'network': { 'mac': node.name, 'addresses': addresses },
'mesh_interfaces': [node.name],
'mesh': {
'bat0': { 'interfaces': { 'other': [node.name] } }
},
'system': {
'site_code': 'net'
},
'traffic': {
'forward': {'packets': 0, 'bytes': 0},
'mgmt_rx': {'packets': 0, 'bytes': 0},
'mgmt_tx': {'packets': 0, 'bytes': 0},
'rx': {'packets': 0, 'bytes': 0},
'tx': {'packets': 0, 'bytes': 0, 'dropped': 0}
}
},
'statistics': {
'clients': 0,
'gateway': '',
'memory_usage': 0,
'rootfs_usage': 0,
'uptime': 0
}
})
return jsonify({
'nodes': nodes,
'timestamp': datetime.now().replace(microsecond=0).isoformat(),
'version': 2
})
if __name__ == '__main__':
netglass.run(debug=False, port=8080)