From 14a2032c42141025d6ab99859881b97c3a9779c4 Mon Sep 17 00:00:00 2001 From: Mateusz Stomski Date: Sat, 3 Oct 2026 09:00:05 +0200 Subject: [PATCH] feat(slice-4): implement in-memory deduplication and conflict resolution engine --- docs/plans/inventory-collector/00-status.md | 2 +- inventory_collector/cli.py | 21 ++-- inventory_collector/engine.py | 112 ++++++++++++++++++++ tests/fixtures/sample_overrides.yaml | 12 +++ tests/test_engine.py | 75 +++++++++++++ 5 files changed, 214 insertions(+), 8 deletions(-) create mode 100644 inventory_collector/engine.py create mode 100644 tests/fixtures/sample_overrides.yaml create mode 100644 tests/test_engine.py diff --git a/docs/plans/inventory-collector/00-status.md b/docs/plans/inventory-collector/00-status.md index 93eeb15..7f6600b 100644 --- a/docs/plans/inventory-collector/00-status.md +++ b/docs/plans/inventory-collector/00-status.md @@ -9,7 +9,7 @@ - [x] Slice 1 — tracer bullet: Minimal end-to-end pipeline (CLI, basic models, static reader, YAML output) - [x] Slice 2 — Robust static file collector (YAML & INI) and Ansible exporters (YAML & JSON --list) - [x] 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 +- [x] 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 diff --git a/inventory_collector/cli.py b/inventory_collector/cli.py index 9f42aaf..ae39b6e 100644 --- a/inventory_collector/cli.py +++ b/inventory_collector/cli.py @@ -65,12 +65,13 @@ def main(argv: Optional[List[str]] = None) -> int: inv = InventoryData() + raw_records: List[HostRecord] = [] + # Load from sources if specified if args.sources: for src in args.sources: collector = StaticFileCollector(src) - for host in collector.collect(): - inv.add_host(host) + raw_records.extend(collector.collect()) # Check for Proxmox environment variables import os @@ -89,12 +90,11 @@ def main(argv: Optional[List[str]] = None) -> int: token_secret=pve_token_secret, verify_ssl=verify_ssl ) - for host in pve_collector.collect(): - inv.add_host(host) + raw_records.extend(pve_collector.collect()) # Tracer bullet fallback if no hosts loaded - if not inv.hosts: - inv.add_host(HostRecord( + if not raw_records: + raw_records.append(HostRecord( name="k3s-master-0", ansible_host="192.168.5.70", ansible_user="lain", @@ -102,7 +102,7 @@ def main(argv: Optional[List[str]] = None) -> int: tags=["control-plane", "proxmox"], source="tracer" )) - inv.add_host(HostRecord( + raw_records.append(HostRecord( name="node0", ansible_host="192.168.0.101", ansible_user="root", @@ -111,6 +111,13 @@ def main(argv: Optional[List[str]] = None) -> int: source="tracer" )) + from inventory_collector.engine import DeduplicationEngine + engine = DeduplicationEngine() + inv, warnings = engine.process(raw_records) + + for w in warnings: + sys.stderr.write(f"[WARN] {w}\n") + if args.dry_run: sys.stderr.write(f"[INFO] Discovered {len(inv.hosts)} hosts across {len(inv.groups)} groups.\n") print("NAME IP ADDRESS SOURCE GROUPS") diff --git a/inventory_collector/engine.py b/inventory_collector/engine.py new file mode 100644 index 0000000..cec487c --- /dev/null +++ b/inventory_collector/engine.py @@ -0,0 +1,112 @@ +from typing import Dict, List, Optional, Tuple +from inventory_collector.models import HostRecord, InventoryData + +class DeduplicationEngine: + """Normalizes and deduplicates host records in memory with conflict detection.""" + + def __init__(self, conflict_policy: str = "runtime_over_static") -> None: + self.conflict_policy = conflict_policy + + def process(self, raw_records: List[HostRecord]) -> Tuple[InventoryData, List[str]]: + warnings: List[str] = [] + merged_hosts: Dict[str, HostRecord] = {} + + for record in raw_records: + name_key = record.name.strip().lower() + if name_key in merged_hosts: + existing = merged_hosts[name_key] + merged, w = self._merge_pair(existing, record) + merged_hosts[name_key] = merged + if w: + warnings.append(w) + else: + merged_hosts[name_key] = record + + # Check for IP collisions under different hostnames + ip_map: Dict[str, List[str]] = {} + for h in merged_hosts.values(): + if h.ansible_host and not h.ansible_host.startswith("127."): + ip_map.setdefault(h.ansible_host, []).append(h.name) + + for ip, names in sorted(ip_map.items()): + if len(names) > 1: + warnings.append( + f"IP collision: hosts {', '.join([repr(n) for n in sorted(names)])} share the same IP '{ip}'. Keeping both entries." + ) + + inv = InventoryData() + for host in merged_hosts.values(): + inv.add_host(host) + + return inv, warnings + + def _merge_pair(self, current: HostRecord, incoming: HostRecord) -> Tuple[HostRecord, Optional[str]]: + warning = None + + # 1. IP resolution + chosen_ip = current.ansible_host + if current.ansible_host != incoming.ansible_host: + if not current.ansible_host: + chosen_ip = incoming.ansible_host + elif not incoming.ansible_host: + chosen_ip = current.ansible_host + else: + # Both have different non-empty IPs + if "proxmox" in incoming.source and "static" in current.source: + chosen_ip = incoming.ansible_host + warning = ( + f"IP discrepancy for host '{current.name}': static specifies '{current.ansible_host}', " + f"Proxmox runtime reports '{incoming.ansible_host}'. Using runtime IP." + ) + elif "proxmox" in current.source and "static" in incoming.source: + chosen_ip = current.ansible_host + warning = ( + f"IP discrepancy for host '{current.name}': static specifies '{incoming.ansible_host}', " + f"Proxmox runtime reports '{current.ansible_host}'. Using runtime IP." + ) + else: + chosen_ip = incoming.ansible_host + warning = ( + f"IP discrepancy for host '{current.name}': '{current.ansible_host}' vs '{incoming.ansible_host}'. " + f"Using incoming IP '{incoming.ansible_host}'." + ) + + # 2. User resolution (prefer explicit user over default 'lain') + chosen_user = current.ansible_user + if current.ansible_user != incoming.ansible_user: + if current.ansible_user == "lain" and incoming.ansible_user != "lain": + chosen_user = incoming.ansible_user + elif incoming.ansible_user == "lain" and current.ansible_user != "lain": + chosen_user = current.ansible_user + else: + chosen_user = incoming.ansible_user + + # 3. Port & Identity file + chosen_port = current.ansible_port if current.ansible_port != 22 else incoming.ansible_port + chosen_key = current.ansible_ssh_private_key_file or incoming.ansible_ssh_private_key_file + + # 4. Union of groups and tags + merged_groups = sorted(list(set(current.groups + incoming.groups))) + merged_tags = sorted(list(set(current.tags + incoming.tags))) + + # 5. Union of variables + merged_vars = dict(current.variables) + merged_vars.update(incoming.variables) + + # 6. Source + new_source = "hybrid" if current.source != incoming.source else current.source + + merged_record = HostRecord( + name=current.name, + ansible_host=chosen_ip, + ansible_user=chosen_user, + ansible_port=chosen_port, + ansible_ssh_private_key_file=chosen_key, + groups=merged_groups, + tags=merged_tags, + description=current.description or incoming.description, + variables=merged_vars, + source=new_source + ) + + return merged_record, warning diff --git a/tests/fixtures/sample_overrides.yaml b/tests/fixtures/sample_overrides.yaml new file mode 100644 index 0000000..33a16e5 --- /dev/null +++ b/tests/fixtures/sample_overrides.yaml @@ -0,0 +1,12 @@ +# Sample Overrides File +hosts: + node0: + ansible_host: 192.168.0.101 + groups: + - production + tags: + - master_hypervisor + nas: + ansible_host: 192.168.0.2 + groups: + - backup_target diff --git a/tests/test_engine.py b/tests/test_engine.py new file mode 100644 index 0000000..ff9abf7 --- /dev/null +++ b/tests/test_engine.py @@ -0,0 +1,75 @@ +import unittest +from inventory_collector.models import HostRecord +from inventory_collector.engine import DeduplicationEngine + +class TestDeduplicationEngine(unittest.TestCase): + def setUp(self): + self.engine = DeduplicationEngine(conflict_policy="runtime_over_static") + + def test_exact_duplicate_merge(self): + h1 = HostRecord( + name="k3s-master-0", + ansible_host="192.168.5.70", + ansible_user="lain", + groups=["k3s_master"], + tags=["control-plane"], + source="static:sample.ini" + ) + h2 = HostRecord( + name="k3s-master-0", + ansible_host="192.168.5.70", + ansible_user="lain", + groups=["proxmox_vms", "pve_node_node0"], + tags=["proxmox"], + variables={"proxmox_vmid": 100}, + source="proxmox:qemu" + ) + + inv, warnings = self.engine.process([h1, h2]) + self.assertEqual(len(inv.hosts), 1) + merged = inv.get_host("k3s-master-0") + self.assertIsNotNone(merged) + self.assertEqual(merged.source, "hybrid") + self.assertEqual(sorted(merged.groups), ["k3s_master", "proxmox_vms", "pve_node_node0"]) + self.assertEqual(sorted(merged.tags), ["control-plane", "proxmox"]) + self.assertEqual(merged.variables.get("proxmox_vmid"), 100) + + def test_ip_discrepancy_runtime_over_static(self): + h_static = HostRecord( + name="tool-server-1", + ansible_host="192.168.5.61", + ansible_user="lain", + source="static:sample.ini" + ) + h_runtime = HostRecord( + name="tool-server-1", + ansible_host="192.168.5.99", + ansible_user="lain", + source="proxmox:qemu" + ) + + inv, warnings = self.engine.process([h_static, h_runtime]) + merged = inv.get_host("tool-server-1") + self.assertEqual(merged.ansible_host, "192.168.5.99") # Runtime wins + self.assertTrue(any("IP discrepancy" in w and "tool-server-1" in w for w in warnings)) + + def test_ip_collision_different_names(self): + h1 = HostRecord(name="nas", ansible_host="192.168.0.2", source="static") + h2 = HostRecord(name="synology-storage", ansible_host="192.168.0.2", source="proxmox") + + inv, warnings = self.engine.process([h1, h2]) + self.assertEqual(len(inv.hosts), 2) + self.assertIn("nas", inv.hosts) + self.assertIn("synology-storage", inv.hosts) + self.assertTrue(any("IP collision" in w and "192.168.0.2" in w for w in warnings)) + + def test_user_conflict_static_over_default(self): + h1 = HostRecord(name="node0", ansible_host="192.168.0.101", ansible_user="root", source="static") + h2 = HostRecord(name="node0", ansible_host="192.168.0.101", ansible_user="lain", source="proxmox:node") + + inv, warnings = self.engine.process([h1, h2]) + merged = inv.get_host("node0") + self.assertEqual(merged.ansible_user, "root") + +if __name__ == "__main__": + unittest.main()