Made targets work with a json
This commit is contained in:
@@ -1,32 +1,16 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
import time
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import aiohttp
|
||||
from mcstatus import JavaServer
|
||||
|
||||
TARGETS = [
|
||||
{
|
||||
'name': 'Gitea',
|
||||
'url': 'https://gitea.rainbow-herring.ts.net/api/healthz',
|
||||
'kind': 'gitea',
|
||||
'critical': True,
|
||||
},
|
||||
{
|
||||
'name': 'Packs Site (Production)',
|
||||
'url': 'https://jakerasp.rainbow-herring.ts.net/healthz/',
|
||||
'kind': 'packs',
|
||||
'critical': True,
|
||||
},
|
||||
{
|
||||
'name': 'Minecraft Server',
|
||||
'host': 'jakelaptop.rainbow-herring.ts.net',
|
||||
'port': 10000,
|
||||
'kind': 'minecraft',
|
||||
'critical': True,
|
||||
},
|
||||
]
|
||||
import config
|
||||
|
||||
log = logging.getLogger('healthbot')
|
||||
|
||||
GITEA_VERSION_URL = 'https://gitea.rainbow-herring.ts.net/api/v1/version'
|
||||
|
||||
@@ -36,6 +20,75 @@ DOH_RESOLVERS = {
|
||||
}
|
||||
|
||||
|
||||
class TargetsConfigError(Exception):
|
||||
"""Raised when the targets configuration file is missing or invalid."""
|
||||
|
||||
|
||||
def validate_targets(data):
|
||||
"""Validate parsed targets data, returning a normalized list of targets."""
|
||||
if not isinstance(data, list):
|
||||
raise TargetsConfigError('targets must be a JSON list')
|
||||
targets = []
|
||||
for i, entry in enumerate(data):
|
||||
if not isinstance(entry, dict):
|
||||
raise TargetsConfigError(f'entry {i} is not an object')
|
||||
name = entry.get('name')
|
||||
if not isinstance(name, str) or not name.strip():
|
||||
raise TargetsConfigError(f'entry {i} missing a valid "name"')
|
||||
kind = entry.get('kind')
|
||||
if not isinstance(kind, str) or not kind.strip():
|
||||
raise TargetsConfigError(f'entry {i} missing a valid "kind"')
|
||||
if kind == 'minecraft':
|
||||
host = entry.get('host')
|
||||
port = entry.get('port')
|
||||
if not isinstance(host, str) or not host.strip():
|
||||
raise TargetsConfigError(f'entry {i} missing a valid "host"')
|
||||
if not isinstance(port, int) or not (0 < port < 65536):
|
||||
raise TargetsConfigError(f'entry {i} missing a valid "port"')
|
||||
else:
|
||||
url = entry.get('url')
|
||||
if not isinstance(url, str) or not url.strip():
|
||||
raise TargetsConfigError(f'entry {i} missing a valid "url"')
|
||||
critical = entry.get('critical', True)
|
||||
if not isinstance(critical, bool):
|
||||
raise TargetsConfigError(f'entry {i} "critical" must be true/false')
|
||||
target = {'name': name.strip(), 'kind': kind.strip(), 'critical': critical}
|
||||
target.update({k: entry[k] for k in ('url', 'host', 'port') if k in entry})
|
||||
targets.append(target)
|
||||
return targets
|
||||
|
||||
|
||||
def load_targets():
|
||||
"""Load the live targets file; on success refresh the backup copy.
|
||||
|
||||
Raises TargetsConfigError if the live file is missing or invalid.
|
||||
"""
|
||||
try:
|
||||
with open(config.TARGETS_FILE, 'r') as f:
|
||||
raw = f.read()
|
||||
targets = validate_targets(json.loads(raw))
|
||||
except (OSError, ValueError, TargetsConfigError) as exc:
|
||||
raise TargetsConfigError(
|
||||
f'invalid targets file {config.TARGETS_FILE}: {exc}'
|
||||
) from exc
|
||||
try:
|
||||
shutil.copyfile(config.TARGETS_FILE, config.TARGETS_BACKUP_FILE)
|
||||
except OSError as exc:
|
||||
log.warning('Could not back up targets file: %s', exc)
|
||||
return targets
|
||||
|
||||
|
||||
def load_backup_targets():
|
||||
"""Load the last known-good copy of the targets file."""
|
||||
try:
|
||||
with open(config.TARGETS_BACKUP_FILE, 'r') as f:
|
||||
return validate_targets(json.load(f))
|
||||
except (OSError, ValueError, TargetsConfigError) as exc:
|
||||
raise TargetsConfigError(
|
||||
f'backup targets file {config.TARGETS_BACKUP_FILE} also invalid: {exc}'
|
||||
) from exc
|
||||
|
||||
|
||||
async def _get(session, url, timeout):
|
||||
started = time.monotonic()
|
||||
async with session.get(
|
||||
@@ -179,7 +232,14 @@ async def check_target(session, target, timeout):
|
||||
|
||||
|
||||
async def run_checks(session, timeout):
|
||||
using_backup = False
|
||||
try:
|
||||
targets = load_targets()
|
||||
except TargetsConfigError as exc:
|
||||
log.exception('Targets config problem: %s', exc)
|
||||
targets = load_backup_targets()
|
||||
using_backup = True
|
||||
results = await asyncio.gather(
|
||||
*(check_target(session, target, timeout) for target in TARGETS)
|
||||
*(check_target(session, target, timeout) for target in targets)
|
||||
)
|
||||
return list(results)
|
||||
return list(results), using_backup
|
||||
|
||||
Reference in New Issue
Block a user