Merge branch 'influxdb3'
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
FROM python:3.12-alpine
|
||||
ARG BUILD_VER
|
||||
|
||||
RUN apk update && apk upgrade --no-cache
|
||||
|
||||
RUN pip install --no-cache-dir RouterOS-API influxdb-client
|
||||
RUN pip install --no-cache-dir RouterOS-API influxdb3-python
|
||||
|
||||
COPY ./routermon.py /home/routermon.py
|
||||
COPY ./utils.py /home/pyutils/utils.py
|
||||
|
||||
ENV VER=${BUILD_VER}
|
||||
CMD [ "python", "/home/routermon.py" ]
|
||||
|
||||
@@ -2,88 +2,81 @@ import os
|
||||
import sys
|
||||
import time
|
||||
import logging
|
||||
import signal
|
||||
import json
|
||||
import routeros_api
|
||||
|
||||
from influxdb_client.client.write.point import Point
|
||||
from influxdb_client.client.influxdb_client import InfluxDBClient
|
||||
from influxdb_client.client.write_api import ASYNCHRONOUS, SYNCHRONOUS
|
||||
from pyutils.utils import *
|
||||
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():
|
||||
##################
|
||||
###### MAIN ######
|
||||
##################
|
||||
def main() -> int:
|
||||
INTERVAL = int(env['INTERVAL'])
|
||||
# Init InfluxDB
|
||||
write_client = InfluxDBClient(url=env['INFLUXDB_URL'],
|
||||
try:
|
||||
# Init InfluxDB-v3 Client
|
||||
write_client = InfluxDBClient3(host=env['INFLUXDB_URL'],
|
||||
token=env['INFLUXDB_TOKEN'],
|
||||
org=env['INFLUXDB_ORG'])
|
||||
write_api = write_client.write_api(write_options=ASYNCHRONOUS)
|
||||
# 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()
|
||||
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']}]")
|
||||
|
||||
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:
|
||||
##############################
|
||||
########## 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 = time.time()
|
||||
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]
|
||||
# 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))
|
||||
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(
|
||||
Point("interfaces")
|
||||
.tag("interface", d['name'])
|
||||
.field('rx-rate', if_stats[n]['rx-rate'])
|
||||
.field('tx-rate', if_stats[n]['tx-rate'])
|
||||
)
|
||||
rs1 = write_api.write(bucket=env['INFLUXDB_BUCKET'], org=env['INFLUXDB_ORG'],
|
||||
record=if_points)
|
||||
rs2 = write_api.write(bucket=env['INFLUXDB_BUCKET'], org=env['INFLUXDB_ORG'],
|
||||
record=Point('resources').field('cpu',int(hw_stats['cpu-load']))
|
||||
)
|
||||
LOGGER.debug(f"InfluxWrite: W1:{rs1}, W2:{rs2}")
|
||||
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
|
||||
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)
|
||||
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 ###
|
||||
|
||||
##############################
|
||||
###### END MAIN LOOP #########
|
||||
##############################
|
||||
connection.disconnect()
|
||||
write_client.close()
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -111,6 +104,7 @@ if __name__ == "__main__":
|
||||
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")
|
||||
|
||||
Reference in New Issue
Block a user