176 lines
4.8 KiB
Python
176 lines
4.8 KiB
Python
import logging
|
|
import os
|
|
from dataclasses import dataclass
|
|
|
|
DEFAULT_LOG_PATH = "/root/threat-engine-agent/logs/threat-agent.log"
|
|
DEFAULT_STATE_FILE = "/root/threat-engine-agent/threat-agent-state.json"
|
|
DEFAULT_CHECK_INTERVAL = 600
|
|
DEFAULT_HEAL_VERIFY_DELAY = 5
|
|
DEFAULT_HEAL_MIN_INTERVAL = 900
|
|
DEFAULT_CONFIG_PATH = "config.yaml"
|
|
DEFAULT_NODE_NAME = "Unknown Node"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class RuntimeSettings:
|
|
node_name: str
|
|
log_path: str
|
|
state_file: str
|
|
check_interval: int
|
|
heal_verify_delay: int
|
|
heal_min_interval: int
|
|
config_path: str
|
|
|
|
|
|
def _parse_scalar(value):
|
|
value = value.strip()
|
|
if value.startswith(("'", '"')) and value.endswith(("'", '"')) and len(value) >= 2:
|
|
return value[1:-1]
|
|
if value.lower() == "true":
|
|
return True
|
|
if value.lower() == "false":
|
|
return False
|
|
try:
|
|
return int(value)
|
|
except ValueError:
|
|
return value
|
|
|
|
|
|
def _load_config_minimal(config_path):
|
|
"""
|
|
Minimal parser for simple two-level YAML mappings.
|
|
Supports the current config.yaml structure without external deps.
|
|
"""
|
|
config = {}
|
|
current_section = None
|
|
|
|
with open(config_path, "r") as f:
|
|
for raw_line in f:
|
|
line = raw_line.split("#", 1)[0].rstrip()
|
|
if not line.strip():
|
|
continue
|
|
|
|
if not line.startswith(" "):
|
|
if ":" not in line:
|
|
continue
|
|
key, value = line.split(":", 1)
|
|
key = key.strip()
|
|
value = value.strip()
|
|
if value == "":
|
|
config[key] = {}
|
|
current_section = key
|
|
else:
|
|
config[key] = _parse_scalar(value)
|
|
current_section = None
|
|
continue
|
|
|
|
if current_section is None:
|
|
continue
|
|
|
|
stripped = line.strip()
|
|
if stripped.startswith("- "):
|
|
continue
|
|
if ":" not in stripped:
|
|
continue
|
|
key, value = stripped.split(":", 1)
|
|
config[current_section][key.strip()] = _parse_scalar(value)
|
|
|
|
return config
|
|
|
|
|
|
def load_config(config_path):
|
|
"""
|
|
Loads YAML config when available. Falls back to empty config.
|
|
"""
|
|
try:
|
|
import yaml # Local import so runtime still works without PyYAML
|
|
except ImportError:
|
|
try:
|
|
return _load_config_minimal(config_path)
|
|
except FileNotFoundError:
|
|
return {}
|
|
except Exception as e:
|
|
logging.warning(f"Failed to read config file '{config_path}': {e}")
|
|
return {}
|
|
|
|
try:
|
|
with open(config_path, "r") as f:
|
|
return yaml.safe_load(f) or {}
|
|
except FileNotFoundError:
|
|
return {}
|
|
except Exception as e:
|
|
logging.warning(f"Failed to read config file '{config_path}': {e}")
|
|
return {}
|
|
|
|
|
|
def cfg_get(config, *keys, default=None):
|
|
cur = config
|
|
for key in keys:
|
|
if not isinstance(cur, dict):
|
|
return default
|
|
cur = cur.get(key)
|
|
return default if cur is None else cur
|
|
|
|
|
|
def as_int(value, default):
|
|
try:
|
|
return int(value)
|
|
except (TypeError, ValueError):
|
|
return default
|
|
|
|
|
|
def setup_logging(log_path):
|
|
os.makedirs(os.path.dirname(os.path.abspath(log_path)), exist_ok=True)
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
filename=log_path,
|
|
force=True,
|
|
)
|
|
|
|
|
|
def load_runtime_settings():
|
|
config_path = os.getenv("THREAT_AGENT_CONFIG", DEFAULT_CONFIG_PATH)
|
|
config = load_config(config_path)
|
|
|
|
node_name = os.getenv(
|
|
"SERVER_NAME",
|
|
cfg_get(config, "agent", "node_name", default=DEFAULT_NODE_NAME),
|
|
)
|
|
log_path = os.getenv(
|
|
"LOG_PATH",
|
|
cfg_get(config, "agent", "log_path", default=DEFAULT_LOG_PATH),
|
|
)
|
|
state_file = os.getenv(
|
|
"STATE_FILE",
|
|
cfg_get(config, "agent", "state_file", default=DEFAULT_STATE_FILE),
|
|
)
|
|
check_interval = as_int(
|
|
os.getenv("CHECK_INTERVAL", cfg_get(config, "agent", "check_interval")),
|
|
DEFAULT_CHECK_INTERVAL,
|
|
)
|
|
heal_verify_delay = as_int(
|
|
os.getenv(
|
|
"HEAL_VERIFY_DELAY",
|
|
cfg_get(config, "agent", "heal_verify_delay"),
|
|
),
|
|
DEFAULT_HEAL_VERIFY_DELAY,
|
|
)
|
|
heal_min_interval = as_int(
|
|
os.getenv(
|
|
"HEAL_MIN_INTERVAL",
|
|
cfg_get(config, "agent", "heal_min_interval"),
|
|
),
|
|
DEFAULT_HEAL_MIN_INTERVAL,
|
|
)
|
|
|
|
return RuntimeSettings(
|
|
node_name=node_name,
|
|
log_path=log_path,
|
|
state_file=state_file,
|
|
check_interval=check_interval,
|
|
heal_verify_delay=heal_verify_delay,
|
|
heal_min_interval=heal_min_interval,
|
|
config_path=config_path,
|
|
)
|