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 @@
|
||||
"""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()
|
||||
)
|
||||
Reference in new issue
Block a user