feat(profiles): implement slice 3 profile system, flock concurrency, and sanitize archiver
This commit is contained in:
1 parent
66ca179937
commit
646bd9d145
8 files changed
+536
-69
No files matched your search
+108
-61
@@ -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])
|
||||
|
||||
Reference in new issue
Block a user