86 lines
2.6 KiB
Python
86 lines
2.6 KiB
Python
import os
|
|
import logging
|
|
import sys
|
|
import time
|
|
import psutil
|
|
|
|
from pyutils.utils import *
|
|
from influxdb_client_3 import InfluxDBClient3, Point
|
|
|
|
# Get environment variables
|
|
env = dict(os.environ)
|
|
LOGGER: logging.Logger
|
|
|
|
def main():
|
|
INTERVAL = int(env['INTERVAL'])
|
|
try:
|
|
# Init InfluxDB-v3 Client
|
|
write_client = InfluxDBClient3(host=env['INFLUXDB_URL'],
|
|
token=env['INFLUXDB_TOKEN'],
|
|
database=env['INFLUXDB_DATABASE'])
|
|
except Exception as e:
|
|
LOGGER.error(e)
|
|
return 1
|
|
finally:
|
|
LOGGER.info(f"InfluxDB Connected: [{env['INFLUXDB_URL']}/{env['INFLUXDB_DATABASE']}]")
|
|
|
|
##############################
|
|
########## MAIN LOOP #########
|
|
##############################
|
|
handler: SignalHandler = SignalHandler(LOGGER)
|
|
while handler.running:
|
|
try:
|
|
p: Point = Point("hwmon").tag("host", "edelweiss-srv")
|
|
for i, cpu_percent in enumerate(psutil.cpu_percent(interval=INTERVAL, percpu=True)):
|
|
p.field(f"cpu_{i}", cpu_percent)
|
|
p.field("temp", psutil.sensors_temperatures()['k10temp'][0].current)
|
|
p.field("ram", psutil.virtual_memory().percent)
|
|
write_client.write(p)
|
|
LOGGER.debug(f"HW Stats: {p.to_line_protocol()}")
|
|
except psutil.Error as e:
|
|
LOGGER.error(e)
|
|
write_client.close()
|
|
time.sleep(10)
|
|
return 1
|
|
except KeyboardInterrupt:
|
|
LOGGER.info("Exiting Loop...")
|
|
write_client.close()
|
|
return 0
|
|
except:
|
|
LOGGER.error("An unexpected error occurred")
|
|
write_client.close()
|
|
time.sleep(10.0)
|
|
return 1
|
|
|
|
#### MAIN LOOP ####
|
|
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) |