use NestedDeserializableDataclass for config

This commit is contained in:
Alex 2025-01-07 01:43:39 +03:00
parent 96664684f8
commit 3eb358d618
13 changed files with 188 additions and 130 deletions

View file

@ -1,34 +1,14 @@
import json
from dataclasses import dataclass
from enum import Enum, StrEnum
from typing import Optional
import aiofiles
import nio
from alerting.common import CONFIG_FILE
from alerting.enum import AlertType, Severity
from misc import cvars
class AlertType(StrEnum):
TEST = "TEST"
ERROR = "ERROR"
RAM = "RAM"
CPU = "CPU"
TEMP = "TEMP"
VULN = "VULN"
LOGIN = "LOGIN" # TODO
SMART = "SMART" # TODO
RAID = "RAID"
DISKS = "DISKS"
UPS = "UPS"
UPDATE = "UPDATE"
class Severity(StrEnum):
INFO = "INFO"
WARNING = "WARNING"
CRITICAL = "CRITICAL"
from misc.common import CONFIG_FILE
from misc.config import get_config
@dataclass
@ -44,11 +24,11 @@ async def get_client() -> nio.AsyncClient:
Returns a Matrix client.
It is better to call get_client once and use it for multiple send_alert calls
"""
matrix_cfg = cvars.config.get()["matrix"]
client = nio.AsyncClient(matrix_cfg["homeserver"])
client.access_token = matrix_cfg["access_token"]
client.user_id = matrix_cfg["user_id"]
client.device_id = matrix_cfg["device_id"]
matrix_cfg = cvars.config.get().matrix
client = nio.AsyncClient(matrix_cfg.homeserver)
client.access_token = matrix_cfg.access_token
client.user_id = matrix_cfg.user_id
client.device_id = matrix_cfg.device_id
return client
@ -72,15 +52,13 @@ async def send_alert(alert: Alert) -> None:
try:
client = cvars.matrix_client.get()
except LookupError: # being called standalone
async with aiofiles.open(CONFIG_FILE) as f:
contents = await f.read()
cvars.config.set(json.loads(contents))
cvars.config.set(get_config())
temp_client = True
client = await get_client()
cvars.matrix_client.set(client)
else:
temp_client = False
room_id = cvars.config.get()["matrix"]["room_id"]
room_id = cvars.config.get().matrix.room_id
message, html_message = format_message(alert)
content = {
"msgtype": "m.text",