feat(inspector): implement slice 2 comprehensive host state inspector
This commit is contained in:
1 parent
2602b66a90
commit
66ca179937
11 files changed
+777
-25
No files matched your search
+45
-22
@@ -19,6 +19,7 @@ from linux_backuper.core.constants import (
|
||||
EXIT_SUCCESS,
|
||||
)
|
||||
from linux_backuper.core.detector import detect_distro
|
||||
from linux_backuper.core.inspector import SystemInspector
|
||||
from linux_backuper.models import SnapshotManifest
|
||||
|
||||
def check_root_permissions() -> bool:
|
||||
@@ -56,40 +57,58 @@ def handle_snapshot(args: argparse.Namespace) -> int:
|
||||
|
||||
os_info = detect_distro()
|
||||
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:
|
||||
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] 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)
|
||||
|
||||
# Manifest preparation
|
||||
manifest = SnapshotManifest(
|
||||
schema_version="1.0",
|
||||
snapshot_id=snapshot_id,
|
||||
created_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
hostname=socket.gethostname(),
|
||||
profile=args.profile,
|
||||
compression=args.compression,
|
||||
os=os_info.to_dict(),
|
||||
package_manager="auto",
|
||||
package_count=0,
|
||||
included_paths=included_paths,
|
||||
stats={
|
||||
"file_count": len(file_entries),
|
||||
"uncompressed_bytes": uncompressed_bytes,
|
||||
"compressed_bytes": 0
|
||||
},
|
||||
files_sha256=files_sha256
|
||||
)
|
||||
# Pass 1b: Collect deep system telemetry meta files
|
||||
import shutil
|
||||
import tempfile
|
||||
from linux_backuper.core.archiver import calculate_file_sha256
|
||||
|
||||
# Pass 2: Create archive with manifest.json as the very first member
|
||||
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 = SnapshotManifest(
|
||||
schema_version="1.0",
|
||||
snapshot_id=snapshot_id,
|
||||
created_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
hostname=socket.gethostname(),
|
||||
profile=args.profile,
|
||||
compression=args.compression,
|
||||
os=os_info.to_dict(),
|
||||
package_manager=inspector.package_manager.get_manager_name(),
|
||||
package_count=len(packages),
|
||||
included_paths=included_paths,
|
||||
stats={
|
||||
"file_count": len(file_entries),
|
||||
"uncompressed_bytes": uncompressed_bytes,
|
||||
"compressed_bytes": 0
|
||||
},
|
||||
files_sha256=files_sha256
|
||||
)
|
||||
|
||||
# Pass 2: Create archive with manifest.json as the very first member
|
||||
archive_path = archiver.create_snapshot_archive(snapshot_id, manifest, file_entries)
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"[ERROR] Failed to create snapshot archive: {e}\n")
|
||||
return EXIT_GENERIC_ERROR
|
||||
finally:
|
||||
shutil.rmtree(temp_meta_dir, ignore_errors=True)
|
||||
|
||||
if args.json:
|
||||
output_payload = {
|
||||
@@ -112,7 +131,11 @@ def handle_list(args: argparse.Namespace) -> int:
|
||||
"""Execute list command."""
|
||||
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
|
||||
archiver = SnapshotArchiver(target_dir=target_dir)
|
||||
snapshots = archiver.list_snapshots()
|
||||
try:
|
||||
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:
|
||||
result = [s.to_dict() for s in snapshots]
|
||||
|
||||
@@ -178,7 +178,10 @@ class SnapshotArchiver:
|
||||
raise ValueError(f"Could not read manifest from {archive_path}")
|
||||
|
||||
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
|
||||
def verify_archive(archive_path: str) -> Tuple[bool, str]:
|
||||
@@ -249,7 +252,14 @@ class SnapshotArchiver:
|
||||
return []
|
||||
|
||||
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("."):
|
||||
filepath = os.path.join(self.target_dir, filename)
|
||||
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]:
|
||||
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
|
||||
class SnapshotManifest:
|
||||
schema_version: str
|
||||
|
||||
Reference in new issue
Block a user