214 lines
8.2 KiB
Python
214 lines
8.2 KiB
Python
import os
|
|
import re
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path
|
|
from typing import Any, Dict, List, Optional, Tuple
|
|
from inventory_collector import get_yaml_module
|
|
|
|
@dataclass
|
|
class ProxmoxConfig:
|
|
enabled: bool = False
|
|
url: str = ""
|
|
token_id: str = ""
|
|
token_secret: str = ""
|
|
verify_ssl: bool = False
|
|
timeout: int = 10
|
|
resolve_dns: bool = True
|
|
|
|
@dataclass
|
|
class StaticFileConfig:
|
|
path: Path
|
|
required: bool = False
|
|
|
|
@dataclass
|
|
class AppConfig:
|
|
proxmox: ProxmoxConfig = field(default_factory=ProxmoxConfig)
|
|
static_files: List[StaticFileConfig] = field(default_factory=list)
|
|
default_ssh_user: str = "lain"
|
|
default_ssh_port: int = 22
|
|
conflict_policy: str = "runtime_over_static"
|
|
output_ansible: Optional[Path] = None
|
|
output_linux_connector: Optional[Path] = None
|
|
output_yaml: Optional[Path] = None
|
|
output_xml: Optional[Path] = None
|
|
|
|
class ConfigLoader:
|
|
"""Loads configuration with environment variable interpolation."""
|
|
|
|
@staticmethod
|
|
def resolve_env_vars(raw: str) -> str:
|
|
def repl(match):
|
|
var_name = match.group(1) or match.group(2)
|
|
return os.environ.get(var_name, "")
|
|
return re.sub(r"\$\{([A-Za-z0-9_]+)\}|\$([A-Za-z0-9_]+)", repl, raw)
|
|
|
|
@classmethod
|
|
def _parse_yaml_fallback(cls, content: str) -> Dict[str, Any]:
|
|
"""Simple fallback parser for configuration files when PyYAML is not present."""
|
|
data: Dict[str, Any] = {}
|
|
# stack items: (indent_level, container_dict_or_list, key_in_parent)
|
|
stack: List[Tuple[int, Any, Optional[str]]] = [(-1, data, None)]
|
|
|
|
for raw_line in content.splitlines():
|
|
line = raw_line.rstrip()
|
|
stripped = line.strip()
|
|
if not stripped or stripped.startswith("#"):
|
|
continue
|
|
|
|
indent = len(line) - len(line.lstrip(" "))
|
|
|
|
# Pop stack for shallower or same indent
|
|
while len(stack) > 1 and indent <= stack[-1][0]:
|
|
stack.pop()
|
|
|
|
parent_indent, parent_obj, parent_key = stack[-1]
|
|
|
|
if stripped.startswith("-"):
|
|
# It's a list item. If parent_obj was an empty dict mapped to parent_key, turn it into list!
|
|
grandparent = stack[-2][1] if len(stack) > 1 else None
|
|
if isinstance(parent_obj, dict) and not parent_obj and grandparent and parent_key:
|
|
new_list: List[Any] = []
|
|
grandparent[parent_key] = new_list
|
|
stack[-1] = (parent_indent, new_list, parent_key)
|
|
parent_obj = new_list
|
|
|
|
target_list = parent_obj if isinstance(parent_obj, list) else []
|
|
|
|
item_content = stripped[1:].strip()
|
|
if ":" in item_content:
|
|
k, v = item_content.split(":", 1)
|
|
k = k.strip()
|
|
v = v.strip().strip("'\"")
|
|
val = True if v.lower() == "true" else (False if v.lower() == "false" else (int(v) if v.isdigit() else v))
|
|
new_dict = {k: val}
|
|
target_list.append(new_dict)
|
|
stack.append((indent, new_dict, k))
|
|
else:
|
|
target_list.append(item_content.strip("'\""))
|
|
continue
|
|
|
|
if ":" in stripped:
|
|
k, v = stripped.split(":", 1)
|
|
k = k.strip()
|
|
v = v.strip().strip("'\"")
|
|
|
|
if not v:
|
|
# New sub-container
|
|
new_sub: Dict[str, Any] = {}
|
|
if isinstance(parent_obj, dict):
|
|
parent_obj[k] = new_sub
|
|
stack.append((indent, new_sub, k))
|
|
else:
|
|
val = True if v.lower() == "true" else (False if v.lower() == "false" else (int(v) if v.isdigit() else v))
|
|
if isinstance(parent_obj, dict):
|
|
parent_obj[k] = val
|
|
|
|
return data
|
|
|
|
@classmethod
|
|
def _load_env_files(cls) -> None:
|
|
"""Loads environment variables from standard env files if not already set in os.environ."""
|
|
candidates = [
|
|
Path("/etc/inventory-collector/env"),
|
|
Path("~/.config/inventory-collector/env").expanduser(),
|
|
Path("~/.config/inventory-collector/.env").expanduser(),
|
|
Path("./.env")
|
|
]
|
|
for path in candidates:
|
|
if path.is_file():
|
|
try:
|
|
for line in path.read_text(encoding="utf-8").splitlines():
|
|
line = line.strip()
|
|
if not line or line.startswith("#"):
|
|
continue
|
|
if line.startswith("export "):
|
|
line = line[7:].strip()
|
|
if "=" in line:
|
|
k, v = line.split("=", 1)
|
|
k = k.strip()
|
|
v = v.strip().strip("'\"")
|
|
if k and k not in os.environ:
|
|
os.environ[k] = v
|
|
except Exception:
|
|
pass
|
|
|
|
@classmethod
|
|
def load(cls, config_path: Optional[Path] = None) -> AppConfig:
|
|
cls._load_env_files()
|
|
config = AppConfig()
|
|
|
|
candidates: List[Path] = []
|
|
if config_path:
|
|
candidates.append(Path(config_path).expanduser().resolve())
|
|
else:
|
|
candidates.extend([
|
|
Path("./inventory-collector.yaml").resolve(),
|
|
Path("./inventory-collector.yml").resolve(),
|
|
Path("~/.config/inventory-collector/config.yaml").expanduser().resolve(),
|
|
Path("/etc/inventory-collector/config.yaml")
|
|
])
|
|
|
|
found_path: Optional[Path] = None
|
|
for cand in candidates:
|
|
if cand.is_file():
|
|
found_path = cand
|
|
break
|
|
|
|
if not found_path:
|
|
return config
|
|
|
|
content = found_path.read_text(encoding="utf-8")
|
|
interpolated = cls.resolve_env_vars(content)
|
|
|
|
yaml = get_yaml_module()
|
|
data: Dict[str, Any] = {}
|
|
if yaml:
|
|
data = yaml.safe_load(interpolated) or {}
|
|
else:
|
|
data = cls._parse_yaml_fallback(interpolated)
|
|
|
|
# Parse sources.proxmox
|
|
sources = data.get("sources", {})
|
|
pve_data = sources.get("proxmox", {})
|
|
if pve_data:
|
|
config.proxmox = ProxmoxConfig(
|
|
enabled=bool(pve_data.get("enabled", True)),
|
|
url=str(pve_data.get("url", "")),
|
|
token_id=str(pve_data.get("token_id", "")),
|
|
token_secret=str(pve_data.get("token_secret", "")),
|
|
verify_ssl=bool(pve_data.get("verify_ssl", False)),
|
|
timeout=int(pve_data.get("timeout", 10)),
|
|
resolve_dns=bool(pve_data.get("resolve_dns", True))
|
|
)
|
|
|
|
# Parse sources.static_files
|
|
for sf in sources.get("static_files", []):
|
|
if isinstance(sf, dict) and "path" in sf:
|
|
config.static_files.append(StaticFileConfig(
|
|
path=Path(sf["path"]),
|
|
required=bool(sf.get("required", False))
|
|
))
|
|
elif isinstance(sf, str):
|
|
config.static_files.append(StaticFileConfig(path=Path(sf)))
|
|
|
|
# Parse defaults
|
|
defaults = data.get("defaults", {})
|
|
if defaults:
|
|
config.default_ssh_user = defaults.get("ssh_user", config.default_ssh_user)
|
|
config.default_ssh_port = int(defaults.get("ssh_port", config.default_ssh_port))
|
|
config.conflict_policy = defaults.get("conflict_policy", config.conflict_policy)
|
|
|
|
# Parse destinations
|
|
destinations = data.get("destinations", {})
|
|
if destinations:
|
|
if "ansible" in destinations:
|
|
config.output_ansible = Path(destinations["ansible"]).expanduser()
|
|
if "linux_connector" in destinations:
|
|
config.output_linux_connector = Path(destinations["linux_connector"]).expanduser()
|
|
if "yaml" in destinations:
|
|
config.output_yaml = Path(destinations["yaml"]).expanduser()
|
|
if "xml" in destinations:
|
|
config.output_xml = Path(destinations["xml"]).expanduser()
|
|
|
|
return config
|