feat(inspector): implement slice 2 comprehensive host state inspector
This commit is contained in:
1 parent
2602b66a90
commit
66ca179937
11 files changed
+759
-7
No files matched your search
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
## Slices
|
## Slices
|
||||||
- [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + gzip snapshot + 0600 perms + tests)
|
- [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + gzip snapshot + 0600 perms + tests)
|
||||||
- [ ] Slice 2 — comprehensive host state inspector (users/groups, kernel/sysctl/cmdline/modules, hardware/cpu/pci, storage/LVM, network, packages)
|
- [x] Slice 2 — comprehensive host state inspector (users/groups, kernel/sysctl/cmdline/modules, hardware/cpu/pci, storage/LVM, network, packages)
|
||||||
- [ ] Slice 3 — profile system, configuration archiver & manifest generator (`quick`, `system`, `full`, custom) with atomic write & SHA-256 manifest
|
- [ ] Slice 3 — profile system, configuration archiver & manifest generator (`quick`, `system`, `full`, custom) with atomic write & SHA-256 manifest
|
||||||
- [ ] Slice 4 — snapshot management, live diff & safe restore engine (list, show, verify, live system diff, extract, restore with dry-run & safety snapshot)
|
- [ ] Slice 4 — snapshot management, live diff & safe restore engine (list, show, verify, live system diff, extract, restore with dry-run & safety snapshot)
|
||||||
- [ ] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote)
|
- [ ] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote)
|
||||||
|
|||||||
+27
-4
@@ -19,6 +19,7 @@ from linux_backuper.core.constants import (
|
|||||||
EXIT_SUCCESS,
|
EXIT_SUCCESS,
|
||||||
)
|
)
|
||||||
from linux_backuper.core.detector import detect_distro
|
from linux_backuper.core.detector import detect_distro
|
||||||
|
from linux_backuper.core.inspector import SystemInspector
|
||||||
from linux_backuper.models import SnapshotManifest
|
from linux_backuper.models import SnapshotManifest
|
||||||
|
|
||||||
def check_root_permissions() -> bool:
|
def check_root_permissions() -> bool:
|
||||||
@@ -56,14 +57,31 @@ def handle_snapshot(args: argparse.Namespace) -> int:
|
|||||||
|
|
||||||
os_info = detect_distro()
|
os_info = detect_distro()
|
||||||
archiver = SnapshotArchiver(target_dir=target_dir, compression=args.compression)
|
archiver = SnapshotArchiver(target_dir=target_dir, compression=args.compression)
|
||||||
|
inspector = SystemInspector(distro_id=os_info.distro_id)
|
||||||
|
packages = inspector.inspect_packages()
|
||||||
|
|
||||||
if not args.json:
|
if not args.json:
|
||||||
sys.stderr.write(f"[INFO] Initializing snapshot '{snapshot_id}' (profile: {args.profile})...\n")
|
sys.stderr.write(f"[INFO] Initializing snapshot '{snapshot_id}' (profile: {args.profile})...\n")
|
||||||
sys.stderr.write(f"[INFO] Host OS: {os_info.distro_name} {os_info.version_id} ({os_info.arch})\n")
|
sys.stderr.write(f"[INFO] Host OS: {os_info.distro_name} {os_info.version_id} ({os_info.arch})\n")
|
||||||
|
sys.stderr.write(f"[INFO] Packages detected: {len(packages)} via {inspector.package_manager.get_manager_name()}\n")
|
||||||
|
|
||||||
# Pass 1: Collect files & calculate checksums
|
# Pass 1: Collect data paths
|
||||||
file_entries, files_sha256, uncompressed_bytes = archiver.collect_file_list(included_paths)
|
file_entries, files_sha256, uncompressed_bytes = archiver.collect_file_list(included_paths)
|
||||||
|
|
||||||
|
# Pass 1b: Collect deep system telemetry meta files
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
from linux_backuper.core.archiver import calculate_file_sha256
|
||||||
|
|
||||||
|
temp_meta_dir = tempfile.mkdtemp(prefix="linux_backuper_meta_")
|
||||||
|
try:
|
||||||
|
meta_files_map = inspector.dump_meta_files(temp_meta_dir)
|
||||||
|
for rel_path, abs_path in meta_files_map.items():
|
||||||
|
file_entries.append((abs_path, rel_path))
|
||||||
|
sha = calculate_file_sha256(abs_path)
|
||||||
|
files_sha256[rel_path] = sha
|
||||||
|
uncompressed_bytes += os.path.getsize(abs_path)
|
||||||
|
|
||||||
# Manifest preparation
|
# Manifest preparation
|
||||||
manifest = SnapshotManifest(
|
manifest = SnapshotManifest(
|
||||||
schema_version="1.0",
|
schema_version="1.0",
|
||||||
@@ -73,8 +91,8 @@ def handle_snapshot(args: argparse.Namespace) -> int:
|
|||||||
profile=args.profile,
|
profile=args.profile,
|
||||||
compression=args.compression,
|
compression=args.compression,
|
||||||
os=os_info.to_dict(),
|
os=os_info.to_dict(),
|
||||||
package_manager="auto",
|
package_manager=inspector.package_manager.get_manager_name(),
|
||||||
package_count=0,
|
package_count=len(packages),
|
||||||
included_paths=included_paths,
|
included_paths=included_paths,
|
||||||
stats={
|
stats={
|
||||||
"file_count": len(file_entries),
|
"file_count": len(file_entries),
|
||||||
@@ -85,11 +103,12 @@ def handle_snapshot(args: argparse.Namespace) -> int:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Pass 2: Create archive with manifest.json as the very first member
|
# Pass 2: Create archive with manifest.json as the very first member
|
||||||
try:
|
|
||||||
archive_path = archiver.create_snapshot_archive(snapshot_id, manifest, file_entries)
|
archive_path = archiver.create_snapshot_archive(snapshot_id, manifest, file_entries)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
sys.stderr.write(f"[ERROR] Failed to create snapshot archive: {e}\n")
|
sys.stderr.write(f"[ERROR] Failed to create snapshot archive: {e}\n")
|
||||||
return EXIT_GENERIC_ERROR
|
return EXIT_GENERIC_ERROR
|
||||||
|
finally:
|
||||||
|
shutil.rmtree(temp_meta_dir, ignore_errors=True)
|
||||||
|
|
||||||
if args.json:
|
if args.json:
|
||||||
output_payload = {
|
output_payload = {
|
||||||
@@ -112,7 +131,11 @@ def handle_list(args: argparse.Namespace) -> int:
|
|||||||
"""Execute list command."""
|
"""Execute list command."""
|
||||||
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
|
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
|
||||||
archiver = SnapshotArchiver(target_dir=target_dir)
|
archiver = SnapshotArchiver(target_dir=target_dir)
|
||||||
|
try:
|
||||||
snapshots = archiver.list_snapshots()
|
snapshots = archiver.list_snapshots()
|
||||||
|
except PermissionError as e:
|
||||||
|
sys.stderr.write(f"[ERROR] {e} (try running with sudo).\n")
|
||||||
|
return EXIT_PERM_DENIED
|
||||||
|
|
||||||
if args.json:
|
if args.json:
|
||||||
result = [s.to_dict() for s in snapshots]
|
result = [s.to_dict() for s in snapshots]
|
||||||
|
|||||||
@@ -178,7 +178,10 @@ class SnapshotArchiver:
|
|||||||
raise ValueError(f"Could not read manifest from {archive_path}")
|
raise ValueError(f"Could not read manifest from {archive_path}")
|
||||||
|
|
||||||
data = json.loads(manifest_file.read().decode("utf-8"))
|
data = json.loads(manifest_file.read().decode("utf-8"))
|
||||||
return SnapshotManifest.from_dict(data)
|
manifest = SnapshotManifest.from_dict(data)
|
||||||
|
if manifest.stats.get("compressed_bytes", 0) == 0 and os.path.isfile(archive_path):
|
||||||
|
manifest.stats["compressed_bytes"] = os.path.getsize(archive_path)
|
||||||
|
return manifest
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def verify_archive(archive_path: str) -> Tuple[bool, str]:
|
def verify_archive(archive_path: str) -> Tuple[bool, str]:
|
||||||
@@ -249,7 +252,14 @@ class SnapshotArchiver:
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
snapshots: List[SnapshotManifest] = []
|
snapshots: List[SnapshotManifest] = []
|
||||||
for filename in sorted(os.listdir(self.target_dir), reverse=True):
|
try:
|
||||||
|
entries = sorted(os.listdir(self.target_dir), reverse=True)
|
||||||
|
except PermissionError:
|
||||||
|
raise PermissionError(f"Permission denied accessing backup directory: {self.target_dir}")
|
||||||
|
except OSError:
|
||||||
|
return []
|
||||||
|
|
||||||
|
for filename in entries:
|
||||||
if filename.endswith(".tar.gz") and not filename.startswith("."):
|
if filename.endswith(".tar.gz") and not filename.startswith("."):
|
||||||
filepath = os.path.join(self.target_dir, filename)
|
filepath = os.path.join(self.target_dir, filename)
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,345 @@
|
|||||||
|
"""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
|
||||||
|
}
|
||||||
|
|
||||||
|
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 and out.strip():
|
||||||
|
try:
|
||||||
|
data = json.loads(out)
|
||||||
|
block_devices = data.get("blockdevices", [])
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
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:
|
||||||
|
lines = out.splitlines()
|
||||||
|
for line in lines[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]
|
||||||
|
})
|
||||||
|
|
||||||
|
# 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 and out.strip():
|
||||||
|
try:
|
||||||
|
raw_ifaces = json.loads(out)
|
||||||
|
for item in raw_ifaces:
|
||||||
|
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
|
||||||
|
]
|
||||||
|
})
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
routes = []
|
||||||
|
rc, out = self._run_cmd(["ip", "-j", "r"])
|
||||||
|
if rc == 0 and out.strip():
|
||||||
|
try:
|
||||||
|
raw_routes = json.loads(out)
|
||||||
|
for r in raw_routes:
|
||||||
|
routes.append({
|
||||||
|
"dst": r.get("dst", ""),
|
||||||
|
"gateway": r.get("gateway", ""),
|
||||||
|
"dev": r.get("dev", "")
|
||||||
|
})
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
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) -> 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
|
||||||
|
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
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Package manager adapters for multi-distro Linux environments."""
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""Base class and factory for package manager adapters."""
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from linux_backuper.models import PackageItem
|
||||||
|
|
||||||
|
class BasePackageManager(ABC):
|
||||||
|
"""Abstract interface for Linux package manager inspectors."""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get_manager_name(self) -> str:
|
||||||
|
"""Return the canonical name of the package manager (e.g. rpm, dpkg, pacman)."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def list_packages(self) -> List[PackageItem]:
|
||||||
|
"""Query and parse all installed packages on the system."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def is_available(self) -> bool:
|
||||||
|
"""Check if the package manager binary exists on the system."""
|
||||||
|
return shutil.which(self.get_manager_name()) is not None
|
||||||
|
|
||||||
|
def get_package_manager(distro_id: str) -> BasePackageManager:
|
||||||
|
"""Return appropriate package manager adapter based on distro_id or system binaries."""
|
||||||
|
from linux_backuper.managers.rpm import RpmPackageManager
|
||||||
|
from linux_backuper.managers.dpkg import DpkgPackageManager
|
||||||
|
from linux_backuper.managers.pacman import PacmanPackageManager
|
||||||
|
|
||||||
|
distro_id = (distro_id or "").lower()
|
||||||
|
|
||||||
|
if distro_id in ("rhel", "almalinux", "rocky", "centos", "fedora", "amzn"):
|
||||||
|
return RpmPackageManager()
|
||||||
|
elif distro_id in ("debian", "ubuntu", "raspbian", "pop", "linuxmint"):
|
||||||
|
return DpkgPackageManager()
|
||||||
|
elif distro_id in ("arch", "manjaro", "endeavouros"):
|
||||||
|
return PacmanPackageManager()
|
||||||
|
|
||||||
|
# Fallback by probing available binaries on PATH
|
||||||
|
if shutil.which("rpm"):
|
||||||
|
return RpmPackageManager()
|
||||||
|
elif shutil.which("dpkg-query"):
|
||||||
|
return DpkgPackageManager()
|
||||||
|
elif shutil.which("pacman"):
|
||||||
|
return PacmanPackageManager()
|
||||||
|
|
||||||
|
# Generic fallback
|
||||||
|
return DpkgPackageManager()
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""DPKG package manager adapter (Debian, Ubuntu)."""
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from linux_backuper.models import PackageItem
|
||||||
|
from linux_backuper.managers.base import BasePackageManager
|
||||||
|
|
||||||
|
class DpkgPackageManager(BasePackageManager):
|
||||||
|
"""Inspector for DPKG-based Linux distributions."""
|
||||||
|
|
||||||
|
def get_manager_name(self) -> str:
|
||||||
|
return "dpkg-query"
|
||||||
|
|
||||||
|
def list_packages(self) -> List[PackageItem]:
|
||||||
|
"""List installed packages via dpkg-query."""
|
||||||
|
cmd = ["dpkg-query", "-W", "-f=${Package}|${Version}|${Architecture}\n"]
|
||||||
|
try:
|
||||||
|
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
|
||||||
|
if res.returncode != 0:
|
||||||
|
return []
|
||||||
|
except (OSError, FileNotFoundError):
|
||||||
|
return []
|
||||||
|
|
||||||
|
packages: List[PackageItem] = []
|
||||||
|
for line in res.stdout.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
parts = line.split("|")
|
||||||
|
if len(parts) >= 2:
|
||||||
|
name = parts[0]
|
||||||
|
version = parts[1]
|
||||||
|
arch = parts[2] if len(parts) > 2 else ""
|
||||||
|
packages.append(PackageItem(name=name, version=version, arch=arch))
|
||||||
|
|
||||||
|
packages.sort(key=lambda p: p.name)
|
||||||
|
return packages
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Pacman package manager adapter (Arch Linux)."""
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from linux_backuper.models import PackageItem
|
||||||
|
from linux_backuper.managers.base import BasePackageManager
|
||||||
|
|
||||||
|
class PacmanPackageManager(BasePackageManager):
|
||||||
|
"""Inspector for Pacman-based Linux distributions (Arch Linux)."""
|
||||||
|
|
||||||
|
def get_manager_name(self) -> str:
|
||||||
|
return "pacman"
|
||||||
|
|
||||||
|
def list_packages(self) -> List[PackageItem]:
|
||||||
|
"""List installed packages via pacman -Q."""
|
||||||
|
cmd = ["pacman", "-Q"]
|
||||||
|
try:
|
||||||
|
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
|
||||||
|
if res.returncode != 0:
|
||||||
|
return []
|
||||||
|
except (OSError, FileNotFoundError):
|
||||||
|
return []
|
||||||
|
|
||||||
|
packages: List[PackageItem] = []
|
||||||
|
for line in res.stdout.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
parts = line.split(None, 1)
|
||||||
|
if len(parts) >= 2:
|
||||||
|
name = parts[0]
|
||||||
|
version = parts[1]
|
||||||
|
packages.append(PackageItem(name=name, version=version, arch=""))
|
||||||
|
|
||||||
|
packages.sort(key=lambda p: p.name)
|
||||||
|
return packages
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""RPM package manager adapter (RHEL, AlmaLinux, Rocky, CentOS, Fedora)."""
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from linux_backuper.models import PackageItem
|
||||||
|
from linux_backuper.managers.base import BasePackageManager
|
||||||
|
|
||||||
|
class RpmPackageManager(BasePackageManager):
|
||||||
|
"""Inspector for RPM-based Linux distributions."""
|
||||||
|
|
||||||
|
def get_manager_name(self) -> str:
|
||||||
|
return "rpm"
|
||||||
|
|
||||||
|
def list_packages(self) -> List[PackageItem]:
|
||||||
|
"""List installed packages via rpm query."""
|
||||||
|
cmd = ["rpm", "-qa", "--qf", "%{NAME}|%{VERSION}-%{RELEASE}|%{ARCH}\n"]
|
||||||
|
try:
|
||||||
|
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
|
||||||
|
if res.returncode != 0:
|
||||||
|
return []
|
||||||
|
except (OSError, FileNotFoundError):
|
||||||
|
return []
|
||||||
|
|
||||||
|
packages: List[PackageItem] = []
|
||||||
|
for line in res.stdout.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("("):
|
||||||
|
continue
|
||||||
|
parts = line.split("|")
|
||||||
|
if len(parts) >= 2:
|
||||||
|
name = parts[0]
|
||||||
|
version = parts[1]
|
||||||
|
arch = parts[2] if len(parts) > 2 else ""
|
||||||
|
packages.append(PackageItem(name=name, version=version, arch=arch))
|
||||||
|
|
||||||
|
packages.sort(key=lambda p: p.name)
|
||||||
|
return packages
|
||||||
@@ -57,6 +57,28 @@ class ProfileConfig:
|
|||||||
def to_dict(self) -> Dict[str, Any]:
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
return asdict(self)
|
return asdict(self)
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class StorageState:
|
||||||
|
block_devices: List[Dict[str, Any]] = field(default_factory=list)
|
||||||
|
mount_points: List[Dict[str, Any]] = field(default_factory=list)
|
||||||
|
lvm_pvs: Optional[List[Dict[str, Any]]] = None
|
||||||
|
lvm_vgs: Optional[List[Dict[str, Any]]] = None
|
||||||
|
lvm_lvs: Optional[List[Dict[str, Any]]] = None
|
||||||
|
fstab_raw: str = ""
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return asdict(self)
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class NetworkState:
|
||||||
|
interfaces: List[Dict[str, Any]] = field(default_factory=list)
|
||||||
|
routes: List[Dict[str, Any]] = field(default_factory=list)
|
||||||
|
dns_servers: List[str] = field(default_factory=list)
|
||||||
|
hostname: str = ""
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return asdict(self)
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class SnapshotManifest:
|
class SnapshotManifest:
|
||||||
schema_version: str
|
schema_version: str
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch, MagicMock
|
||||||
|
|
||||||
|
from linux_backuper.models import PackageItem, StorageState, NetworkState
|
||||||
|
from linux_backuper.managers.base import BasePackageManager
|
||||||
|
from linux_backuper.managers.rpm import RpmPackageManager
|
||||||
|
from linux_backuper.managers.dpkg import DpkgPackageManager
|
||||||
|
from linux_backuper.managers.pacman import PacmanPackageManager
|
||||||
|
from linux_backuper.core.inspector import SystemInspector
|
||||||
|
|
||||||
|
class TestPackageManagerAdapters(unittest.TestCase):
|
||||||
|
def test_rpm_parser(self):
|
||||||
|
sample_output = """bash|5.1.8-9.el9|x86_64
|
||||||
|
coreutils|8.32-35.el9|x86_64
|
||||||
|
systemd|252-32.el9_4.6|x86_64
|
||||||
|
"""
|
||||||
|
with patch("subprocess.run") as mock_run:
|
||||||
|
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
|
||||||
|
mgr = RpmPackageManager()
|
||||||
|
packages = mgr.list_packages()
|
||||||
|
|
||||||
|
self.assertEqual(len(packages), 3)
|
||||||
|
self.assertEqual(packages[0].name, "bash")
|
||||||
|
self.assertEqual(packages[0].version, "5.1.8-9.el9")
|
||||||
|
self.assertEqual(packages[0].arch, "x86_64")
|
||||||
|
|
||||||
|
def test_dpkg_parser(self):
|
||||||
|
sample_output = """adduser|3.134ubuntu1|all
|
||||||
|
apt|2.4.12|amd64
|
||||||
|
systemd|249.11-0ubuntu3.12|amd64
|
||||||
|
"""
|
||||||
|
with patch("subprocess.run") as mock_run:
|
||||||
|
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
|
||||||
|
mgr = DpkgPackageManager()
|
||||||
|
packages = mgr.list_packages()
|
||||||
|
|
||||||
|
self.assertEqual(len(packages), 3)
|
||||||
|
self.assertEqual(packages[1].name, "apt")
|
||||||
|
self.assertEqual(packages[1].version, "2.4.12")
|
||||||
|
self.assertEqual(packages[1].arch, "amd64")
|
||||||
|
|
||||||
|
def test_pacman_parser(self):
|
||||||
|
sample_output = """bash 5.2.026-2
|
||||||
|
coreutils 9.5-1
|
||||||
|
systemd 255.7-1
|
||||||
|
"""
|
||||||
|
with patch("subprocess.run") as mock_run:
|
||||||
|
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
|
||||||
|
mgr = PacmanPackageManager()
|
||||||
|
packages = mgr.list_packages()
|
||||||
|
|
||||||
|
self.assertEqual(len(packages), 3)
|
||||||
|
self.assertEqual(packages[0].name, "bash")
|
||||||
|
self.assertEqual(packages[0].version, "5.2.026-2")
|
||||||
|
|
||||||
|
class TestSystemInspector(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.temp_dir = tempfile.mkdtemp(prefix="test_inspector_")
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
import shutil
|
||||||
|
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
def test_inspect_users_and_groups_parsing(self):
|
||||||
|
passwd_content = """root:x:0:0:root:/root:/bin/bash
|
||||||
|
bin:x:1:1:bin:/bin:/sbin/nologin
|
||||||
|
soda64:x:1000:1000:Soda User:/home/soda64:/bin/zsh
|
||||||
|
"""
|
||||||
|
group_content = """root:x:0:
|
||||||
|
wheel:x:10:soda64
|
||||||
|
soda64:x:1000:
|
||||||
|
"""
|
||||||
|
passwd_file = os.path.join(self.temp_dir, "passwd")
|
||||||
|
group_file = os.path.join(self.temp_dir, "group")
|
||||||
|
with open(passwd_file, "w") as f:
|
||||||
|
f.write(passwd_content)
|
||||||
|
with open(group_file, "w") as f:
|
||||||
|
f.write(group_content)
|
||||||
|
|
||||||
|
inspector = SystemInspector(distro_id="almalinux")
|
||||||
|
users_info = inspector.parse_users_and_groups(passwd_path=passwd_file, group_path=group_file)
|
||||||
|
|
||||||
|
self.assertEqual(len(users_info["users"]), 3)
|
||||||
|
self.assertEqual(users_info["users"][0]["username"], "root")
|
||||||
|
self.assertEqual(users_info["users"][0]["uid"], 0)
|
||||||
|
self.assertEqual(users_info["users"][2]["shell"], "/bin/zsh")
|
||||||
|
self.assertEqual(len(users_info["groups"]), 3)
|
||||||
|
self.assertEqual(users_info["groups"][1]["name"], "wheel")
|
||||||
|
|
||||||
|
def test_inspect_storage_json_parsing(self):
|
||||||
|
sample_lsblk_json = json.dumps({
|
||||||
|
"blockdevices": [
|
||||||
|
{"name": "sda", "size": "50G", "type": "disk", "children": [
|
||||||
|
{"name": "sda1", "size": "1G", "type": "part", "mountpoint": "/boot"},
|
||||||
|
{"name": "sda2", "size": "49G", "type": "part", "mountpoint": "/"}
|
||||||
|
]}
|
||||||
|
]
|
||||||
|
})
|
||||||
|
sample_df_output = """Filesystem Type Size Used Avail Use% Mounted on
|
||||||
|
/dev/sda2 ext4 48G 12G 34G 27% /
|
||||||
|
/dev/sda1 ext4 976M 142M 767M 16% /boot
|
||||||
|
"""
|
||||||
|
with patch("subprocess.run") as mock_run:
|
||||||
|
def side_effect(cmd, *args, **kwargs):
|
||||||
|
cmd_str = " ".join(cmd) if isinstance(cmd, list) else cmd
|
||||||
|
if "lsblk" in cmd_str:
|
||||||
|
return MagicMock(returncode=0, stdout=sample_lsblk_json, stderr="")
|
||||||
|
if "df" in cmd_str:
|
||||||
|
return MagicMock(returncode=0, stdout=sample_df_output, stderr="")
|
||||||
|
return MagicMock(returncode=1, stdout="", stderr="not found")
|
||||||
|
|
||||||
|
mock_run.side_effect = side_effect
|
||||||
|
inspector = SystemInspector(distro_id="debian")
|
||||||
|
storage_state = inspector.inspect_storage()
|
||||||
|
|
||||||
|
self.assertIsInstance(storage_state, StorageState)
|
||||||
|
self.assertEqual(len(storage_state.block_devices), 1)
|
||||||
|
self.assertEqual(storage_state.block_devices[0]["name"], "sda")
|
||||||
|
self.assertEqual(len(storage_state.mount_points), 2)
|
||||||
|
self.assertEqual(storage_state.mount_points[0]["mount"], "/")
|
||||||
|
|
||||||
|
def test_inspect_network_parsing(self):
|
||||||
|
sample_ip_a = json.dumps([
|
||||||
|
{
|
||||||
|
"ifname": "eth0",
|
||||||
|
"flags": ["UP", "LOWER_UP"],
|
||||||
|
"addr_info": [
|
||||||
|
{"family": "inet", "local": "192.168.10.55", "prefixlen": 24}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
])
|
||||||
|
sample_ip_r = json.dumps([
|
||||||
|
{"dst": "default", "gateway": "192.168.10.1", "dev": "eth0"}
|
||||||
|
])
|
||||||
|
sample_resolv = "nameserver 192.168.10.1\nnameserver 1.1.1.1\n"
|
||||||
|
resolv_path = os.path.join(self.temp_dir, "resolv.conf")
|
||||||
|
with open(resolv_path, "w") as f:
|
||||||
|
f.write(sample_resolv)
|
||||||
|
|
||||||
|
with patch("subprocess.run") as mock_run:
|
||||||
|
def side_effect(cmd, *args, **kwargs):
|
||||||
|
cmd_str = " ".join(cmd) if isinstance(cmd, list) else cmd
|
||||||
|
if "ip -j a" in cmd_str or "ip" in cmd_str and "a" in cmd_str:
|
||||||
|
return MagicMock(returncode=0, stdout=sample_ip_a, stderr="")
|
||||||
|
if "ip -j r" in cmd_str or "ip" in cmd_str and "r" in cmd_str:
|
||||||
|
return MagicMock(returncode=0, stdout=sample_ip_r, stderr="")
|
||||||
|
return MagicMock(returncode=1, stdout="", stderr="")
|
||||||
|
|
||||||
|
mock_run.side_effect = side_effect
|
||||||
|
inspector = SystemInspector(distro_id="almalinux")
|
||||||
|
net_state = inspector.inspect_network(resolv_path=resolv_path)
|
||||||
|
|
||||||
|
self.assertIsInstance(net_state, NetworkState)
|
||||||
|
self.assertEqual(len(net_state.interfaces), 1)
|
||||||
|
self.assertEqual(net_state.interfaces[0]["name"], "eth0")
|
||||||
|
self.assertEqual(len(net_state.routes), 1)
|
||||||
|
self.assertEqual(net_state.routes[0]["gateway"], "192.168.10.1")
|
||||||
|
self.assertEqual(net_state.dns_servers, ["192.168.10.1", "1.1.1.1"])
|
||||||
|
|
||||||
|
def test_dump_meta_files(self):
|
||||||
|
inspector = SystemInspector(distro_id="almalinux")
|
||||||
|
with patch.object(inspector, "inspect_packages", return_value=[
|
||||||
|
PackageItem(name="bash", version="5.1.8", arch="x86_64")
|
||||||
|
]):
|
||||||
|
meta_dir = os.path.join(self.temp_dir, "meta")
|
||||||
|
files_map = inspector.dump_meta_files(meta_dir)
|
||||||
|
|
||||||
|
self.assertIn("meta/packages.txt", files_map)
|
||||||
|
self.assertIn("meta/users.json", files_map)
|
||||||
|
self.assertIn("meta/storage.json", files_map)
|
||||||
|
self.assertIn("meta/network.json", files_map)
|
||||||
|
self.assertIn("meta/kernel.txt", files_map)
|
||||||
|
self.assertIn("meta/hardware.txt", files_map)
|
||||||
|
|
||||||
|
# Check that files actually exist on disk
|
||||||
|
for rel_path, abs_path in files_map.items():
|
||||||
|
self.assertTrue(os.path.isfile(abs_path), f"File {abs_path} was not created")
|
||||||
|
|
||||||
|
# Check content of packages.txt
|
||||||
|
with open(files_map["meta/packages.txt"], "r") as f:
|
||||||
|
content = f.read()
|
||||||
|
self.assertIn("bash|5.1.8|x86_64", content)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user