feat(profiles): implement slice 3 profile system, flock concurrency, and sanitize archiver

This commit is contained in:
soda64 committed 2026-10-09 18:59:49 +02:00
1 parent 66ca179937
commit 646bd9d145
8 files changed
+536 -69

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@
## Slices
- [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + gzip snapshot + 0600 perms + tests)
- [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
- [x] 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 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote)
- [ ] Slice 6 — remote transport sync (local-first + SFTP / rsync / mounted NFS/SMB push with separate remote retention)
+108 -61
View File
@@ -9,9 +9,11 @@ import sys
from typing import List, Optional
from linux_backuper import __version__
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.archiver import SnapshotArchiver, calculate_file_sha256
from linux_backuper.core.constants import (
DEFAULT_BACKUP_DIR,
DEFAULT_CONFIG_PATH,
DEFAULT_PID_PATH,
EXIT_CORRUPTED,
EXIT_GENERIC_ERROR,
EXIT_PERM_DENIED,
@@ -20,6 +22,8 @@ from linux_backuper.core.constants import (
)
from linux_backuper.core.detector import detect_distro
from linux_backuper.core.inspector import SystemInspector
from linux_backuper.core.lock import SingleInstanceLock, LockAcquisitionError
from linux_backuper.core.profiles import ProfileManager
from linux_backuper.models import SnapshotManifest
def check_root_permissions() -> bool:
@@ -44,71 +48,105 @@ def handle_snapshot(args: argparse.Namespace) -> int:
sys.stderr.write(f"[ERROR] Target backup directory not accessible: {e}\n")
return EXIT_PREFLIGHT_FAIL
hostname = socket.gethostname().split(".")[0]
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
snapshot_id = f"backup_{hostname}_{timestamp}"
# Determine paths to back up
if args.paths:
included_paths = args.paths
else:
# Default quick profile includes /etc
included_paths = ["/etc"]
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 data 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_")
pid_path = getattr(args, "pid_path", None) or os.environ.get("LINUX_BACKUPER_PID_PATH") or DEFAULT_PID_PATH
lock = SingleInstanceLock(pid_path=pid_path)
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)
lock.acquire()
except LockAcquisitionError as e:
sys.stderr.write(f"[ERROR] {e}\n")
return EXIT_GENERIC_ERROR
# 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
try:
config_path = getattr(args, "config", None) or DEFAULT_CONFIG_PATH
profile_mgr = ProfileManager(config_path=config_path)
try:
profile = profile_mgr.get_profile(args.profile)
except KeyError as e:
sys.stderr.write(f"[ERROR] {e}\n")
return EXIT_GENERIC_ERROR
hostname = socket.gethostname().split(".")[0]
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
snapshot_id = f"backup_{hostname}_{timestamp}"
# Resolve paths & exclusions
included_paths = args.paths if args.paths else profile.included_paths
exclude_patterns = profile.exclude_patterns
compression = "none" if getattr(args, "no_compression", False) else args.compression
sanitize = getattr(args, "sanitize", False)
os_info = detect_distro()
archiver = SnapshotArchiver(target_dir=target_dir, compression=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 data paths
file_entries, files_sha256, uncompressed_bytes, sanitized_files = archiver.collect_file_list(
included_paths,
exclude_patterns=exclude_patterns,
sanitize=sanitize
)
# Pass 2: Create archive with manifest.json as the very first member
archive_path = archiver.create_snapshot_archive(snapshot_id, manifest, file_entries)
# Pass 1b: Collect deep system telemetry meta files
import shutil
import tempfile
temp_meta_dir = tempfile.mkdtemp(prefix="linux_backuper_meta_")
try:
meta_files_map = inspector.dump_meta_files(temp_meta_dir)
# Record sanitized files if any
if sanitized_files:
sanitized_log_path = os.path.join(temp_meta_dir, "sanitized.txt")
with open(sanitized_log_path, "w", encoding="utf-8") as f:
f.write("# Redacted security files:\n")
for s in sanitized_files:
f.write(f"{s}\n")
meta_files_map["meta/sanitized.txt"] = sanitized_log_path
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=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,
"sanitized_count": len(sanitized_files)
},
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)
finally:
shutil.rmtree(temp_meta_dir, ignore_errors=True)
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)
lock.release()
if args.json:
output_payload = {
@@ -160,10 +198,15 @@ def handle_verify(args: argparse.Namespace) -> int:
snapshot_id = args.snapshot_id
# Resolve filename
if not snapshot_id.endswith(".tar.gz"):
filename = f"{snapshot_id}.tar.gz"
else:
if snapshot_id.endswith(".tar.gz") or snapshot_id.endswith(".tar"):
filename = snapshot_id
else:
candidate_tar = os.path.join(target_dir, f"{snapshot_id}.tar") if not os.path.isabs(snapshot_id) else f"{snapshot_id}.tar"
candidate_gz = os.path.join(target_dir, f"{snapshot_id}.tar.gz") if not os.path.isabs(snapshot_id) else f"{snapshot_id}.tar.gz"
if os.path.exists(candidate_tar) and not os.path.exists(candidate_gz):
filename = f"{snapshot_id}.tar"
else:
filename = f"{snapshot_id}.tar.gz"
archive_path = os.path.join(target_dir, filename) if not os.path.isabs(filename) else filename
is_valid, msg = SnapshotArchiver.verify_archive(archive_path)
@@ -200,6 +243,10 @@ def build_parser() -> argparse.ArgumentParser:
snap_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help=f"Destination directory (default: {DEFAULT_BACKUP_DIR})")
snap_parser.add_argument("--paths", nargs="+", help="Specific directories or files to include in snapshot")
snap_parser.add_argument("--compression", choices=["gzip", "none"], default="gzip", help="Compression algorithm")
snap_parser.add_argument("--no-compression", action="store_true", help="Store plain uncompressed tar archive")
snap_parser.add_argument("--sanitize", action="store_true", help="Redact secrets and private keys for diagnostic export")
snap_parser.add_argument("--config", help=f"Path to JSON configuration file (default: {DEFAULT_CONFIG_PATH})")
snap_parser.add_argument("--pid-path", help=f"Path to lockfile PID file (default: {DEFAULT_PID_PATH})")
# List command
list_parser = subparsers.add_parser("list", help="List existing local snapshots", parents=[common_parser])
+62 -7
View File
@@ -29,6 +29,15 @@ def is_socket_or_fifo(filepath: str) -> bool:
except OSError:
return True
def is_sanitized_target(filepath: str) -> bool:
"""Check if file contains secrets and must be omitted during sanitized export."""
name = os.path.basename(filepath)
if name in ("shadow", "gshadow", "opasswd", "shadow-", "gshadow-"):
return True
if name.startswith("ssh_host_") and "key" in name and not name.endswith(".pub"):
return True
return False
class SnapshotArchiver:
"""Manages creation, listing, and verification of snapshot archives."""
@@ -50,17 +59,22 @@ class SnapshotArchiver:
def collect_file_list(
self,
paths: List[str],
exclude_patterns: Optional[List[str]] = None
) -> Tuple[List[Tuple[str, str]], Dict[str, str], int]:
exclude_patterns: Optional[List[str]] = None,
sanitize: bool = False,
one_file_system: bool = True,
max_file_size_mb: int = 50
) -> Tuple[List[Tuple[str, str]], Dict[str, str], int, List[str]]:
"""
Scan paths and compute pre-archive hashes and metadata.
Returns:
- list of (filesystem_abs_path, tar_rel_path)
- dict of {tar_rel_path: sha256_hash}
- total uncompressed bytes
- list of sanitized/redacted relative paths
"""
file_entries: List[Tuple[str, str]] = []
files_sha256: Dict[str, str] = {}
sanitized_files: List[str] = []
total_bytes = 0
exclude_patterns = exclude_patterns or []
@@ -69,9 +83,19 @@ class SnapshotArchiver:
if not os.path.exists(abs_base):
continue
try:
base_st = os.lstat(abs_base)
base_dev = base_st.st_dev
except OSError:
continue
if os.path.isfile(abs_base) or os.path.islink(abs_base):
rel_name = os.path.join("data", os.path.basename(abs_base))
if sanitize and is_sanitized_target(abs_base):
sanitized_files.append(rel_name)
continue
if not is_socket_or_fifo(abs_base):
rel_name = os.path.join("data", os.path.basename(abs_base))
file_entries.append((abs_base, rel_name))
if not os.path.islink(abs_base):
sha = calculate_file_sha256(abs_base)
@@ -84,26 +108,57 @@ class SnapshotArchiver:
# Filter subdirectories in place
dirs[:] = [d for d in dirs if not any(p in d for p in exclude_patterns)]
# Check one-file-system boundary for subdirectories
if one_file_system:
allowed_dirs = []
for d in dirs:
dir_path = os.path.join(root, d)
try:
if os.lstat(dir_path).st_dev == base_dev:
allowed_dirs.append(d)
except OSError:
pass
dirs[:] = allowed_dirs
for filename in files:
abs_filepath = os.path.join(root, filename)
if is_socket_or_fifo(abs_filepath):
if any(p in filename for p in exclude_patterns):
continue
# One file system boundary check
try:
st = os.lstat(abs_filepath)
if one_file_system and st.st_dev != base_dev:
continue
except OSError:
continue
# Large file check (> 50 MB)
if max_file_size_mb > 0 and st.st_size > (max_file_size_mb * 1024 * 1024):
continue
# Calculate archive path under data/
rel_to_base = os.path.relpath(abs_filepath, os.path.dirname(abs_base))
arc_path = os.path.join("data", rel_to_base)
# Diagnostic sanitization check
if sanitize and is_sanitized_target(abs_filepath):
sanitized_files.append(arc_path)
continue
if is_socket_or_fifo(abs_filepath):
continue
file_entries.append((abs_filepath, arc_path))
if not os.path.islink(abs_filepath):
try:
sha = calculate_file_sha256(abs_filepath)
files_sha256[arc_path] = sha
total_bytes += os.path.getsize(abs_filepath)
total_bytes += st.st_size
except (OSError, IOError):
pass
return file_entries, files_sha256, total_bytes
return file_entries, files_sha256, total_bytes, sanitized_files
def create_snapshot_archive(
self,
+76
View File
@@ -0,0 +1,76 @@
"""Concurrency locking using non-blocking fcntl.flock on a PID file."""
import fcntl
import os
from typing import Optional
from linux_backuper.core.constants import DEFAULT_PID_PATH
class LockAcquisitionError(RuntimeError):
"""Raised when another instance of linux-backuper is already executing."""
pass
class SingleInstanceLock:
"""Ensures single-process execution using kernel-level file locks."""
def __init__(self, pid_path: str = DEFAULT_PID_PATH):
self.pid_path = pid_path
self._fd: Optional[int] = None
def acquire(self) -> bool:
"""Acquire exclusive non-blocking lock. Raises LockAcquisitionError on conflict."""
parent_dir = os.path.dirname(self.pid_path)
if parent_dir:
try:
os.makedirs(parent_dir, exist_ok=True)
except OSError:
pass
try:
self._fd = os.open(self.pid_path, os.O_CREAT | os.O_RDWR, 0o600)
except PermissionError:
if os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT") == "1":
import tempfile
self.pid_path = os.path.join(tempfile.gettempdir(), f"linux-backuper-{os.getpid()}.pid")
self._fd = os.open(self.pid_path, os.O_CREAT | os.O_RDWR, 0o600)
else:
raise
try:
fcntl.flock(self._fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
os.ftruncate(self._fd, 0)
os.write(self._fd, f"{os.getpid()}\n".encode("utf-8"))
return True
except (BlockingIOError, OSError) as e:
if self._fd is not None:
try:
os.close(self._fd)
except OSError:
pass
self._fd = None
raise LockAcquisitionError(
f"Another linux-backuper instance is already running (locked on {self.pid_path}): {e}"
)
def release(self) -> None:
"""Release the file lock and remove the PID file."""
if self._fd is not None:
try:
fcntl.flock(self._fd, fcntl.LOCK_UN)
os.close(self._fd)
except OSError:
pass
self._fd = None
if os.path.isfile(self.pid_path):
try:
os.unlink(self.pid_path)
except OSError:
pass
def __enter__(self) -> "SingleInstanceLock":
self.acquire()
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.release()
+104
View File
@@ -0,0 +1,104 @@
"""Backup profile manager supporting built-in and user-defined custom profiles."""
import json
import os
from typing import Dict, List, Optional
from linux_backuper.core.constants import DEFAULT_CONFIG_PATH
from linux_backuper.models import ProfileConfig
class ProfileManager:
"""Manages built-in profiles (quick, system, full) and custom profiles."""
BUILTIN_PROFILES: Dict[str, ProfileConfig] = {
"quick": ProfileConfig(
name="quick",
description="Default lightweight snapshot of /etc and full host telemetry",
included_paths=["/etc"],
exclude_patterns=[
"*.sock", "*.fifo", "*.lock", "*.pid",
"/etc/mtab", "/etc/resolv.conf"
],
collect_users=True,
collect_kernel=True,
collect_storage=True,
collect_network=True,
collect_packages=True
),
"system": ProfileConfig(
name="system",
description="System configuration, /boot, systemd units and kernel state",
included_paths=["/etc", "/boot", "/usr/lib/systemd/system"],
exclude_patterns=[
"*.sock", "*.fifo", "*.lock", "*.pid",
"/etc/mtab", "/etc/resolv.conf"
],
collect_users=True,
collect_kernel=True,
collect_storage=True,
collect_network=True,
collect_packages=True
),
"full": ProfileConfig(
name="full",
description="Complete disaster-recovery profile including cron, NetworkManager and systemd state",
included_paths=[
"/etc", "/boot",
"/var/spool/cron",
"/var/lib/systemd",
"/var/lib/NetworkManager"
],
exclude_patterns=[
"*.sock", "*.fifo", "*.lock", "*.pid",
"/etc/mtab", "/etc/resolv.conf"
],
collect_users=True,
collect_kernel=True,
collect_storage=True,
collect_network=True,
collect_packages=True,
max_journal_mb=50
)
}
def __init__(self, config_path: str = DEFAULT_CONFIG_PATH):
self.config_path = config_path
self._profiles: Dict[str, ProfileConfig] = dict(self.BUILTIN_PROFILES)
self._load_custom_profiles()
def _load_custom_profiles(self) -> None:
"""Load optional user-defined profiles from JSON configuration."""
if not os.path.isfile(self.config_path):
return
try:
with open(self.config_path, "r", encoding="utf-8") as f:
data = json.load(f)
custom_dict = data.get("profiles", {})
for name, cfg in custom_dict.items():
self._profiles[name] = ProfileConfig(
name=name,
description=cfg.get("description", f"Custom profile '{name}'"),
included_paths=cfg.get("included_paths", ["/etc"]),
exclude_patterns=cfg.get("exclude_patterns", ["*.sock", "*.lock"]),
collect_users=cfg.get("collect_users", True),
collect_kernel=cfg.get("collect_kernel", True),
collect_storage=cfg.get("collect_storage", True),
collect_network=cfg.get("collect_network", True),
collect_packages=cfg.get("collect_packages", True),
max_journal_mb=cfg.get("max_journal_mb", 0)
)
except (OSError, json.JSONDecodeError):
pass
def get_profile(self, name: str) -> ProfileConfig:
"""Retrieve profile configuration by name. Raises KeyError if not found."""
if name not in self._profiles:
valid_names = ", ".join(self._profiles.keys())
raise KeyError(f"Unknown backup profile '{name}'. Available profiles: {valid_names}")
return self._profiles[name]
def list_profiles(self) -> List[ProfileConfig]:
"""List all available profiles."""
return list(self._profiles.values())
+60
View File
@@ -121,5 +121,65 @@ class TestCliTracerBullet(unittest.TestCase):
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_CORRUPTED)
def test_snapshot_sanitize_redacts_secrets(self):
# Create sensitive files in mock_etc
shadow_path = os.path.join(self.mock_etc, "shadow")
with open(shadow_path, "w") as f:
f.write("root:$6$secretpasswordhash:19000:0:99999:7:::\n")
ssh_key_path = os.path.join(self.mock_etc, "ssh_host_ed25519_key")
with open(ssh_key_path, "w") as f:
f.write("-----BEGIN OPENSSH PRIVATE KEY-----\nsecret\n-----END OPENSSH PRIVATE KEY-----\n")
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", self.mock_etc,
"--sanitize",
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
snap_data = json.loads(stdout.getvalue().strip())
archive_path = snap_data["archive_path"]
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
# Sensitive files must NOT be in archive data/
self.assertFalse(any("data" in n and "shadow" in n for n in names))
self.assertFalse(any("data" in n and "ssh_host_ed25519_key" in n for n in names))
# meta/sanitized.txt must exist and list them
self.assertIn("meta/sanitized.txt", names)
sanitized_log = tar.extractfile("meta/sanitized.txt").read().decode("utf-8")
self.assertIn("shadow", sanitized_log)
self.assertIn("ssh_host_ed25519_key", sanitized_log)
def test_snapshot_no_compression(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", self.mock_etc,
"--no-compression",
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
snap_data = json.loads(stdout.getvalue().strip())
archive_path = snap_data["archive_path"]
self.assertTrue(archive_path.endswith(".tar"))
# Verify it is openable as uncompressed tar
with tarfile.open(archive_path, "r:") as tar:
self.assertEqual(tar.getmembers()[0].name, "manifest.json")
# Verify command works on uncompressed tar
snap_id = snap_data["snapshot_id"]
with patch("sys.stdout", io.StringIO()):
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_SUCCESS)
if __name__ == "__main__":
unittest.main()
+51
View File
@@ -0,0 +1,51 @@
import os
import tempfile
import unittest
from linux_backuper.core.lock import SingleInstanceLock, LockAcquisitionError
class TestSingleInstanceLock(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="test_lock_")
self.pid_path = os.path.join(self.temp_dir, "test.pid")
def tearDown(self):
import shutil
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_lock_acquire_and_release(self):
lock1 = SingleInstanceLock(pid_path=self.pid_path)
self.assertTrue(lock1.acquire())
self.assertTrue(os.path.isfile(self.pid_path))
with open(self.pid_path, "r") as f:
pid = int(f.read().strip())
self.assertEqual(pid, os.getpid())
# Second lock attempt must fail
lock2 = SingleInstanceLock(pid_path=self.pid_path)
with self.assertRaises(LockAcquisitionError):
lock2.acquire()
# Release first lock
lock1.release()
# Now lock2 should succeed
self.assertTrue(lock2.acquire())
lock2.release()
def test_lock_context_manager(self):
with SingleInstanceLock(pid_path=self.pid_path):
self.assertTrue(os.path.isfile(self.pid_path))
# Nested lock should fail
lock2 = SingleInstanceLock(pid_path=self.pid_path)
with self.assertRaises(LockAcquisitionError):
lock2.acquire()
# After context exit, lock file is unlinked or released
lock3 = SingleInstanceLock(pid_path=self.pid_path)
self.assertTrue(lock3.acquire())
lock3.release()
if __name__ == "__main__":
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
import json
import os
import tempfile
import unittest
from linux_backuper.core.profiles import ProfileManager
from linux_backuper.models import ProfileConfig
class TestProfileManager(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="test_profiles_")
def tearDown(self):
import shutil
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_builtin_profiles_exist(self):
mgr = ProfileManager()
profiles = mgr.list_profiles()
names = [p.name for p in profiles]
self.assertIn("quick", names)
self.assertIn("system", names)
self.assertIn("full", names)
def test_quick_profile_paths(self):
mgr = ProfileManager()
quick = mgr.get_profile("quick")
self.assertEqual(quick.name, "quick")
self.assertIn("/etc", quick.included_paths)
self.assertNotIn("/boot", quick.included_paths)
def test_system_profile_paths(self):
mgr = ProfileManager()
system = mgr.get_profile("system")
self.assertIn("/etc", system.included_paths)
self.assertIn("/boot", system.included_paths)
def test_full_profile_paths(self):
mgr = ProfileManager()
full = mgr.get_profile("full")
self.assertIn("/etc", full.included_paths)
self.assertIn("/boot", full.included_paths)
self.assertIn("/var/spool/cron", full.included_paths)
self.assertIn("/var/lib/systemd", full.included_paths)
def test_custom_profile_from_config(self):
config_path = os.path.join(self.temp_dir, "linux-backuper.json")
custom_data = {
"profiles": {
"custom_web": {
"description": "Web server custom profile",
"included_paths": ["/etc", "/var/www/html"],
"exclude_patterns": ["*.log", "*.tmp"],
"collect_packages": True
}
}
}
with open(config_path, "w") as f:
json.dump(custom_data, f)
mgr = ProfileManager(config_path=config_path)
p = mgr.get_profile("custom_web")
self.assertEqual(p.name, "custom_web")
self.assertIn("/var/www/html", p.included_paths)
self.assertIn("*.log", p.exclude_patterns)
def test_unknown_profile_raises_key_error(self):
mgr = ProfileManager()
with self.assertRaises(KeyError):
mgr.get_profile("non_existent_profile_xyz")
if __name__ == "__main__":
unittest.main()