feat(core): implement slice 1 tracer bullet end-to-end skeleton
This commit is contained in:
1 parent
0aed5bb003
commit
2602b66a90
13 files changed
+882
-1
No files matched your search
@@ -0,0 +1,4 @@
|
||||
"""linux-backuper - Enterprise Linux system snapshot and configuration backup utility."""
|
||||
|
||||
__version__ = "1.0.0"
|
||||
__author__ = "wiredLAB"
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Entrypoint when executed as a module: python3 -m linux_backuper."""
|
||||
|
||||
import sys
|
||||
from linux_backuper.cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Command-line interface and dispatch for linux-backuper."""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
from typing import List, Optional
|
||||
|
||||
from linux_backuper import __version__
|
||||
from linux_backuper.core.archiver import SnapshotArchiver
|
||||
from linux_backuper.core.constants import (
|
||||
DEFAULT_BACKUP_DIR,
|
||||
EXIT_CORRUPTED,
|
||||
EXIT_GENERIC_ERROR,
|
||||
EXIT_PERM_DENIED,
|
||||
EXIT_PREFLIGHT_FAIL,
|
||||
EXIT_SUCCESS,
|
||||
)
|
||||
from linux_backuper.core.detector import detect_distro
|
||||
from linux_backuper.models import SnapshotManifest
|
||||
|
||||
def check_root_permissions() -> bool:
|
||||
"""Check if process has root privileges, respecting test overrides."""
|
||||
if os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT") == "1":
|
||||
return True
|
||||
try:
|
||||
return os.geteuid() == 0
|
||||
except AttributeError:
|
||||
return True
|
||||
|
||||
def handle_snapshot(args: argparse.Namespace) -> int:
|
||||
"""Execute snapshot command."""
|
||||
if not check_root_permissions():
|
||||
sys.stderr.write("[ERROR] Creating snapshots requires root privileges (uid 0).\n")
|
||||
return EXIT_PERM_DENIED
|
||||
|
||||
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
|
||||
try:
|
||||
os.makedirs(target_dir, exist_ok=True)
|
||||
except OSError as e:
|
||||
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)
|
||||
|
||||
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")
|
||||
|
||||
# Pass 1: Collect files & calculate checksums
|
||||
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 2: Create archive with manifest.json as the very first member
|
||||
try:
|
||||
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
|
||||
|
||||
if args.json:
|
||||
output_payload = {
|
||||
"snapshot_id": snapshot_id,
|
||||
"archive_path": archive_path,
|
||||
"profile": args.profile,
|
||||
"files_count": len(file_entries),
|
||||
"uncompressed_bytes": uncompressed_bytes,
|
||||
"compressed_bytes": manifest.stats.get("compressed_bytes", 0),
|
||||
"status": "success"
|
||||
}
|
||||
print(json.dumps(output_payload, indent=2))
|
||||
else:
|
||||
size_mb = manifest.stats.get("compressed_bytes", 0) / (1024 * 1024)
|
||||
sys.stdout.write(f"[SUCCESS] Snapshot created successfully: {archive_path} ({size_mb:.2f} MB, {len(file_entries)} files)\n")
|
||||
|
||||
return EXIT_SUCCESS
|
||||
|
||||
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()
|
||||
|
||||
if args.json:
|
||||
result = [s.to_dict() for s in snapshots]
|
||||
print(json.dumps(result, indent=2))
|
||||
return EXIT_SUCCESS
|
||||
|
||||
if not snapshots:
|
||||
sys.stdout.write(f"No snapshots found in {target_dir}.\n")
|
||||
return EXIT_SUCCESS
|
||||
|
||||
sys.stdout.write(f"{'SNAPSHOT ID':<40} {'PROFILE':<10} {'FILES':<8} {'SIZE (MB)':<10} {'CREATED AT':<25}\n")
|
||||
sys.stdout.write("-" * 95 + "\n")
|
||||
for s in snapshots:
|
||||
size_mb = s.stats.get("compressed_bytes", 0) / (1024 * 1024)
|
||||
sys.stdout.write(f"{s.snapshot_id:<40} {s.profile:<10} {s.stats.get('file_count', 0):<8} {size_mb:<10.2f} {s.created_at[:19]:<25}\n")
|
||||
|
||||
return EXIT_SUCCESS
|
||||
|
||||
def handle_verify(args: argparse.Namespace) -> int:
|
||||
"""Execute verify command."""
|
||||
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
|
||||
snapshot_id = args.snapshot_id
|
||||
|
||||
# Resolve filename
|
||||
if not snapshot_id.endswith(".tar.gz"):
|
||||
filename = f"{snapshot_id}.tar.gz"
|
||||
else:
|
||||
filename = snapshot_id
|
||||
|
||||
archive_path = os.path.join(target_dir, filename) if not os.path.isabs(filename) else filename
|
||||
is_valid, msg = SnapshotArchiver.verify_archive(archive_path)
|
||||
|
||||
if args.json:
|
||||
print(json.dumps({"snapshot_id": snapshot_id, "valid": is_valid, "message": msg}, indent=2))
|
||||
else:
|
||||
if is_valid:
|
||||
sys.stdout.write(f"[SUCCESS] {msg}: {archive_path}\n")
|
||||
else:
|
||||
sys.stderr.write(f"[ERROR] Integrity check failed: {msg}\n")
|
||||
|
||||
return EXIT_SUCCESS if is_valid else EXIT_CORRUPTED
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
"""Construct CLI argument parser."""
|
||||
common_parser = argparse.ArgumentParser(add_help=False)
|
||||
common_parser.add_argument("--json", action="store_true", help="Output machine-readable JSON to stdout")
|
||||
common_parser.add_argument("--verbose", action="store_true", help="Enable detailed diagnostic logging")
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="linux-backuper",
|
||||
description="Enterprise Linux system snapshot and configuration backup utility.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
parents=[common_parser]
|
||||
)
|
||||
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {__version__}")
|
||||
|
||||
subparsers = parser.add_subparsers(dest="subcommand", help="Available sub-commands")
|
||||
|
||||
# Snapshot command
|
||||
snap_parser = subparsers.add_parser("snapshot", help="Capture a new system state snapshot", parents=[common_parser])
|
||||
snap_parser.add_argument("--profile", default="quick", help="Backup profile (default: quick)")
|
||||
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")
|
||||
|
||||
# List command
|
||||
list_parser = subparsers.add_parser("list", help="List existing local snapshots", parents=[common_parser])
|
||||
list_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory to scan for snapshots")
|
||||
|
||||
# Verify command
|
||||
verify_parser = subparsers.add_parser("verify", help="Verify snapshot cryptographic integrity", parents=[common_parser])
|
||||
verify_parser.add_argument("snapshot_id", help="Snapshot ID or archive filename to verify")
|
||||
verify_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot")
|
||||
|
||||
return parser
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
"""Main CLI entrypoint."""
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if not args.subcommand:
|
||||
parser.print_help()
|
||||
return EXIT_SUCCESS
|
||||
|
||||
if args.subcommand == "snapshot":
|
||||
return handle_snapshot(args)
|
||||
elif args.subcommand == "list":
|
||||
return handle_list(args)
|
||||
elif args.subcommand == "verify":
|
||||
return handle_verify(args)
|
||||
|
||||
return EXIT_SUCCESS
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
"""Core modules for linux-backuper."""
|
||||
@@ -0,0 +1,260 @@
|
||||
"""Archive creation, extraction, and verification using Python standard library."""
|
||||
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import tarfile
|
||||
import time
|
||||
from typing import Dict, List, Optional, Tuple, Any
|
||||
|
||||
from linux_backuper.models import SnapshotManifest
|
||||
|
||||
BUFFER_SIZE = 64 * 1024 # 64 KB chunks for hashing and streaming
|
||||
|
||||
def calculate_file_sha256(filepath: str) -> str:
|
||||
"""Calculate SHA-256 checksum of a file."""
|
||||
hasher = hashlib.sha256()
|
||||
with open(filepath, "rb") as f:
|
||||
while chunk := f.read(BUFFER_SIZE):
|
||||
hasher.update(chunk)
|
||||
return hasher.hexdigest()
|
||||
|
||||
def is_socket_or_fifo(filepath: str) -> bool:
|
||||
"""Check if path is a UNIX socket, named pipe (FIFO) or character device."""
|
||||
try:
|
||||
st = os.lstat(filepath)
|
||||
return stat.S_ISSOCK(st.st_mode) or stat.S_ISFIFO(st.st_mode)
|
||||
except OSError:
|
||||
return True
|
||||
|
||||
class SnapshotArchiver:
|
||||
"""Manages creation, listing, and verification of snapshot archives."""
|
||||
|
||||
def __init__(self, target_dir: str, compression: str = "gzip"):
|
||||
self.target_dir = target_dir
|
||||
self.compression = "gzip" if compression in ("gz", "gzip") else "none"
|
||||
|
||||
def _ensure_target_dir() -> None:
|
||||
pass
|
||||
|
||||
def _ensure_target_dir_inst(self) -> None:
|
||||
"""Ensure target directory exists with 0700 permissions."""
|
||||
os.makedirs(self.target_dir, exist_ok=True)
|
||||
try:
|
||||
os.chmod(self.target_dir, 0o700)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def collect_file_list(
|
||||
self,
|
||||
paths: List[str],
|
||||
exclude_patterns: Optional[List[str]] = None
|
||||
) -> Tuple[List[Tuple[str, str]], Dict[str, str], int]:
|
||||
"""
|
||||
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
|
||||
"""
|
||||
file_entries: List[Tuple[str, str]] = []
|
||||
files_sha256: Dict[str, str] = {}
|
||||
total_bytes = 0
|
||||
exclude_patterns = exclude_patterns or []
|
||||
|
||||
for base_path in paths:
|
||||
abs_base = os.path.abspath(base_path)
|
||||
if not os.path.exists(abs_base):
|
||||
continue
|
||||
|
||||
if os.path.isfile(abs_base) or os.path.islink(abs_base):
|
||||
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)
|
||||
files_sha256[rel_name] = sha
|
||||
total_bytes += os.path.getsize(abs_base)
|
||||
continue
|
||||
|
||||
# Directory tree traversal
|
||||
for root, dirs, files in os.walk(abs_base, followlinks=False):
|
||||
# Filter subdirectories in place
|
||||
dirs[:] = [d for d in dirs if not any(p in d for p in exclude_patterns)]
|
||||
|
||||
for filename in files:
|
||||
abs_filepath = os.path.join(root, filename)
|
||||
if is_socket_or_fifo(abs_filepath):
|
||||
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)
|
||||
|
||||
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)
|
||||
except (OSError, IOError):
|
||||
pass
|
||||
|
||||
return file_entries, files_sha256, total_bytes
|
||||
|
||||
def create_snapshot_archive(
|
||||
self,
|
||||
snapshot_id: str,
|
||||
manifest: SnapshotManifest,
|
||||
file_entries: List[Tuple[str, str]]
|
||||
) -> str:
|
||||
"""
|
||||
Create atomic .tar.gz archive with manifest.json as the very first member.
|
||||
Enforces 0600 file permissions.
|
||||
"""
|
||||
self._ensure_target_dir_inst()
|
||||
ext = ".tar.gz" if self.compression == "gzip" else ".tar"
|
||||
final_archive_path = os.path.join(self.target_dir, f"{snapshot_id}{ext}")
|
||||
temp_archive_path = os.path.join(self.target_dir, f".{snapshot_id}.tmp{ext}")
|
||||
|
||||
# Encode manifest JSON bytes
|
||||
manifest_dict = manifest.to_dict()
|
||||
manifest_bytes = json.dumps(manifest_dict, indent=2, sort_keys=True).encode("utf-8")
|
||||
|
||||
# Open temp archive for writing with gzip or plain tar
|
||||
tar_mode = "w:gz" if self.compression == "gzip" else "w:"
|
||||
with tarfile.open(temp_archive_path, tar_mode) as tar:
|
||||
# 1. ADD MANIFEST.JSON AS THE VERY FIRST MEMBER
|
||||
manifest_info = tarfile.TarInfo(name="manifest.json")
|
||||
manifest_info.size = len(manifest_bytes)
|
||||
manifest_info.mtime = int(time.time())
|
||||
manifest_info.mode = 0o600
|
||||
manifest_info.type = tarfile.REGTYPE
|
||||
|
||||
import io
|
||||
tar.addfile(tarinfo=manifest_info, fileobj=io.BytesIO(manifest_bytes))
|
||||
|
||||
# 2. ADD ALL COLLECTED DATA FILES
|
||||
for abs_path, arc_path in file_entries:
|
||||
try:
|
||||
tar.add(abs_path, arcname=arc_path, recursive=False)
|
||||
except (OSError, IOError):
|
||||
pass
|
||||
|
||||
# Set strict 0600 permissions
|
||||
try:
|
||||
os.chmod(temp_archive_path, 0o600)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Atomic rename to final path
|
||||
os.replace(temp_archive_path, final_archive_path)
|
||||
|
||||
# Update manifest compressed size stat
|
||||
compressed_size = os.path.getsize(final_archive_path)
|
||||
manifest.stats["compressed_bytes"] = compressed_size
|
||||
|
||||
return final_archive_path
|
||||
|
||||
@staticmethod
|
||||
def read_manifest_from_archive(archive_path: str) -> SnapshotManifest:
|
||||
"""
|
||||
Read manifest.json from the first member of the archive stream.
|
||||
Ultra-fast: avoids decompressing the rest of the archive.
|
||||
"""
|
||||
with tarfile.open(archive_path, "r:*") as tar:
|
||||
first_member = tar.next()
|
||||
if not first_member or first_member.name != "manifest.json":
|
||||
# Fallback: scan for manifest.json if not first
|
||||
member = tar.getmember("manifest.json")
|
||||
else:
|
||||
member = first_member
|
||||
|
||||
manifest_file = tar.extractfile(member)
|
||||
if not manifest_file:
|
||||
raise ValueError(f"Could not read manifest from {archive_path}")
|
||||
|
||||
data = json.loads(manifest_file.read().decode("utf-8"))
|
||||
return SnapshotManifest.from_dict(data)
|
||||
|
||||
@staticmethod
|
||||
def verify_archive(archive_path: str) -> Tuple[bool, str]:
|
||||
"""
|
||||
Verify gzip stream integrity and all file SHA-256 checksums against manifest.json.
|
||||
Returns (is_valid, error_message).
|
||||
"""
|
||||
if not os.path.isfile(archive_path):
|
||||
return False, f"Archive not found: {archive_path}"
|
||||
|
||||
# 1. Check if file is gzip by inspecting header
|
||||
is_gz = False
|
||||
try:
|
||||
with open(archive_path, "rb") as f:
|
||||
header = f.read(2)
|
||||
is_gz = (header == b"\x1f\x8b")
|
||||
except OSError as e:
|
||||
return False, f"Cannot open archive: {e}"
|
||||
|
||||
# If gzipped, verify complete stream integrity
|
||||
if is_gz:
|
||||
try:
|
||||
with gzip.open(archive_path, "rb") as gz:
|
||||
while gz.read(BUFFER_SIZE):
|
||||
pass
|
||||
except Exception as e:
|
||||
return False, f"Gzip stream corrupted: {e}"
|
||||
|
||||
# 2. Manifest and member checksum verification
|
||||
try:
|
||||
with tarfile.open(archive_path, "r:*") as tar:
|
||||
# Read manifest
|
||||
try:
|
||||
manifest_member = tar.getmember("manifest.json")
|
||||
manifest_data = json.loads(tar.extractfile(manifest_member).read().decode("utf-8"))
|
||||
except Exception as e:
|
||||
return False, f"Invalid or missing manifest.json: {e}"
|
||||
|
||||
expected_hashes: Dict[str, str] = manifest_data.get("files_sha256", {})
|
||||
|
||||
for arc_name, expected_sha in expected_hashes.items():
|
||||
try:
|
||||
member = tar.getmember(arc_name)
|
||||
except KeyError:
|
||||
return False, f"Missing file in archive: {arc_name}"
|
||||
|
||||
if member.isreg():
|
||||
f = tar.extractfile(member)
|
||||
if not f:
|
||||
return False, f"Unable to read file: {arc_name}"
|
||||
|
||||
hasher = hashlib.sha256()
|
||||
while chunk := f.read(BUFFER_SIZE):
|
||||
hasher.update(chunk)
|
||||
actual_sha = hasher.hexdigest()
|
||||
|
||||
if actual_sha != expected_sha:
|
||||
return False, f"Checksum mismatch for {arc_name}: expected {expected_sha}, got {actual_sha}"
|
||||
|
||||
except Exception as e:
|
||||
return False, f"Tar archive corrupted: {e}"
|
||||
|
||||
return True, "Integrity verified successfully"
|
||||
|
||||
def list_snapshots(self) -> List[SnapshotManifest]:
|
||||
"""List all valid snapshots in the target directory."""
|
||||
if not os.path.isdir(self.target_dir):
|
||||
return []
|
||||
|
||||
snapshots: List[SnapshotManifest] = []
|
||||
for filename in sorted(os.listdir(self.target_dir), reverse=True):
|
||||
if filename.endswith(".tar.gz") and not filename.startswith("."):
|
||||
filepath = os.path.join(self.target_dir, filename)
|
||||
try:
|
||||
manifest = self.read_manifest_from_archive(filepath)
|
||||
snapshots.append(manifest)
|
||||
except Exception:
|
||||
pass
|
||||
return snapshots
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Constants and exit codes for linux-backuper."""
|
||||
|
||||
# Exit Codes
|
||||
EXIT_SUCCESS = 0
|
||||
EXIT_GENERIC_ERROR = 1
|
||||
EXIT_PREFLIGHT_FAIL = 2
|
||||
EXIT_CORRUPTED = 3
|
||||
EXIT_PERM_DENIED = 4
|
||||
EXIT_DRY_RUN = 5
|
||||
|
||||
# Default filesystem locations
|
||||
DEFAULT_BACKUP_DIR = "/var/backups/linux-backuper"
|
||||
DEFAULT_CONFIG_PATH = "/etc/linux-backuper.json"
|
||||
DEFAULT_PID_PATH = "/var/run/linux-backuper.pid"
|
||||
DEFAULT_LOG_DIR = "/var/log/linux-backuper"
|
||||
|
||||
# Minimum free disk space in megabytes for preflight check
|
||||
MIN_FREE_DISK_MB = 1024
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Linux distribution and operating system detector."""
|
||||
|
||||
import os
|
||||
import platform
|
||||
from typing import Dict, Optional
|
||||
from linux_backuper.models import OsInfo
|
||||
|
||||
DEFAULT_OS_RELEASE_PATH = "/etc/os-release"
|
||||
FALLBACK_OS_RELEASE_PATH = "/usr/lib/os-release"
|
||||
|
||||
def parse_os_release(content: str) -> Dict[str, str]:
|
||||
"""Parse key-value pairs from os-release format string."""
|
||||
data = {}
|
||||
for line in content.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if "=" in line:
|
||||
key, val = line.split("=", 1)
|
||||
key = key.strip().lower()
|
||||
val = val.strip().strip("\"'")
|
||||
data[key] = val
|
||||
|
||||
distro_id = data.get("id", "linux").lower()
|
||||
distro_name = data.get("name", "Linux")
|
||||
version_id = data.get("version_id", data.get("build_id", "rolling"))
|
||||
|
||||
return {
|
||||
"id": distro_id,
|
||||
"name": distro_name,
|
||||
"version_id": version_id,
|
||||
"id_like": data.get("id_like", "")
|
||||
}
|
||||
|
||||
def detect_distro(os_release_path: Optional[str] = None) -> OsInfo:
|
||||
"""Detect current operating system distribution and kernel release."""
|
||||
content = ""
|
||||
candidate_paths = [os_release_path] if os_release_path else [DEFAULT_OS_RELEASE_PATH, FALLBACK_OS_RELEASE_PATH]
|
||||
|
||||
for path in candidate_paths:
|
||||
if path and os.path.isfile(path):
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
||||
content = f.read()
|
||||
break
|
||||
except (OSError, IOError):
|
||||
pass
|
||||
|
||||
if content:
|
||||
parsed = parse_os_release(content)
|
||||
distro_id = parsed["id"]
|
||||
distro_name = parsed["name"]
|
||||
version_id = parsed["version_id"]
|
||||
else:
|
||||
# Fallback for non-Linux or testing environments
|
||||
distro_id = platform.system().lower()
|
||||
distro_name = platform.system()
|
||||
version_id = platform.release()
|
||||
|
||||
return OsInfo(
|
||||
distro_id=distro_id,
|
||||
distro_name=distro_name,
|
||||
version_id=version_id,
|
||||
kernel=platform.release(),
|
||||
arch=platform.machine()
|
||||
)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Data transfer objects and models for linux-backuper."""
|
||||
|
||||
from dataclasses import dataclass, asdict, field
|
||||
from typing import Dict, List, Optional, Any
|
||||
|
||||
@dataclass
|
||||
class OsInfo:
|
||||
distro_id: str
|
||||
distro_name: str
|
||||
version_id: str
|
||||
kernel: str
|
||||
arch: str
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "OsInfo":
|
||||
return cls(
|
||||
distro_id=data.get("distro_id", "unknown"),
|
||||
distro_name=data.get("distro_name", "Unknown Linux"),
|
||||
version_id=data.get("version_id", "0"),
|
||||
kernel=data.get("kernel", ""),
|
||||
arch=data.get("arch", "")
|
||||
)
|
||||
|
||||
@dataclass
|
||||
class PackageItem:
|
||||
name: str
|
||||
version: str
|
||||
arch: str
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "PackageItem":
|
||||
return cls(
|
||||
name=data["name"],
|
||||
version=data["version"],
|
||||
arch=data.get("arch", "")
|
||||
)
|
||||
|
||||
@dataclass
|
||||
class ProfileConfig:
|
||||
name: str
|
||||
description: str
|
||||
included_paths: List[str]
|
||||
exclude_patterns: List[str] = field(default_factory=list)
|
||||
collect_users: bool = True
|
||||
collect_kernel: bool = True
|
||||
collect_storage: bool = True
|
||||
collect_network: bool = True
|
||||
collect_packages: bool = True
|
||||
max_journal_mb: int = 0
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
@dataclass
|
||||
class SnapshotManifest:
|
||||
schema_version: str
|
||||
snapshot_id: str
|
||||
created_at: str
|
||||
hostname: str
|
||||
profile: str
|
||||
compression: str
|
||||
os: Dict[str, Any]
|
||||
package_manager: str
|
||||
package_count: int
|
||||
included_paths: List[str]
|
||||
stats: Dict[str, Any]
|
||||
files_sha256: Dict[str, str] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "SnapshotManifest":
|
||||
return cls(
|
||||
schema_version=data.get("schema_version", "1.0"),
|
||||
snapshot_id=data["snapshot_id"],
|
||||
created_at=data["created_at"],
|
||||
hostname=data["hostname"],
|
||||
profile=data.get("profile", "quick"),
|
||||
compression=data.get("compression", "gzip"),
|
||||
os=data.get("os", {}),
|
||||
package_manager=data.get("package_manager", "none"),
|
||||
package_count=data.get("package_count", 0),
|
||||
included_paths=data.get("included_paths", []),
|
||||
stats=data.get("stats", {}),
|
||||
files_sha256=data.get("files_sha256", {})
|
||||
)
|
||||
Reference in new issue
Block a user