117 lines
4.1 KiB
Python
117 lines
4.1 KiB
Python
import os
|
|
import sys
|
|
import time
|
|
import logging
|
|
import signal
|
|
import json
|
|
import routeros_api
|
|
|
|
from influxdb_client_3 import InfluxDBClient3, Point
|
|
|
|
# Get environment variables
|
|
env = dict(os.environ)
|
|
LOGGER: logging.Logger
|
|
|
|
class SignalHandler:
|
|
running: bool
|
|
|
|
def __init__(self):
|
|
self.running: bool = True
|
|
signal.signal(signal.SIGINT, self._handle_sigint)
|
|
signal.signal(signal.SIGTERM, self._handle_sigint)
|
|
|
|
def _handle_sigint(self, signum, frame):
|
|
self.running = False
|
|
|
|
|
|
def main():
|
|
INTERVAL = int(env['INTERVAL'])
|
|
# Init InfluxDB
|
|
write_client = InfluxDBClient3(host=env['INFLUXDB_URL'],
|
|
token=env['INFLUXDB_TOKEN'],
|
|
database=env['INFLUXDB_DATABASE'])
|
|
# Init routerOS API
|
|
connection = routeros_api.RouterOsApiPool(env['MIKROTIK_IP'],
|
|
username=env['MIKROTIK_USER'],
|
|
password=env['MIKROTIK_PASSWORD'],
|
|
plaintext_login=True)
|
|
api = connection.get_api()
|
|
|
|
run: SignalHandler = SignalHandler()
|
|
last = 0
|
|
if_points = []
|
|
if_stats_old = api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})
|
|
for n,d in enumerate(if_stats_old):
|
|
for k,v in d.items():
|
|
if str.isdecimal(v):
|
|
if_stats_old[n][k] = int(v)
|
|
### MAIN LOOP ###
|
|
while run:
|
|
try:
|
|
now = time.time()
|
|
if_stats: list[dict] = api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})
|
|
hw_stats: dict[str,str] = api.get_resource('/system/resource').call('print', {'proplist':'uptime,cpu-load,total-memory,free-memory'})[0]
|
|
# calcolo della velocita' interfaccia a ogni ciclo
|
|
for n,d in enumerate(if_stats):
|
|
for k,v in d.items():
|
|
if str.isdecimal(v):
|
|
if_stats[n][k] = int(v)
|
|
if_stats[n]['rx-rate'] = int((if_stats[n]['rx-bytes']-if_stats_old[n]['rx-bytes'])/(now-last))
|
|
if_stats[n]['tx-rate'] = int((if_stats[n]['tx-bytes']-if_stats_old[n]['tx-bytes'])/(now-last))
|
|
if_points.append(
|
|
Point('interfaces')
|
|
.tag('interface', d['name'])
|
|
.field('rx-rate', if_stats[n]['rx-rate'])
|
|
.field('tx-rate', if_stats[n]['tx-rate'])
|
|
)
|
|
write_client.write(record=if_points)
|
|
|
|
hw_point = Point('resources')
|
|
for k,v in hw_stats.items():
|
|
hw_point.field(k,int(v) if v.isdecimal() else v)
|
|
write_client.write(record=hw_point)
|
|
|
|
if_stats_old = if_stats
|
|
last = time.time()
|
|
LOGGER.debug(f"\nInterfaces: {json.dumps(if_stats, indent = 2)}")
|
|
LOGGER.debug(f"\nResources: {json.dumps(hw_stats, indent = 2)}")
|
|
time.sleep(INTERVAL)
|
|
except Exception as e:
|
|
print(f"Unexpected exception: [{e}]")
|
|
return 1
|
|
### END MAIN LOOP ###
|
|
|
|
connection.disconnect()
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
# Logger Constants
|
|
LOG_FORMAT = '%(asctime)s| %(levelname)-7s|%(funcName)-10s|%(lineno)-3d: %(message)-50s'
|
|
|
|
# Enabling Logger
|
|
LOGGER = logging.getLogger(__name__)
|
|
LOGGER.setLevel(logging.DEBUG)
|
|
LOGGER.propagate = False
|
|
formatter = logging.Formatter(LOG_FORMAT, None)
|
|
levels = logging.getLevelNamesMapping()
|
|
|
|
# File logging
|
|
log_name = os.path.abspath(env['LOG_FILE'])
|
|
fh = logging.FileHandler(log_name)
|
|
fh.setLevel(levels[env['LOG_FILE_LVL']])
|
|
fh.setFormatter(formatter)
|
|
LOGGER.addHandler(fh)
|
|
|
|
# Console logging
|
|
cl = logging.StreamHandler(sys.stdout)
|
|
cl.setLevel(levels[env['LOG_CLI_LVL']])
|
|
cl.setFormatter(formatter)
|
|
LOGGER.addHandler(cl)
|
|
|
|
LOGGER.warning(f"Routermon started on: {time.asctime()}")
|
|
|
|
while main():
|
|
LOGGER.error("Main thread exited unexpectedly")
|
|
time.sleep(15)
|
|
sys.exit(0)
|