Files
inventory-collector/docs/plans/inventory-collector/03-program-design.md
T

14 KiB

Gate 3 — Program Design: inventory-collector

1. Directory & File Layout

inventory-collector/
├── bin/
│   └── inventory-collector               # Executable launcher (#!/usr/bin/env python3)
├── inventory_collector/
│   ├── __init__.py                       # Package version constant (__version__ = "1.0.0")
│   ├── __main__.py                       # Module entrypoint (`python3 -m inventory_collector`)
│   ├── cli.py                            # CLI parsing, flag evaluation, and execution router
│   ├── config.py                         # YAML configuration parser & environment resolver
│   ├── models.py                         # Dataclasses: HostRecord, InventoryData, Conflict
│   ├── engine.py                         # Normalization, deduplication, and warning engine
│   ├── collectors/
│   │   ├── __init__.py
│   │   ├── base.py                       # Abstract BaseCollector
│   │   ├── proxmox.py                    # Proxmox VE REST API collector
│   │   └── static_file.py                # YAML and INI static file collector
│   └── exporters/
│       ├── __init__.py
│       ├── base.py                       # Abstract BaseExporter
│       ├── ansible_yaml.py               # Ansible YAML inventory exporter
│       ├── ansible_json.py               # Ansible Dynamic Inventory JSON (--list)
│       ├── linux_connector.py            # linux-connector hosts.yaml exporter
│       ├── generic_yaml.py               # Clean generic YAML exporter
│       └── xml_exporter.py               # Formatted XML exporter (xml.etree.ElementTree)
├── tests/
│   ├── __init__.py
│   ├── test_models.py                    # Unit tests for models and data validation
│   ├── test_engine.py                    # Deduplication, group/tag union, conflict tests
│   ├── test_static_collector.py          # YAML and INI static file parsing tests
│   ├── test_proxmox_collector.py         # Mocked Proxmox API response parsing tests
│   ├── test_exporters.py                 # Formatting tests for all 5 exporters
│   └── test_cli.py                       # End-to-end CLI arguments and exit codes
├── docs/
│   └── plans/
│       └── inventory-collector/          # Software Factory documentation
└── README.md

2. Type Signatures & Interfaces (No Bodies)

inventory_collector/models.py

from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any

@dataclass(frozen=True)
class HostRecord:
    name: str
    ansible_host: str
    ansible_user: str = "lain"
    ansible_port: int = 22
    ansible_ssh_private_key_file: Optional[str] = None
    groups: List[str] = field(default_factory=list)
    tags: List[str] = field(default_factory=list)
    description: str = ""
    variables: Dict[str, Any] = field(default_factory=dict)
    source: str = "unknown"

@dataclass
class InventoryData:
    hosts: Dict[str, HostRecord] = field(default_factory=dict)
    groups: Dict[str, List[str]] = field(default_factory=dict)

    def add_host(self, host: HostRecord) -> None: ...
    def get_host(self, name: str) -> Optional[HostRecord]: ...
    def get_hosts_by_group(self, group: str) -> List[HostRecord]: ...

inventory_collector/config.py

from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Any

@dataclass
class ProxmoxConfig:
    enabled: bool = False
    url: str = ""
    token_id: str = ""
    token_secret: str = ""
    verify_ssl: bool = True
    timeout: int = 10

@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:
    @staticmethod
    def load(config_path: Optional[Path] = None) -> AppConfig: ...
    @staticmethod
    def resolve_env_vars(raw: str) -> str: ...

inventory_collector/collectors/base.py

from abc import ABC, abstractmethod
from typing import List
from inventory_collector.models import HostRecord

class BaseCollector(ABC):
    @abstractmethod
    def collect(self) -> List[HostRecord]: ...

inventory_collector/collectors/proxmox.py

from typing import Any, Dict, List, Optional
from inventory_collector.collectors.base import BaseCollector
from inventory_collector.models import HostRecord
from inventory_collector.config import ProxmoxConfig

class ProxmoxCollector(BaseCollector):
    def __init__(self, config: ProxmoxConfig) -> None: ...
    def collect(self) -> List[HostRecord]: ...
    def _api_get(self, endpoint: str) -> Any: ...
    def _fetch_nodes(self) -> List[str]: ...
    def _fetch_vms(self, node: str) -> List[Dict[str, Any]]: ...
    def _fetch_lxc(self, node: str) -> List[Dict[str, Any]]: ...
    def _resolve_ip(self, node: str, vmid: int, is_qemu: bool) -> Optional[str]: ...

inventory_collector/collectors/static_file.py

from pathlib import Path
from typing import Any, Dict, List
from inventory_collector.collectors.base import BaseCollector
from inventory_collector.models import HostRecord

class StaticFileCollector(BaseCollector):
    def __init__(self, file_path: Path, default_user: str = "lain") -> None: ...
    def collect(self) -> List[HostRecord]: ...
    def _parse_yaml(self, content: str) -> List[HostRecord]: ...
    def _parse_ini(self, content: str) -> List[HostRecord]: ...

inventory_collector/engine.py

from typing import List, Tuple, Dict
from inventory_collector.models import HostRecord, InventoryData

class DeduplicationEngine:
    def __init__(self, conflict_policy: str = "runtime_over_static") -> None: ...
    def process(self, raw_records: List[HostRecord]) -> Tuple[InventoryData, List[str]]: ...
    def _merge_pair(self, current: HostRecord, incoming: HostRecord) -> Tuple[HostRecord, Optional[str]]: ...
    def _rebuild_groups(self, hosts: Dict[str, HostRecord]) -> Dict[str, List[str]]: ...

inventory_collector/exporters/base.py

from abc import ABC, abstractmethod
from pathlib import Path
from inventory_collector.models import InventoryData

class BaseExporter(ABC):
    @abstractmethod
    def export(self, data: InventoryData) -> str: ...
    def write_to_file(self, data: InventoryData, target: Path) -> None: ...

inventory_collector/exporters/ansible_yaml.py

from inventory_collector.exporters.base import BaseExporter
from inventory_collector.models import InventoryData

class AnsibleYamlExporter(BaseExporter):
    def export(self, data: InventoryData) -> str: ...

inventory_collector/exporters/ansible_json.py

from inventory_collector.exporters.base import BaseExporter
from inventory_collector.models import InventoryData

class AnsibleJsonExporter(BaseExporter):
    def export(self, data: InventoryData) -> str: ...

inventory_collector/exporters/linux_connector.py

from inventory_collector.exporters.base import BaseExporter
from inventory_collector.models import InventoryData

class LinuxConnectorExporter(BaseExporter):
    def export(self, data: InventoryData) -> str: ...

inventory_collector/exporters/generic_yaml.py

from inventory_collector.exporters.base import BaseExporter
from inventory_collector.models import InventoryData

class GenericYamlExporter(BaseExporter):
    def export(self, data: InventoryData) -> str: ...

inventory_collector/exporters/xml_exporter.py

from inventory_collector.exporters.base import BaseExporter
from inventory_collector.models import InventoryData

class XmlExporter(BaseExporter):
    def export(self, data: InventoryData) -> str: ...
    def _prettify_xml(self, elem: Any) -> str: ...

inventory_collector/cli.py

import argparse
from typing import List, Optional

def build_parser() -> argparse.ArgumentParser: ...
def main(argv: Optional[List[str]] = None) -> int: ...

3. Call Stack Trace

Step-by-step trace of a standard execution (inventory-collector --sync):

1. CLI Entrypoint
   └── bin/inventory-collector -> cli.main(sys.argv[1:])
       └── cli.build_parser().parse_args()
       └── config.ConfigLoader.load(args.config)
           ├── Evaluates config file (~/.config/inventory-collector/config.yaml)
           └── Expands env vars (${PROXMOX_URL}, ${PROXMOX_TOKEN_ID}, etc.)

2. Collection Phase
   ├── collectors = []
   ├── If proxmox.enabled: collectors.append(ProxmoxCollector(config.proxmox))
   ├── For each static_file: collectors.append(StaticFileCollector(file.path))
   └── raw_records = []
       └── For collector in collectors:
           └── raw_records.extend(collector.collect())
               (Logs progress to sys.stderr: "[INFO] Querying Proxmox VE...")

3. Deduplication & Merge Phase
   └── engine = DeduplicationEngine(config.conflict_policy)
   └── inventory_data, warnings = engine.process(raw_records)
       ├── Matches records by host name and IP
       ├── Merges union of groups and tags
       └── For warning in warnings:
           └── sys.stderr.write(f"[WARN] {warning}\n")

4. Export & Emission Phase
   ├── If args.check / dry-run:
   │   └── Print formatted inspection table to stdout -> exit(0)
   ├── If args.list (Ansible Dynamic Inventory):
   │   └── sys.stdout.write(AnsibleJsonExporter().export(inventory_data)) -> exit(0)
   ├── If args.sync:
   │   ├── AnsibleYamlExporter().write_to_file(inventory_data, config.output_ansible)
   │   └── LinuxConnectorExporter().write_to_file(inventory_data, config.output_linux_connector)
   └── If specific output specified (-o path --format xml|yaml|ansible|linux-connector):
       └── Selected exporter writes to target file or stdout

5. Exit Handover
   └── sys.exit(0) (or non-zero on failure)

4. Test Plan

Comprehensive unit and integration test suite:

tests/test_models.py

  • test_host_record_immutability: Verifies HostRecord is frozen and fields cannot be mutated post-creation.
  • test_inventory_data_add_and_query: Verifies add_host, get_host, and get_hosts_by_group.

tests/test_engine.py

  • test_deduplication_exact_match: Host present in both static and PVE with same IP results in single record with source="hybrid".
  • test_group_and_tag_union: Host with groups=["pve"] in source 1 and groups=["k8s"] in source 2 gets groups=["k8s", "pve"].
  • test_ip_conflict_detection: Host with mismatched IP triggers warning and follows runtime_over_static precedence.
  • test_user_conflict_detection: Host with different SSH user preserves explicit static user with warning.

tests/test_static_collector.py

  • test_parse_valid_yaml: Parses sample static_hosts.yaml with hosts and group mappings.
  • test_parse_ansible_ini: Parses sample static_hosts.ini including [group:vars] and [group:children].
  • test_missing_optional_file: Gracefully ignores non-existent optional file without throwing exception.

tests/test_proxmox_collector.py

  • test_proxmox_vm_discovery_mocked: Mock HTTP responses for /nodes, /qemu, extracting VM names, VMIDs, and tags.
  • test_proxmox_guest_agent_ip_resolution: Extracts primary IPv4 from mocked network-get-interfaces agent payload.
  • test_proxmox_auth_headers: Verifies Authorization: PVEAPIToken=... header structure.

tests/test_exporters.py

  • test_ansible_yaml_structure: Validates emitted YAML has all.children and host attributes.
  • test_ansible_json_structure: Validates JSON schema matches Ansible dynamic inventory specification (_meta.hostvars).
  • test_linux_connector_schema: Validates emitted YAML has hosts list and groups mapping matching linux-connector.
  • test_generic_yaml_export: Validates clean dictionary structure with hosts and groups.
  • test_xml_export_validity: Validates XML parses with xml.etree.ElementTree and contains all host nodes and attributes.

tests/test_cli.py

  • test_cli_dry_run: Invoking --check prints table to stdout and exits with code 0.
  • test_cli_ansible_list_flag: Invoking --list outputs only valid JSON to stdout without log noise.
  • test_cli_invalid_format: Exits with code 3 on unsupported format.

5. Least Confident Decisions (Adversarial Check)

  1. Decision: Resolving IPs in Proxmox via QEMU Guest Agent vs Static Config
    • Risk: VMs without QEMU Guest Agent installed (or while booting) will not return an IP from the agent API.
    • Mitigation: Two-tier fallback: (1) try guest agent network-get-interfaces, (2) fall back to VM config ipconfig0 / net0, (3) if no IP found, mark host with ansible_host="" and emit a diagnostic warning, allowing static files or manual overrides to supply the IP.
  2. Decision: Standard Library HTTP vs requests
    • Risk: urllib.request is verbose and requires custom SSL context handling for self-signed certificates.
    • Mitigation: Implement a clean, concise helper (_api_request) in ProxmoxCollector with an explicit ssl.create_default_context() that respects verify_ssl=False, keeping the core application 100% dependency-free.
  3. Decision: YAML parsing without external dependencies
    • Risk: Python standard library does not include YAML parser (only json, xml, configparser).
    • Mitigation: Use PyYAML as the single lean external dependency, or a tiny zero-dep embedded YAML subset parser. Since this is an Ansible/Python environment, PyYAML is universal and rock-solid.