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

+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())