"""System inspector collecting deep host telemetry (hardware, storage, network, kernel, users, packages).""" import json import os import platform import subprocess from typing import Any, Dict, List, Optional, Tuple from linux_backuper.models import NetworkState, PackageItem, StorageState from linux_backuper.managers.base import BasePackageManager, get_package_manager class SystemInspector: """Collects comprehensive Linux host metadata across diverse distributions.""" def __init__(self, distro_id: str): self.distro_id = distro_id self.package_manager: BasePackageManager = get_package_manager(distro_id) def _run_cmd(self, cmd: List[str]) -> Tuple[int, str]: """Safely execute a shell command and return (returncode, stdout).""" try: res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False) return res.returncode, res.stdout except (OSError, FileNotFoundError): return 1, "" def inspect_packages(self) -> List[PackageItem]: """Query installed packages using the detected package manager.""" return self.package_manager.list_packages() def parse_users_and_groups( self, passwd_path: str = "/etc/passwd", group_path: str = "/etc/group", subuid_path: str = "/etc/subuid", subgid_path: str = "/etc/subgid" ) -> Dict[str, Any]: """Parse Linux user accounts, group memberships, and container subuid/subgid mappings.""" users = [] if os.path.isfile(passwd_path): try: with open(passwd_path, "r", encoding="utf-8", errors="replace") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue parts = line.split(":") if len(parts) >= 7: users.append({ "username": parts[0], "uid": int(parts[2]), "gid": int(parts[3]), "gecos": parts[4], "home": parts[5], "shell": parts[6] }) except (OSError, ValueError): pass groups = [] if os.path.isfile(group_path): try: with open(group_path, "r", encoding="utf-8", errors="replace") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue parts = line.split(":") if len(parts) >= 3: members = parts[3].split(",") if len(parts) > 3 and parts[3] else [] groups.append({ "name": parts[0], "gid": int(parts[2]), "members": members }) except (OSError, ValueError): pass subuids = [] if os.path.isfile(subuid_path): try: with open(subuid_path, "r", encoding="utf-8", errors="replace") as f: for line in f: parts = line.strip().split(":") if len(parts) == 3: subuids.append({"user": parts[0], "start_uid": int(parts[1]), "count": int(parts[2])}) except (OSError, ValueError): pass subgids = [] if os.path.isfile(subgid_path): try: with open(subgid_path, "r", encoding="utf-8", errors="replace") as f: for line in f: parts = line.strip().split(":") if len(parts) == 3: subgids.append({"group": parts[0], "start_gid": int(parts[1]), "count": int(parts[2])}) except (OSError, ValueError): pass return { "users": users, "groups": groups, "subuid": subuids, "subgid": subgids } @staticmethod def parse_lsblk_json(out: str) -> List[Dict[str, Any]]: """Parse JSON output from lsblk -J.""" if not out.strip(): return [] try: data = json.loads(out) return data.get("blockdevices", []) except json.JSONDecodeError: return [] @staticmethod def parse_df_output(out: str) -> List[Dict[str, str]]: """Parse columnized output from df -hT.""" mount_points = [] for line in out.splitlines()[1:]: parts = line.split() if len(parts) >= 7: mount_points.append({ "device": parts[0], "fstype": parts[1], "size": parts[2], "used": parts[3], "avail": parts[4], "percent": parts[5], "mount": parts[6] }) return mount_points @staticmethod def parse_ip_a(out: str) -> List[Dict[str, Any]]: """Parse JSON output from ip -j a.""" if not out.strip(): return [] try: return json.loads(out) except json.JSONDecodeError: return [] @staticmethod def parse_ip_r(out: str) -> List[Dict[str, Any]]: """Parse JSON output from ip -j r.""" if not out.strip(): return [] try: return json.loads(out) except json.JSONDecodeError: return [] def inspect_storage(self, fstab_path: str = "/etc/fstab") -> StorageState: """Inspect storage topology: lsblk block devices, df mounts, LVM, and fstab.""" block_devices = [] rc, out = self._run_cmd(["lsblk", "-J", "-o", "NAME,SIZE,TYPE,MOUNTPOINT,FSTYPE,UUID"]) if rc == 0: block_devices = self.parse_lsblk_json(out) if not block_devices: # Fallback plain lsblk rc, out = self._run_cmd(["lsblk", "-l", "-o", "NAME,SIZE,TYPE,MOUNTPOINT"]) if rc == 0: for line in out.splitlines()[1:]: parts = line.split() if parts: block_devices.append({"name": parts[0], "size": parts[1] if len(parts) > 1 else ""}) # Mount points from df -hT mount_points = [] rc, out = self._run_cmd(["df", "-hT"]) if rc == 0: mount_points = self.parse_df_output(out) # LVM Inspection if tools exist lvm_pvs, lvm_vgs, lvm_lvs = None, None, None rc, out = self._run_cmd(["pvs", "--reportformat", "json"]) if rc == 0 and out.strip(): try: lvm_pvs = json.loads(out).get("report", [{}])[0].get("pv", []) except (json.JSONDecodeError, IndexError, KeyError): pass rc, out = self._run_cmd(["vgs", "--reportformat", "json"]) if rc == 0 and out.strip(): try: lvm_vgs = json.loads(out).get("report", [{}])[0].get("vg", []) except (json.JSONDecodeError, IndexError, KeyError): pass rc, out = self._run_cmd(["lvs", "--reportformat", "json"]) if rc == 0 and out.strip(): try: lvm_lvs = json.loads(out).get("report", [{}])[0].get("lv", []) except (json.JSONDecodeError, IndexError, KeyError): pass # Read fstab fstab_raw = "" if os.path.isfile(fstab_path): try: with open(fstab_path, "r", encoding="utf-8", errors="replace") as f: fstab_raw = f.read() except OSError: pass return StorageState( block_devices=block_devices, mount_points=mount_points, lvm_pvs=lvm_pvs, lvm_vgs=lvm_vgs, lvm_lvs=lvm_lvs, fstab_raw=fstab_raw ) def inspect_network(self, resolv_path: str = "/etc/resolv.conf") -> NetworkState: """Inspect network interfaces, IP routes, and DNS resolvers.""" interfaces = [] rc, out = self._run_cmd(["ip", "-j", "a"]) if rc == 0: for item in self.parse_ip_a(out): interfaces.append({ "name": item.get("ifname", ""), "flags": item.get("flags", []), "addresses": [ f"{a.get('local')}/{a.get('prefixlen')}" for a in item.get("addr_info", []) if "local" in a ] }) routes = [] rc, out = self._run_cmd(["ip", "-j", "r"]) if rc == 0: for r in self.parse_ip_r(out): routes.append({ "dst": r.get("dst", ""), "gateway": r.get("gateway", ""), "dev": r.get("dev", "") }) dns_servers = [] if os.path.isfile(resolv_path): try: with open(resolv_path, "r", encoding="utf-8", errors="replace") as f: for line in f: line = line.strip() if line.startswith("nameserver"): parts = line.split() if len(parts) >= 2: dns_servers.append(parts[1]) except OSError: pass return NetworkState( interfaces=interfaces, routes=routes, dns_servers=dns_servers, hostname=platform.node() ) def inspect_hardware(self) -> str: """Generate hardware overview text.""" lines = [] lines.append(f"System: {platform.system()} {platform.release()} ({platform.machine()})") lines.append(f"Node: {platform.node()}") # lscpu rc, out = self._run_cmd(["lscpu"]) if rc == 0 and out: lines.append("\n=== CPU Architecture (lscpu) ===") lines.append(out.strip()) elif os.path.isfile("/proc/cpuinfo"): try: with open("/proc/cpuinfo", "r") as f: lines.append("\n=== /proc/cpuinfo ===") lines.append(f.read().strip()) except OSError: pass # memory info if os.path.isfile("/proc/meminfo"): try: with open("/proc/meminfo", "r") as f: lines.append("\n=== /proc/meminfo ===") lines.append(f.read().strip()) except OSError: pass return "\n".join(lines) def inspect_kernel(self) -> str: """Generate kernel parameters and loaded modules text.""" lines = [] lines.append(f"Kernel Release: {platform.release()}") lines.append(f"Kernel Version: {platform.version()}") if os.path.isfile("/proc/cmdline"): try: with open("/proc/cmdline", "r") as f: lines.append(f"Boot cmdline: {f.read().strip()}") except OSError: pass rc, out = self._run_cmd(["lsmod"]) if rc == 0 and out: lines.append("\n=== Loaded Modules (lsmod) ===") lines.append(out.strip()) rc, out = self._run_cmd(["sysctl", "-a"]) if rc == 0 and out: lines.append("\n=== Kernel Parameters (sysctl -a) ===") lines.append(out.strip()) return "\n".join(lines) def dump_meta_files(self, meta_dir: str, packages: Optional[List[PackageItem]] = None) -> Dict[str, str]: """ Dump all telemetry command outputs and structured JSON into meta_dir. Returns a mapping of archive relative path to host absolute path. """ os.makedirs(meta_dir, exist_ok=True) files_map: Dict[str, str] = {} # 1. Packages if packages is None: packages = self.inspect_packages() pkg_path = os.path.join(meta_dir, "packages.txt") with open(pkg_path, "w", encoding="utf-8") as f: for p in packages: f.write(f"{p.name}|{p.version}|{p.arch}\n") files_map["meta/packages.txt"] = pkg_path # 2. Users and Groups users_data = self.parse_users_and_groups() users_path = os.path.join(meta_dir, "users.json") with open(users_path, "w", encoding="utf-8") as f: json.dump(users_data, f, indent=2) files_map["meta/users.json"] = users_path # 3. Storage storage_data = self.inspect_storage() storage_path = os.path.join(meta_dir, "storage.json") with open(storage_path, "w", encoding="utf-8") as f: json.dump(storage_data.to_dict(), f, indent=2) files_map["meta/storage.json"] = storage_path # 4. Network network_data = self.inspect_network() network_path = os.path.join(meta_dir, "network.json") with open(network_path, "w", encoding="utf-8") as f: json.dump(network_data.to_dict(), f, indent=2) files_map["meta/network.json"] = network_path # 5. Hardware hw_text = self.inspect_hardware() hw_path = os.path.join(meta_dir, "hardware.txt") with open(hw_path, "w", encoding="utf-8") as f: f.write(hw_text) files_map["meta/hardware.txt"] = hw_path # 6. Kernel kernel_text = self.inspect_kernel() kernel_path = os.path.join(meta_dir, "kernel.txt") with open(kernel_path, "w", encoding="utf-8") as f: f.write(kernel_text) files_map["meta/kernel.txt"] = kernel_path return files_map