import os import sys import time import logging import json import routeros_api from pyutils.utils import * from influxdb_client_3 import InfluxDBClient3, Point # Get environment variables env = dict(os.environ) LOGGER: logging.Logger ################## ###### MAIN ###### ################## def main() -> int: INTERVAL = int(env['INTERVAL']) try: # Init InfluxDB-v3 Client 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() except Exception as e: LOGGER.error(e) return 1 finally: LOGGER.info(f"InfluxDB Connected: [{env['INFLUXDB_URL']}/{env['INFLUXDB_DATABASE']}]") LOGGER.info(f"Mikrotik Connected: [{env['MIKROTIK_IP']}]") ############################## ########## MAIN LOOP ######### ############################## last: float = 0 handler: SignalHandler = SignalHandler(LOGGER) if_stats_old = convertIntList(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})) while handler.running: try: now:float = time.time() if_points: list[Point] = [] if_stats: list[dict] = convertIntList(api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})) hw_stats: dict[str,str] = convertInt(api.get_resource('/system/resource').call('print', {'proplist':'uptime,cpu-load,total-memory,free-memory'})[0]) hw_stats['temperature'] = convertInt(api.get_resource('/system/health').call('print')[1])['value'] # Calcolo della velocita' interfaccia a ogni ciclo for n, _ in enumerate(if_stats): if_name = if_stats[n].pop('name') if_stats[n]['rx-rate'] = int((if_stats[n]['rx-bytes']-if_stats_old[n]['rx-bytes'])/(INTERVAL)) if_stats[n]['tx-rate'] = int((if_stats[n]['tx-bytes']-if_stats_old[n]['tx-bytes'])/(INTERVAL)) if_points.append( dict2Point('interfaces', if_stats[n], {'interface': if_name}) ) write_client.write(record=if_points) # Risorse del router write_client.write(record=dict2Point('resources',hw_stats)) # Salvo ultimo punto per il giro successivo if_stats_old = if_stats LOGGER.debug(f"\nInterfaces: {json.dumps(if_stats, indent = 2)}") LOGGER.debug(f"\nResources: {json.dumps(hw_stats, indent = 2)}") last: float = time.time() cycle_time: float = last - now LOGGER.debug(f"Cycle Time: {cycle_time:4.3f}") time.sleep(INTERVAL-cycle_time) except Exception as e: print(f"Unexpected exception: [{e}]") return 1 ############################## ###### END MAIN LOOP ######### ############################## connection.disconnect() write_client.close() 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()}") LOGGER.info(f"Routermon BUILD: {env.get("VER", "Test")}") while main(): LOGGER.error("Main thread exited unexpectedly") time.sleep(15) sys.exit(0)