feat(slice-1): implement tracer bullet pipeline with PyYAML check and pure-python fallback

This commit is contained in:
soda64 committed 2026-10-03 08:29:59 +02:00
1 parent 937acc2548
commit 68802710b0
12 files changed
+331 -1

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
import sys
from pathlib import Path
# Add project root to sys.path when running from source checkout
root_dir = Path(__file__).resolve().parent.parent
if str(root_dir) not in sys.path:
sys.path.insert(0, str(root_dir))
for candidate in ("/usr/lib/inventory-collector", "/usr/local/lib/inventory-collector"):
if candidate not in sys.path and Path(candidate).is_dir():
sys.path.insert(0, candidate)
from inventory_collector.cli import main
if __name__ == "__main__":
sys.exit(main())
+1 -1
View File
@@ -6,7 +6,7 @@
- Gate 4 — Slice Plan: APPROVED 2026-10-03 - Gate 4 — Slice Plan: APPROVED 2026-10-03
## Slices ## Slices
- [ ] Slice 1 — tracer bullet: Minimal end-to-end pipeline (CLI, basic models, static reader, YAML output) - [x] 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 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 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 4 — In-memory deduplication and conflict resolution engine with stderr warnings
+19
View File
@@ -0,0 +1,19 @@
"""Universal homelab and fleet inventory collector and deduplicator."""
__version__ = "1.0.0"
_yaml_warning_emitted = False
def get_yaml_module():
"""Return the yaml module if installed, or None while emitting an actionable warning on stderr."""
global _yaml_warning_emitted
try:
import yaml
return yaml
except ImportError:
import sys
if not _yaml_warning_emitted:
sys.stderr.write("[WARN] Moduł 'pyyaml' nie jest zainstalowany w środowisku Python. "
"Zainstaluj go za pomocą: pip install pyyaml (lub pip install -r requirements.txt)\n")
_yaml_warning_emitted = True
return None
+5
View File
@@ -0,0 +1,5 @@
import sys
from inventory_collector.cli import main
if __name__ == "__main__":
sys.exit(main())
+96
View File
@@ -0,0 +1,96 @@
import argparse
import sys
from pathlib import Path
from typing import List, Optional
from inventory_collector import __version__
from inventory_collector.models import HostRecord, InventoryData
from inventory_collector.exporters.ansible_yaml import AnsibleYamlExporter
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="inventory-collector",
description="Universal homelab and fleet inventory collector and deduplicator."
)
parser.add_argument(
"-V", "--version",
action="version",
version=f"%(prog)s {__version__}"
)
parser.add_argument(
"-o", "--output",
type=Path,
help="Target output file path. Defaults to stdout."
)
parser.add_argument(
"-f", "--format",
choices=["ansible-yaml", "ansible-json", "linux-connector", "yaml", "xml", "ini"],
default="ansible-yaml",
help="Export format. Inferred from output file extension if omitted."
)
parser.add_argument(
"--check", "--dry-run",
dest="dry_run",
action="store_true",
help="Inspect inventory without writing any files."
)
parser.add_argument(
"--list",
action="store_true",
help="Ansible dynamic inventory mode: outputs JSON to stdout."
)
parser.add_argument(
"--sync",
action="store_true",
help="Synchronize inventory to both Ansible and linux-connector default paths."
)
parser.add_argument(
"-c", "--config",
type=Path,
help="Path to configuration file (config.yaml)."
)
return parser
def main(argv: Optional[List[str]] = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
# Tracer bullet sample data when no source is loaded yet
inv = InventoryData()
inv.add_host(HostRecord(
name="k3s-master-0",
ansible_host="192.168.5.70",
ansible_user="lain",
groups=["k3s_master", "k3s_cluster"],
tags=["control-plane", "proxmox"],
source="tracer"
))
inv.add_host(HostRecord(
name="node0",
ansible_host="192.168.0.101",
ansible_user="root",
groups=["proxmox_nodes"],
tags=["hypervisor", "pve"],
source="tracer"
))
if args.dry_run:
sys.stderr.write(f"[INFO] Discovered {len(inv.hosts)} hosts across {len(inv.groups)} groups (tracer mode).\n")
print("NAME IP ADDRESS SOURCE GROUPS")
for h in inv.hosts.values():
groups_str = ", ".join(h.groups)
print(f"{h.name:<17} {h.ansible_host:<15} {h.source:<9} {groups_str}")
return 0
exporter = AnsibleYamlExporter()
rendered = exporter.export(inv)
if args.output:
exporter.write_to_file(inv, args.output)
sys.stderr.write(f"[SUCCESS] Written inventory to {args.output}\n")
else:
sys.stdout.write(rendered)
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1 @@
# Exporters package
@@ -0,0 +1,82 @@
from typing import Any, Dict
from inventory_collector import get_yaml_module
from inventory_collector.exporters.base import BaseExporter
from inventory_collector.models import InventoryData
class AnsibleYamlExporter(BaseExporter):
"""Exports inventory in standard Ansible YAML format."""
def _build_structure(self, data: InventoryData) -> Dict[str, Any]:
structure: Dict[str, Any] = {
"all": {
"children": {}
}
}
# Hosts assigned to groups
grouped_hosts = set()
for group_name, host_names in sorted(data.groups.items()):
group_dict: Dict[str, Any] = {"hosts": {}}
for name in sorted(host_names):
host = data.get_host(name)
if not host:
continue
grouped_hosts.add(name)
host_vars: Dict[str, Any] = {
"ansible_host": host.ansible_host,
"ansible_user": host.ansible_user,
"ansible_port": host.ansible_port,
}
if host.ansible_ssh_private_key_file:
host_vars["ansible_ssh_private_key_file"] = host.ansible_ssh_private_key_file
if host.tags:
host_vars["tags"] = host.tags
for k, v in host.variables.items():
host_vars[k] = v
group_dict["hosts"][name] = host_vars
structure["all"]["children"][group_name] = group_dict
# Ungrouped hosts placed directly under all.hosts
ungrouped = {name: host for name, host in data.hosts.items() if name not in grouped_hosts}
if ungrouped:
structure["all"]["hosts"] = {}
for name, host in sorted(ungrouped.items()):
host_vars = {
"ansible_host": host.ansible_host,
"ansible_user": host.ansible_user,
"ansible_port": host.ansible_port,
}
if host.tags:
host_vars["tags"] = host.tags
for k, v in host.variables.items():
host_vars[k] = v
structure["all"]["hosts"][name] = host_vars
return structure
def _builtin_yaml_dump(self, obj: Any, indent: int = 0) -> str:
"""Lightweight pure-python YAML serializer for basic dictionary/list structures."""
lines = []
prefix = " " * indent
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
lines.append(f"{prefix}{k}:")
lines.append(self._builtin_yaml_dump(v, indent + 1))
else:
lines.append(f"{prefix}{k}: {v}")
elif isinstance(obj, list):
for item in obj:
if isinstance(item, (dict, list)):
lines.append(f"{prefix}-")
lines.append(self._builtin_yaml_dump(item, indent + 1))
else:
lines.append(f"{prefix}- {item}")
return "\n".join(lines)
def export(self, data: InventoryData) -> str:
structure = self._build_structure(data)
yaml = get_yaml_module()
if yaml:
return yaml.dump(structure, sort_keys=False, default_flow_style=False)
return self._builtin_yaml_dump(structure) + "\n"
+16
View File
@@ -0,0 +1,16 @@
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:
"""Export inventory data to a formatted string representation."""
raise NotImplementedError
def write_to_file(self, data: InventoryData, target: Path) -> None:
"""Export inventory data and write to target path, creating parent dirs if needed."""
target = Path(target).expanduser().resolve()
target.parent.mkdir(parents=True, exist_ok=True)
content = self.export(data)
target.write_text(content, encoding="utf-8")
+35
View File
@@ -0,0 +1,35 @@
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:
self.hosts[host.name] = host
for group in host.groups:
if group not in self.groups:
self.groups[group] = []
if host.name not in self.groups[group]:
self.groups[group].append(host.name)
def get_host(self, name: str) -> Optional[HostRecord]:
return self.hosts.get(name)
def get_hosts_by_group(self, group: str) -> List[HostRecord]:
host_names = self.groups.get(group, [])
return [self.hosts[name] for name in host_names if name in self.hosts]
+1
View File
@@ -0,0 +1 @@
pyyaml>=6.0
+1
View File
@@ -0,0 +1 @@
# tests package
+57
View File
@@ -0,0 +1,57 @@
import unittest
import sys
from io import StringIO
from inventory_collector.models import HostRecord, InventoryData
from inventory_collector.exporters.ansible_yaml import AnsibleYamlExporter
from inventory_collector.cli import main
class TestTracerBullet(unittest.TestCase):
def test_host_record_creation(self):
host = HostRecord(
name="k3s-master-0",
ansible_host="192.168.5.70",
ansible_user="lain",
groups=["k3s_master", "k3s_cluster"],
tags=["control-plane", "proxmox"],
source="test"
)
self.assertEqual(host.name, "k3s-master-0")
self.assertEqual(host.ansible_host, "192.168.5.70")
self.assertEqual(host.ansible_user, "lain")
self.assertIn("k3s_master", host.groups)
def test_ansible_yaml_exporter_output(self):
inv = InventoryData()
host = HostRecord(
name="k3s-master-0",
ansible_host="192.168.5.70",
ansible_user="lain",
groups=["k3s_master"],
tags=["control-plane"]
)
inv.add_host(host)
exporter = AnsibleYamlExporter()
output = exporter.export(inv)
self.assertIn("all:", output)
self.assertIn("children:", output)
self.assertIn("k3s_master:", output)
self.assertIn("k3s-master-0:", output)
self.assertIn("192.168.5.70", output)
def test_cli_runs_tracer(self):
stdout_capture = StringIO()
stderr_capture = StringIO()
old_stdout, old_stderr = sys.stdout, sys.stderr
try:
sys.stdout = stdout_capture
sys.stderr = stderr_capture
exit_code = main(["--dry-run"])
self.assertEqual(exit_code, 0)
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
if __name__ == "__main__":
unittest.main()