Files
thor/thor/config.py
T
jaredandClaude Opus 5.5 ab4b20d15f
CI / Lint (flake8, house style) (pull_request) Successful in 56s
CI / Test (pytest) (pull_request) Successful in 53s
CI / Security (bandit, pip-audit) (pull_request) Successful in 1m8s
CI / Integration (MariaDB) (pull_request) Successful in 1m49s
CI / UI (screenshots) (pull_request) Failing after 1m7s
CI / Scan (secrets, workflows, shell, patterns) (pull_request) Successful in 1m58s
CI / Deploy (pull_request) Skipped
UI and API: Needs attention, incident pages, known conditions, /covering for Gandalf and hwmonDaemon
- thor/web/api.py: /api/incidents/covering (thor#1 pre-check), /api/incidents, /api/incident/<key>,
  machine keys by SHA-256 with optional source CIDRs, like Gandalf's (gandalf#68); 503 when the
  database is away so callers fail open. covered=true only when there is a ticket to comment on;
  shadow incidents are listed but never cover.
- thor/web/ui.py + templates: Needs attention (incidents, Thor itself, timeline-only, known
  conditions seen again, unexplained symptoms), incident page (what happened, also seen, what
  Thor sent or would have sent, ticket text), known conditions. Read-only; CSP with nonces;
  Authelia identity shown only when it comes from NPM. Mobile nav drawer.
- web_template v1.2 (8286bb2) vendored and checked against upstream in CI.
- docs/contract.md: the /covering contract for the Gandalf and hwmonDaemon sessions.
- scripts/ui_demo.py + scripts/screenshots.py, and a CI job that renders every page with replay
  data (desktop, mobile, dark, light) and uploads the screenshots.
- Fix: systemd-escaped cpusets (system-ceph\x2dosd.slice) were not recognised as Ceph; four of
  the 11-23 kills came from the OSD slice. Found while reviewing the screenshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 23:23:43 -05:00

163 lines
6.2 KiB
Python

"""Settings for Thor.
Two sources, read in this order (later wins):
1. ``/etc/thor/thor.json``: non-secret settings (URLs, cadence, check modes). Optional;
every key has a default. ``deploy/thor.example.json`` documents them.
2. ``/etc/thor/*.env``: one ``KEY=VALUE`` per line, holding secrets (Proxmox token,
database password, Gandalf and Tinker keys). Readable by root and the ``thor`` group
only, never in the repo.
3. The process environment, for tests and one-off runs.
Nothing here talks to the network; a missing secret just leaves that source unconfigured,
and the monitor reports it as unavailable instead of failing to start.
"""
import json
import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Mapping, Optional
DEFAULT_CONFIG_PATH = '/etc/thor/thor.json'
DEFAULT_ENV_DIR = '/etc/thor'
# Every check starts in shadow: it is evaluated and shown in Thor, and what it would have
# opened is logged, but nothing is sent to Tinker (thor#1, Area 5).
CHECK_MODES = ('off', 'shadow', 'live')
@dataclass
class DatabaseSettings:
host: str = ''
port: int = 3306
name: str = 'thor'
user: str = 'thor'
password: str = ''
@property
def configured(self) -> bool:
return bool(self.host and self.user and self.password)
@dataclass
class Settings:
prometheus_url: str = 'http://10.10.10.48:9090'
loki_url: str = 'http://10.10.10.69:3100'
# Any node answers for the whole cluster; Thor tries them in this order.
proxmox_nodes: List[str] = field(default_factory=lambda: [
'10.10.10.11', '10.10.10.10', '10.10.10.4', '10.10.10.2', '10.10.10.8', '10.10.10.9'])
proxmox_token_id: str = ''
proxmox_token_secret: str = ''
# Proxmox nodes use their self-signed cluster CA.
proxmox_verify_tls: bool = False
gandalf_url: str = 'http://10.10.10.61'
gandalf_api_key: str = ''
tinker_url: str = 'https://t.lotusguild.org/create_ticket_api.php'
tinker_api_key: str = ''
public_url: str = 'https://thor.lotusguild.org'
cycle_seconds: int = 120
catchup_hours: int = 24
# How many missed cycles before /health reports the monitor as stale.
stale_after_cycles: int = 3
http_timeout_s: float = 10.0
checks: Dict[str, str] = field(default_factory=dict)
database: DatabaseSettings = field(default_factory=DatabaseSettings)
# Machine keys for Thor's API (Gandalf's and hwmonDaemon's /covering pre-check): only the
# SHA-256 of each key is kept, like Gandalf's api_keys (gandalf#68).
api_keys: List[Dict] = field(default_factory=list)
# Requests through NPM carry Authelia's Remote-* headers. They are only displayed (the UI is
# read-only), and only believed from this proxy address.
trusted_proxy: str = '10.10.10.27'
def check_mode(self, name: str) -> str:
mode = self.checks.get(name, 'shadow')
return mode if mode in CHECK_MODES else 'shadow'
@property
def stale_after_s(self) -> int:
return self.cycle_seconds * self.stale_after_cycles
def parse_env_file(text: str) -> Dict[str, str]:
"""KEY=VALUE lines; blank lines and # comments ignored; optional surrounding quotes."""
out = {}
for raw in text.splitlines():
line = raw.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, value = line.split('=', 1)
key, value = key.strip(), value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in '"\'':
value = value[1:-1]
if key:
out[key] = value
return out
def read_env_dir(env_dir: str) -> Dict[str, str]:
values: Dict[str, str] = {}
path = Path(env_dir)
if not path.is_dir():
return values
for f in sorted(path.glob('*.env')):
try:
values.update(parse_env_file(f.read_text()))
except OSError:
continue
return values
def _as_bool(value) -> bool:
if isinstance(value, bool):
return value
return str(value).strip().lower() in ('1', 'true', 'yes', 'on')
def load(config_path: Optional[str] = None, env_dir: Optional[str] = None,
environ: Optional[Mapping[str, str]] = None) -> Settings:
config_path = config_path or os.environ.get('THOR_CONFIG', DEFAULT_CONFIG_PATH)
env_dir = env_dir or os.environ.get('THOR_ENV_DIR', DEFAULT_ENV_DIR)
environ = os.environ if environ is None else environ
s = Settings()
try:
with open(config_path) as f:
data = json.load(f)
except FileNotFoundError:
data = {}
for key in ('prometheus_url', 'loki_url', 'gandalf_url', 'tinker_url', 'public_url'):
if data.get(key):
setattr(s, key, str(data[key]).rstrip('/') if key != 'tinker_url' else str(data[key]))
for key in ('cycle_seconds', 'catchup_hours', 'stale_after_cycles'):
if key in data:
setattr(s, key, int(data[key]))
if 'http_timeout_s' in data:
s.http_timeout_s = float(data['http_timeout_s'])
if data.get('proxmox_nodes'):
s.proxmox_nodes = [str(n) for n in data['proxmox_nodes']]
if 'proxmox_verify_tls' in data:
s.proxmox_verify_tls = _as_bool(data['proxmox_verify_tls'])
if isinstance(data.get('api_keys'), list):
s.api_keys = [k for k in data['api_keys'] if isinstance(k, dict) and k.get('sha256')]
if data.get('trusted_proxy'):
s.trusted_proxy = str(data['trusted_proxy'])
if isinstance(data.get('checks'), dict):
s.checks = {str(k): str(v) for k, v in data['checks'].items()}
env = read_env_dir(env_dir)
env.update({k: v for k, v in environ.items() if k.isupper()})
s.proxmox_token_id = env.get('PVE_TOKEN_ID', s.proxmox_token_id)
s.proxmox_token_secret = env.get('PVE_TOKEN_SECRET', s.proxmox_token_secret)
s.gandalf_url = env.get('GANDALF_URL', s.gandalf_url).rstrip('/')
s.gandalf_api_key = env.get('GANDALF_API_KEY', s.gandalf_api_key)
s.tinker_url = env.get('TINKER_URL', s.tinker_url)
s.tinker_api_key = env.get('TINKER_API_KEY', s.tinker_api_key)
db = s.database
db.host = env.get('DB_HOST', db.host)
db.port = int(env.get('DB_PORT', db.port))
db.name = env.get('DB_NAME', db.name)
db.user = env.get('DB_USER', db.user)
db.password = env.get('DB_PASSWORD', db.password)
return s