Logging, envvars and launch profile
This commit is contained in:
25
.vscode/launch.json
vendored
Normal file
25
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Python Debugger: Tikmon",
|
||||||
|
"type": "debugpy",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${file}",
|
||||||
|
"console": "integratedTerminal",
|
||||||
|
"env": {
|
||||||
|
"INTERVAL" : "5",
|
||||||
|
"INFLUXDB_TOKEN":"rg5dZrBHQxJTH4Etq2jmDduggCC28QaWcua0VVvW4hjsEVhy_JUpVhcyg-aLAbM-TXv92pTB7IGJlyAPvi7Kvw==",
|
||||||
|
"INFLUXDB_URL" : "http://10.0.2.249:4567",
|
||||||
|
"INFLUXDB_ORG" : "edelweiss",
|
||||||
|
"INFLUXDB_BUCKET" : "router",
|
||||||
|
"MIKROTIK_IP": "10.128.0.1",
|
||||||
|
"MIKROTIK_USER": "service",
|
||||||
|
"MIKROTIK_PASSWORD": "edxservice",
|
||||||
|
"LOG_FILE": "D:\\Test\\routermon.log",
|
||||||
|
"LOG_FILE_LVL": "WARNING",
|
||||||
|
"LOG_CLI_LVL": "DEBUG"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
94
routermon.py
94
routermon.py
@@ -1,35 +1,54 @@
|
|||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
import json
|
|
||||||
import time
|
import time
|
||||||
|
import logging
|
||||||
|
import signal
|
||||||
|
import json
|
||||||
import routeros_api
|
import routeros_api
|
||||||
|
|
||||||
import influxdb_client
|
import influxdb_client
|
||||||
from influxdb_client import Point
|
from influxdb_client import Point
|
||||||
from influxdb_client.client.write_api import ASYNCHRONOUS
|
from influxdb_client.client.write_api import ASYNCHRONOUS
|
||||||
|
|
||||||
INTERVAL = 5
|
# Get environment variables
|
||||||
INFLUXDB_TOKEN='rg5dZrBHQxJTH4Etq2jmDduggCC28QaWcua0VVvW4hjsEVhy_JUpVhcyg-aLAbM-TXv92pTB7IGJlyAPvi7Kvw=='
|
env = dict(os.environ)
|
||||||
URL = "http://10.0.2.249:4567"
|
LOGGER = None
|
||||||
ORG = "edelweiss"
|
|
||||||
BUCKET = "router"
|
class Runner:
|
||||||
|
running: property = True
|
||||||
|
def __init__(self):
|
||||||
|
signal.signal(signal.SIGINT, self.stop)
|
||||||
|
signal.signal(signal.SIGTERM, self.stop)
|
||||||
|
|
||||||
|
def stop(self, _):
|
||||||
|
self.running = False
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
INTERVAL = int(env['INTERVAL'])
|
||||||
write_client = influxdb_client.InfluxDBClient(url=URL, token=INFLUXDB_TOKEN, org=ORG)
|
# Init InfluxDB
|
||||||
|
write_client = influxdb_client.InfluxDBClient(url=env['INFLUXDB_URL'],
|
||||||
|
token=env['INFLUXDB_TOKEN'],
|
||||||
|
org=env['INFLUXDB_ORG'])
|
||||||
write_api = write_client.write_api(write_options=ASYNCHRONOUS)
|
write_api = write_client.write_api(write_options=ASYNCHRONOUS)
|
||||||
|
# Init routerOS API
|
||||||
connection = routeros_api.RouterOsApiPool('10.128.0.1', username='service', password='edxservice', plaintext_login=True)
|
connection = routeros_api.RouterOsApiPool(env['MIKROTIK_IP'],
|
||||||
|
username=env['MIKROTIK_USER'],
|
||||||
|
password=env['MIKROTIK_PASSWORD'],
|
||||||
|
plaintext_login=True)
|
||||||
api = connection.get_api()
|
api = connection.get_api()
|
||||||
run = True
|
|
||||||
if_stats_old = None
|
run = Runner.running
|
||||||
last = 0
|
last = 0
|
||||||
|
points = []
|
||||||
|
if_stats_old = None
|
||||||
|
### MAIN LOOP ###
|
||||||
while run:
|
while run:
|
||||||
try:
|
try:
|
||||||
if_stats = api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})
|
if_stats = api.get_resource('/interface/ethernet').call('print', {'proplist': 'name,rx-bytes,tx-bytes'})
|
||||||
hw_stats = api.get_resource('/system/resource').call('print', {'proplist':'uptime,cpu-load'})[0]
|
hw_stats = api.get_resource('/system/resource').call('print', {'proplist':'uptime,cpu-load'})[0]
|
||||||
# calcolo della velocita' interfaccia a ogni ciclo
|
# calcolo della velocita' interfaccia a ogni ciclo
|
||||||
now = time.time()
|
now = time.time()
|
||||||
points = []
|
|
||||||
for n,d in enumerate(if_stats):
|
for n,d in enumerate(if_stats):
|
||||||
for k,v in d.items():
|
for k,v in d.items():
|
||||||
if str.isdecimal(v):
|
if str.isdecimal(v):
|
||||||
@@ -43,20 +62,53 @@ def main():
|
|||||||
.field('rx-rate', if_stats[n]['rx-rate'])
|
.field('rx-rate', if_stats[n]['rx-rate'])
|
||||||
.field('tx-rate', if_stats[n]['tx-rate'])
|
.field('tx-rate', if_stats[n]['tx-rate'])
|
||||||
)
|
)
|
||||||
write_api.write(bucket=BUCKET, org=ORG, record=points)
|
rs1 = write_api.write(bucket=env['INFLUXDB_BUCKET'], org=env['INFLUXDB_ORG'], record=points)
|
||||||
write_api.write(bucket=BUCKET, org=ORG,
|
rs2 = write_api.write(bucket=env['INFLUXDB_BUCKET'], org=env['INFLUXDB_ORG'],
|
||||||
record=Point('resources')
|
record=Point('resources')
|
||||||
.field('cpu',int(hw_stats['cpu-load']))
|
.field('cpu',int(hw_stats['cpu-load']))
|
||||||
)
|
)
|
||||||
if_stats_old = if_stats
|
if_stats_old = if_stats
|
||||||
print(json.dumps(if_stats, indent=2))
|
|
||||||
print(json.dumps(hw_stats, indent=2))
|
|
||||||
last = time.time()
|
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)
|
time.sleep(INTERVAL)
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
run = False
|
run = False
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Unexpected exception: [{e}]")
|
||||||
|
return 1
|
||||||
|
### END MAIN LOOP ###
|
||||||
|
|
||||||
connection.disconnect()
|
connection.disconnect()
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
sys.exit(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)
|
||||||
|
|||||||
Reference in New Issue
Block a user