From 937acc2548369f84aedd47dbbd0d60afda8ff33b Mon Sep 17 00:00:00 2001 From: Mateusz Stomski Date: Sat, 3 Oct 2026 08:04:56 +0200 Subject: [PATCH] docs: complete 4-gate workflow planning for inventory-collector --- .gitignore | 49 +++ README.md | 23 ++ docs/plans/inventory-collector/00-status.md | 20 ++ docs/plans/inventory-collector/01-spec.md | 119 +++++++ .../inventory-collector/02-architecture.md | 297 ++++++++++++++++ .../inventory-collector/03-program-design.md | 331 ++++++++++++++++++ docs/plans/inventory-collector/04-slices.md | 75 ++++ 7 files changed, 914 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 docs/plans/inventory-collector/00-status.md create mode 100644 docs/plans/inventory-collector/01-spec.md create mode 100644 docs/plans/inventory-collector/02-architecture.md create mode 100644 docs/plans/inventory-collector/03-program-design.md create mode 100644 docs/plans/inventory-collector/04-slices.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9796ee3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,49 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# Virtual environments +venv/ +.venv/ +ENV/ +env/ + +# IDE & OS +.DS_Store +.vscode/ +.idea/ +*.swp +*.swo + +# Testing & coverage +.pytest_cache/ +.coverage +htmlcov/ + +# Local sensitive configuration overrides +config.local.yaml +*.secret.yaml diff --git a/README.md b/README.md new file mode 100644 index 0000000..8bd15ac --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# Inventory Collector (`inventory-collector`) + +Universal homelab and fleet inventory collector and deduplicator for Ansible and `linux-connector`. + +## Overview + +`inventory-collector` queries infrastructure sources (Proxmox VE REST API, static YAML/INI files), normalizes and deduplicates host records in memory, and generates unified inventory files for: +- **Ansible:** Playbook execution (`-i hosts.yaml`) and dynamic inventory mode (`--list`). +- **`linux-connector`:** Interactive TUI fuzzy launcher and fleet command runner (`hosts.yaml`). +- **Standard Exports:** Clean generic YAML and formatted XML for external tooling and CMDBs. + +## Architecture & Plans + +The project follows the Software Factory 4-Gate Workflow: +- [00-status.md](docs/plans/inventory-collector/00-status.md) — Implementation status and slice progress. +- [01-spec.md](docs/plans/inventory-collector/01-spec.md) — Product specification and CLI interfaces. +- [02-architecture.md](docs/plans/inventory-collector/02-architecture.md) — Technical architecture and data models. +- [03-program-design.md](docs/plans/inventory-collector/03-program-design.md) — Program design, signatures, and test plan. +- [04-slices.md](docs/plans/inventory-collector/04-slices.md) — Vertical slice execution plan. + +## License + +MIT diff --git a/docs/plans/inventory-collector/00-status.md b/docs/plans/inventory-collector/00-status.md new file mode 100644 index 0000000..f06e280 --- /dev/null +++ b/docs/plans/inventory-collector/00-status.md @@ -0,0 +1,20 @@ +# Status: inventory-collector + +- Gate 1 — Spec & Product: APPROVED 2026-10-03 +- Gate 2 — Architecture: APPROVED 2026-10-03 +- Gate 3 — Program Design: APPROVED 2026-10-03 +- Gate 4 — Slice Plan: APPROVED 2026-10-03 + +## Slices +- [ ] Slice 1 — tracer bullet: Minimal end-to-end pipeline (CLI, basic models, static reader, YAML output) +- [ ] Slice 2 — Robust static file collector (YAML & INI) and Ansible exporters (YAML & JSON --list) +- [ ] Slice 3 — Proxmox VE REST API collector with token auth and guest agent IP resolution +- [ ] Slice 4 — In-memory deduplication and conflict resolution engine with stderr warnings +- [ ] Slice 5 — Extended exporters (linux-connector, Generic YAML, XML) and --sync flag +- [ ] Slice 6 — Configuration file (config.yaml), CLI check mode (--check), and documentation + +## Notes for a fresh session +- Project: Universal homelab and fleet inventory collector and deduplicator. +- Consumers: Ansible (playbooks & Gitea Actions), linux-connector (fleet connection & runner). +- Key principle: Avoid overengineering. Read sources, merge & deduplicate in memory, emit clean inventory file. +- Remote repo: Public on Gitea (https://gitea.wired.synology.me/soda64/inventory-collector). diff --git a/docs/plans/inventory-collector/01-spec.md b/docs/plans/inventory-collector/01-spec.md new file mode 100644 index 0000000..a586839 --- /dev/null +++ b/docs/plans/inventory-collector/01-spec.md @@ -0,0 +1,119 @@ +# Gate 1 — Spec & Product: inventory-collector + +## 1. Problem Statement +Homelab operators and sysadmins run infrastructure across heterogeneous environments: +- Hypervisors (Proxmox VE with dozens of virtual machines and LXC containers), +- Bare-metal appliances and unmanaged hardware (NAS, managed switches, routers, jump hosts), +- Container orchestration nodes (K3s / Kubernetes clusters). + +Today, maintaining inventory of these machines is heavily fragmented and manual: +1. Static files (such as `static_hosts.ini`) become outdated as soon as new VMs are created, destroyed, or receive new IP addresses. +2. Separate tools maintain duplicate, divergent lists: Ansible requires its own inventory, connection managers (like `linux-connector`) require their own host list, and CI/CD pipelines require separate inventory files. +3. When the same server is defined in multiple places (e.g. in a static file for legacy reasons and discovered dynamically via Proxmox API), tools either duplicate the host, fail with ambiguous errors, or silently use stale parameters. + +`inventory-collector` solves this by acting as a single, lightweight command-line utility that collects hosts from all configured homelab sources, merges them in memory, warns operators of any duplicates or IP conflicts, and generates a unified, standard inventory ready for immediate use by Ansible, `linux-connector`, and CI/CD automation. + +--- + +## 2. Measurable Success Criteria +1. **Single Command Generation:** Running a single command generates a complete, validated inventory for a homelab environment (50+ hosts) in under **500 milliseconds** (from local/cached sources) or under **2 seconds** (including live Proxmox API network queries). +2. **100% Ansible Interoperability:** Generated inventory passes `ansible-inventory -i --graph` and `ansible-inventory -i --list` with zero syntax errors or warnings. +3. **100% linux-connector Interoperability:** The exact same output (or simultaneously generated `hosts.yaml`) can be loaded by `linux-connector` without transformation, enabling immediate fuzzy search and fleet execution across all discovered nodes and groups. +4. **Deterministic Deduplication & Conflict Detection:** + - 0 duplicate host records in the output even if the same machine is present in both static files and Proxmox. + - Any conflicting definition (such as mismatched IP addresses or conflicting SSH users for the same host identifier) emits a clear, human-readable warning on standard error without crashing the process. +5. **Zero Complex Dependencies:** Operates out-of-the-box on standard Linux workstations, macOS, and lightweight CI/CD runner environments without requiring external databases or heavy service daemons. + +--- + +## 3. Announcement & User Stories + +### Announcement +> "Introducing `inventory-collector` — the single source of truth for homelab and fleet inventory. Stop manually maintaining separate host lists across Ansible, SSH managers, and CI/CD. `inventory-collector` dynamically queries your hypervisors and static definitions, deduplicates host records with smart conflict warnings, and generates unified inventory files for Ansible and `linux-connector` in a single command." + +### User Stories +- **As a homelab administrator**, I want to add or clone a new VM in Proxmox and run `inventory-collector`, so that the new machine is instantly accessible in `linux-connector` and available for Ansible playbooks without touching any static config files. +- **As a DevOps engineer**, I want `inventory-collector` to run in my Gitea Actions CI/CD pipeline before executing Ansible playbooks, ensuring my deployment runs against the real-time state of the cluster. +- **As a sysadmin**, I want to define non-Proxmox devices (like Synology NAS and home routers) in a simple static YAML or INI file and have them automatically merged into the fleet inventory with their proper groups and tags. +- **As an operator**, I want to be warned if a static file still lists an old IP for a host that Proxmox reports with a different IP, so that I can easily spot and fix network configuration drift. + +--- + +## 4. CLI Experience & User Interfaces + +`inventory-collector` is a command-line application designed for both interactive terminal use and headless automation in scripts and CI/CD pipelines. + +### Primary Commands & Modes + +#### 1. Standard Generation (Default) +Generates the inventory file and writes it to disk or stdout: +```text +$ inventory-collector +[INFO] Querying Proxmox VE (3 nodes, 18 VMs/LXCs found)... +[INFO] Reading static file '/etc/inventory-collector/static_hosts.yaml' (4 hosts found)... +[WARN] Duplicate host 'k3s-master-0' found in static file and Proxmox API (IP: 192.168.5.70). Merged tags and groups. +[SUCCESS] Generated unified inventory with 21 unique hosts across 6 groups -> /etc/ansible/hosts.yaml +``` + +#### 2. Writing to Custom Destination or linux-connector Path +```text +$ inventory-collector -o ~/.config/linux-connector/hosts.yaml --format linux-connector +[INFO] Discovered 21 hosts. +[SUCCESS] Written linux-connector inventory to ~/.config/linux-connector/hosts.yaml +``` + +#### 3. Dual Export (Ansible + linux-connector simultaneously) +A single run can update both targets at once: +```text +$ inventory-collector --sync +[INFO] Collecting from all configured sources... +[SUCCESS] Updated Ansible inventory: /etc/ansible/hosts.yaml +[SUCCESS] Updated linux-connector inventory: ~/.config/linux-connector/hosts.yaml +``` + +#### 4. Dry-Run / Inspection Mode (`--check` / `--dry-run`) +Prints a clean tabular summary of discovered hosts, groups, and any warnings to the terminal without modifying any files: +```text +$ inventory-collector --check +======================== Discovered Inventory ======================== +NAME IP ADDRESS SOURCE GROUPS TAGS +node0 192.168.0.101 Proxmox proxmox_nodes pve, hypervisor +k3s-master-0 192.168.5.70 Hybrid* k3s_master, k3s control-plane, terraform +tool-server-1 192.168.5.61 Proxmox tool_servers debian, utility +synology-nas 192.168.0.2 Static storage, external nas, btrfs +---------------------------------------------------------------------- +Total hosts: 21 | Groups: 6 | Duplicates merged: 1 | Conflicts: 0 +====================================================================== +* Hybrid indicates host was present in multiple sources and successfully merged. +``` + +#### 5. Ansible Executable Dynamic Inventory Mode (`--list`) +Supports running directly as an Ansible dynamic inventory script: +```text +$ ansible-playbook -i /usr/local/bin/inventory-collector playbooks/site.yml +``` +When invoked by Ansible with `--list`, it writes valid Ansible Dynamic Inventory JSON with `_meta.hostvars` directly to stdout and suppresses all informational logs from stdout (sending warnings/diagnostics only to stderr). + +--- + +## 5. Conflict Resolution & Warning Discipline + +When merging records from multiple sources, `inventory-collector` follows strict, predictable rules: +1. **Host Identity Matching:** Hosts are matched first by canonical hostname/name, and second by primary IPv4 address. +2. **Additive Attributes (Union):** Groups and tags from all matching sources are merged together without duplicates. +3. **Attribute Discrepancies (Warnings):** + - If Source A and Source B specify different IP addresses for the same hostname: + `[WARN] IP conflict for host 'alma-crash': Proxmox reports '192.168.5.51', static file specifies '192.168.5.99'. Using Proxmox runtime IP.` + - If Source A and Source B specify different SSH usernames: + `[WARN] User conflict for host 'node0': Proxmox default is 'lain', static file specifies 'root'. Using static file.` +4. **Clean Stdio Separation:** + - Standard output (`stdout`) is reserved strictly for inventory payloads when piping or in `--list` mode. + - All human-facing progress messages, warnings, and error logs are written to standard error (`stderr`). + +--- + +## 6. Non-Goals & Boundaries (Keeping it Lean) +1. **No SSH connection execution:** `inventory-collector` does NOT open SSH connections, manage TTYs, or execute remote commands. That is the explicit role of `linux-connector` and `ansible`. +2. **No state management or orchestration:** It does NOT create, destroy, or modify VMs. That is the role of `terraform` and `proxmox`. +3. **No daemon or background service:** It is a fast, stateless CLI utility executed on demand, on a cron schedule, or as part of CI/CD pipelines. +4. **No heavy database backend:** All collection, deduplication, and file generation happens in-memory with sub-second execution. diff --git a/docs/plans/inventory-collector/02-architecture.md b/docs/plans/inventory-collector/02-architecture.md new file mode 100644 index 0000000..1e9f61a --- /dev/null +++ b/docs/plans/inventory-collector/02-architecture.md @@ -0,0 +1,297 @@ +# Gate 2 — Architecture: inventory-collector + +## 1. System Fit & Architecture Diagram + +`inventory-collector` is a modular, pipeline-oriented CLI utility written in Python 3. It decouples data collection from output generation through a normalized, in-memory intermediate representation. + +```text + ┌─────────────────────────┐ + │ CLI & Config │ + │ (argparse / config.py) │ + └────────────┬────────────┘ + │ + ▼ + ┌─────────────────────────┐ + │ Collector Registry │ + └──────┬───────────┬──────┘ + │ │ + ┌────────────────────┴─────┐ └───────────────────────────┐ + ▼ ▼ ▼ + ┌──────────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐ + │ ProxmoxCollector │ │ StaticFileCollector │ │ (Future Collectors) │ + │ - Nodes query │ │ - YAML parser │ │ - K3s/K8s nodes │ + │ - QEMU VMs & LXCs │ │ - INI parser │ │ - Terraform state │ + │ - Guest Agent IPs │ │ │ │ │ + └──────────┬───────────┘ └──────────┬───────────┘ └──────────┬───────────┘ + │ │ │ + └────────────────────┬─────┴─────────────────────────────────┘ + │ Raw HostRecords + ▼ + ┌───────────────────────────┐ + │ Deduplication Engine │ + │ - Identity Matching │ + │ - Tag & Group Union │ + │ - Conflict Warnings │ + └─────────────┬─────────────┘ + │ Normalized InventoryData + ▼ + ┌───────────────────────────┐ + │ Exporter Engine │ + └──────┬─────────────┬──────┘ + │ │ + ┌─────────────┴─────┐ └─────────────────────────────────┐ + ▼ ▼ ▼ + ┌──────────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐ + │ AnsibleYamlExporter │ │ AnsibleJsonExporter │ │ XmlExporter │ + │ (ansible inventory) │ │ (--list / CI) │ │ (standard XML) │ + └──────────────────────┘ └──────────────────────┘ └──────────────────────┘ + │ │ + ▼ ▼ + ┌──────────────────────┐ ┌──────────────────────┐ + │ LinuxConnectorExport │ │ GenericYamlExporter │ + │ (hosts.yaml) │ │ (clean plain YAML) │ + └──────────────────────┘ └──────────────────────┘ +``` + +--- + +## 2. In-Memory Data Models & Contract + +The pipeline uses strongly typed, immutable dataclasses for intermediate representation (`models.py`): + +### `HostRecord` +```python +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Any + +@dataclass +class HostRecord: + name: str # Unique canonical identifier (e.g. "k3s-master-0") + ansible_host: str # Primary IPv4/IPv6 address or resolvable FQDN + ansible_user: str = "lain" # Default SSH user + ansible_port: int = 22 # SSH port + 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" # "proxmox", "static", "hybrid" +``` + +### `InventoryData` +```python +@dataclass +class InventoryData: + hosts: Dict[str, HostRecord] = field(default_factory=dict) # Keyed by canonical name + groups: Dict[str, List[str]] = field(default_factory=dict) # group_name -> list of host names +``` + +--- + +## 3. Data Sources (Collectors) + +All collectors implement a uniform interface (`BaseCollector`): + +```python +class BaseCollector: + def collect(self) -> List[HostRecord]: + raise NotImplementedError +``` + +### A. `ProxmoxCollector` +- **Transport:** HTTP REST calls using Python standard library (`urllib.request` / `json` / `ssl`) or `requests`. +- **Endpoints:** + 1. `GET /api2/json/nodes` — lists hypervisor nodes (`node0`, `node1`, `node2`). + 2. `GET /api2/json/nodes/{node}/qemu` — lists virtual machines. + 3. `GET /api2/json/nodes/{node}/lxc` — lists LXC containers. + 4. `GET /api2/json/nodes/{node}/qemu/{vmid}/agent/network-get-interfaces` — retrieves real-time IP from QEMU Guest Agent (falls back to `config` / `ipconfig0` if agent is offline). +- **Extracted Attributes:** + - `name`: VM/CT name. + - `ansible_host`: Primary non-loopback IPv4. + - `groups`: Derived from Proxmox tags (e.g. `tag:k3s_master` -> group `k3s_master`, plus base group `proxmox_vms` or `proxmox_lxc`). + - `variables`: `proxmox_vmid`, `proxmox_node`, `proxmox_status` (running/stopped). + +### B. `StaticFileCollector` +- **Supported Formats:** + - YAML (`.yaml` / `.yml`): Parses structured host maps and group lists. + - INI (`.ini`): Parses standard Ansible INI sections (`[group]`, `[group:vars]`, `[group:children]`). +- **Use Case:** Physical appliances not present in PVE (Synology NAS, smart switches, internet gateways). + +--- + +## 4. Deduplication & Conflict Resolution Engine + +The deduplication engine processes raw `HostRecord` instances into a clean `InventoryData` structure: + +### Algorithm +1. **Primary Keying:** + - Look up existing records by `name` (case-insensitive). + - Secondary check: verify if an existing record shares the same `ansible_host` IP under a different alias. +2. **Merging Matching Records:** + - **Groups:** Merged as a mathematical union (set operation): `merged.groups = sorted(list(set(r1.groups + r2.groups)))`. + - **Tags:** Merged as a union: `merged.tags = sorted(list(set(r1.tags + r2.tags)))`. + - **Source:** Marked as `"hybrid"` when collected from multiple sources. +3. **Conflict Detection & Reporting (Warnings to `stderr`):** + - **IP Conflict:** If `r1.ansible_host != r2.ansible_host`: + - Default rule (`runtime_over_static`): The Proxmox runtime IP takes precedence, but an explicit warning is logged: + `[WARN] IP conflict for host '{name}': Proxmox ({ip1}) != Static ({ip2}). Using Proxmox runtime IP.` + - **User Conflict:** If `r1.ansible_user != r2.ansible_user`: + - Static file explicit user takes precedence over Proxmox default (`lain`), with warning logged: + `[WARN] SSH user conflict for host '{name}': Proxmox default ({u1}) != Static ({u2}). Using '{u2}'.` +4. **Group Inversion:** + - Populates `inventory.groups[group_name] = [host_names...]` ensuring bidirectional consistency. + +--- + +## 5. Exporters (Output Formats) + +### A. `AnsibleYamlExporter` +Outputs standard Ansible YAML inventory conforming to Ansible 2.9+: +```yaml +all: + children: + proxmox_nodes: + hosts: + node0: + ansible_host: 192.168.0.101 + ansible_user: root + k3s_cluster: + children: + k3s_master: + hosts: + k3s-master-0: + ansible_host: 192.168.5.70 + ansible_user: lain + proxmox_vmid: 12005070 +``` + +### B. `AnsibleJsonExporter` (`--list`) +Outputs standard Ansible Dynamic Inventory JSON for CLI execution (`ansible-playbook -i ./inventory-collector`): +```json +{ + "_meta": { + "hostvars": { + "k3s-master-0": { + "ansible_host": "192.168.5.70", + "ansible_user": "lain" + } + } + }, + "all": { + "children": ["k3s_cluster", "proxmox_nodes"] + }, + "k3s_master": { + "hosts": ["k3s-master-0"] + } +} +``` + +### C. `LinuxConnectorExporter` +Outputs the exact schema expected by `linux-connector` (`hosts.yaml`): +```yaml +hosts: + - name: k3s-master-0 + hostname: 192.168.5.70 + user: lain + port: 22 + groups: + - k3s_cluster + - k3s_master + tags: + - control-plane + - proxmox +groups: + k3s_master: + - k3s-master-0 +``` + +### D. `GenericYamlExporter` +Outputs a clean, human-readable generic YAML inventory (free of Ansible-specific wrappers) suitable for scripting, custom pipelines, and general tooling: +```yaml +hosts: + - name: k3s-master-0 + ip: 192.168.5.70 + user: lain + port: 22 + groups: [k3s_cluster, k3s_master] + tags: [control-plane, proxmox] + source: hybrid +groups: + k3s_master: + - k3s-master-0 +``` + +### E. `XmlExporter` +Outputs a well-formed, pretty-printed XML document using Python's standard library (`xml.etree.ElementTree` / `minidom`), ideal for legacy tooling, CMDBs, monitoring systems, and automated XML ingestion: +```xml + + + + + + k3s_cluster + k3s_master + + + control-plane + proxmox + + + 12005070 + + + + + + k3s-master-0 + + + +``` + +--- + +## 6. Configuration & Secret Management + +- **Zero-Secrets Policy:** No plain-text passwords or tokens are stored in configuration files. +- **Config file:** `~/.config/inventory-collector/config.yaml` (user) or `/etc/inventory-collector/config.yaml` (system), with fallback to local `./inventory-collector.yaml`. +- **Environment Variables:** + - `PROXMOX_URL` (e.g. `https://pve-01.wired.intra:8006`) + - `PROXMOX_TOKEN_ID` (e.g. `root@pam!inventory-collector`) + - `PROXMOX_TOKEN_SECRET` (token UUID / secret) + - `PROXMOX_VERIFY_SSL` (default: `true`, can be set to `false` for self-signed certificates) + +### Configuration Schema Example (`config.yaml`) +```yaml +sources: + proxmox: + enabled: true + url: "${PROXMOX_URL}" + token_id: "${PROXMOX_TOKEN_ID}" + token_secret: "${PROXMOX_TOKEN_SECRET}" + verify_ssl: false + static_files: + - path: "~/.config/inventory-collector/static_hosts.yaml" + required: false + +defaults: + ssh_user: "lain" + ssh_port: 22 + conflict_policy: "runtime_over_static" + +destinations: + ansible: "inventory/hosts.yaml" + linux_connector: "~/.config/linux-connector/hosts.yaml" +``` + +--- + +## 7. Exit Codes & Error Discipline + +| Code | Name | Meaning | +|---|---|---| +| `0` | `SUCCESS` | Inventory successfully collected, merged, and emitted. | +| `1` | `RUNTIME_ERROR` | Unhandled runtime exception or missing critical resource. | +| `2` | `SOURCE_UNREACHABLE`| Proxmox API unreachable or network timeout. | +| `3` | `CONFIG_ERROR` | Invalid YAML/JSON syntax in config file or static inventory. | +| `4` | `VALIDATION_FAILED`| Host conflict could not be resolved or invalid host structure. | diff --git a/docs/plans/inventory-collector/03-program-design.md b/docs/plans/inventory-collector/03-program-design.md new file mode 100644 index 0000000..59ec768 --- /dev/null +++ b/docs/plans/inventory-collector/03-program-design.md @@ -0,0 +1,331 @@ +# Gate 3 — Program Design: inventory-collector + +## 1. Directory & File Layout + +```text +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` +```python +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` +```python +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` +```python +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` +```python +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` +```python +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` +```python +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` +```python +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` +```python +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` +```python +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` +```python +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` +```python +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` +```python +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` +```python +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`): + +```text +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. diff --git a/docs/plans/inventory-collector/04-slices.md b/docs/plans/inventory-collector/04-slices.md new file mode 100644 index 0000000..b7a5abd --- /dev/null +++ b/docs/plans/inventory-collector/04-slices.md @@ -0,0 +1,75 @@ +# Gate 4 — Vertical Slice Plan: inventory-collector + +The implementation is broken down into 6 thin, verifiable vertical slices. Each slice cuts across all layers (models, logic, CLI, and tests), ensuring runnable code and instant verification at every checkpoint. + +--- + +## Slice 1: Tracer Bullet (Minimal End-to-End Pipeline) +- **Scope:** + - Create package skeleton: `inventory_collector/__init__.py`, `models.py`, `cli.py`, `bin/inventory-collector`. + - Implement minimal `HostRecord` and `InventoryData` dataclasses. + - Implement a basic static host reader and minimal YAML exporter. + - Wire CLI arguments to execute the end-to-end pipeline and emit valid YAML. +- **Test / Verification:** + - Unit test verifying basic model creation and export. + - Shell execution test: `./bin/inventory-collector` outputs a valid YAML inventory to stdout. + +--- + +## Slice 2: Full Static File Collector & Ansible Exporters +- **Scope:** + - Implement `StaticFileCollector` in `collectors/static_file.py` supporting both YAML and INI formats. + - Parse Ansible INI sections (`[group]`, `[group:vars]`, `[group:children]`). + - Implement `AnsibleYamlExporter` (`all: children: ...`) and `AnsibleJsonExporter` (`--list` mode with `_meta.hostvars`). + - Wire `--list` flag in `cli.py` to support running directly as an Ansible dynamic inventory script. +- **Test / Verification:** + - `tests/test_static_collector.py` parses real-world sample `static_hosts.ini` (from `wired-proxmox-provisioning`) and YAML hosts. + - `tests/test_exporters.py` validates output against Ansible dynamic inventory JSON spec. + +--- + +## Slice 3: Proxmox VE REST API Collector +- **Scope:** + - Implement `ProxmoxCollector` in `collectors/proxmox.py` using Python standard library (`urllib.request` / `ssl` / `json`). + - Support API token auth (`PVEAPIToken=USER@REALM!TOKENID=SECRET`). + - Query nodes (`/nodes`), VMs (`/nodes/{node}/qemu`), and LXCs (`/nodes/{node}/lxc`). + - Extract tags, VM state, and resolve IP addresses via QEMU Guest Agent with fallback to network configuration. +- **Test / Verification:** + - `tests/test_proxmox_collector.py` with comprehensive mocked HTTP responses for nodes, QEMU VMs, LXCs, and guest agent network interfaces. + - Verification of SSL context (`verify_ssl=False` support). + +--- + +## Slice 4: Deduplication & Conflict Resolution Engine +- **Scope:** + - Implement `DeduplicationEngine` in `engine.py`. + - Host identity matching by canonical name and IPv4 address. + - Group and tag union (mathematical set merge). + - Conflict resolution (`runtime_over_static` policy) and emission of clear warning logs to `sys.stderr`. + - Mark deduplicated records with `source="hybrid"`. +- **Test / Verification:** + - `tests/test_engine.py` verifying exact duplicate merging, tag unions, IP conflict detection, and warning message strings. + +--- + +## Slice 5: Extended Exporters (`linux-connector`, Generic YAML, XML) & `--sync` +- **Scope:** + - Implement `LinuxConnectorExporter` in `exporters/linux_connector.py` (`hosts` list and `groups` mapping). + - Implement `GenericYamlExporter` in `exporters/generic_yaml.py` (clean dictionary format). + - Implement `XmlExporter` in `exporters/xml_exporter.py` using `xml.etree.ElementTree` and `minidom`. + - Wire `--format` flag (`ansible-yaml`, `ansible-json`, `linux-connector`, `yaml`, `xml`). + - Wire `--sync` flag to update both Ansible and `linux-connector` target paths simultaneously. +- **Test / Verification:** + - `tests/test_exporters.py` asserting XML tree validity, clean YAML dictionaries, and `linux-connector` schema conformance. + +--- + +## Slice 6: Configuration File, Inspection Mode (`--check`), and Documentation +- **Scope:** + - Implement `config.py` loading `config.yaml` with `${ENV_VAR}` expansion and fallback paths. + - Implement `--check` / `--dry-run` inspection mode printing a clean ASCII/Unicode table to stdout without modifying files. + - Write user documentation (`README.md`, `docs/user-guide.md`). + - Generate shell completion scripts for Bash and Zsh in `completions/`. +- **Test / Verification:** + - `tests/test_cli.py` testing `--check` output format and config file loading. + - End-to-end regression test suite passing 100% of unit tests.