113 lines
4.8 KiB
Python
113 lines
4.8 KiB
Python
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
|