feat(restore): implement slice 4 snapshot management, diff engine, and safe restore
This commit is contained in:
1 parent
646bd9d145
commit
8d4127de30
9 files changed
+1386
-4
No files matched your search
+116
-1
@@ -9,7 +9,7 @@ import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from linux_backuper.cli import main
|
||||
from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_CORRUPTED
|
||||
from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_CORRUPTED, EXIT_DRY_RUN
|
||||
|
||||
class TestCliTracerBullet(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -181,5 +181,120 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
|
||||
self.assertEqual(exit_code, EXIT_SUCCESS)
|
||||
|
||||
def test_show_command(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
|
||||
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
|
||||
|
||||
# Text mode
|
||||
stdout_show = io.StringIO()
|
||||
with patch("sys.stdout", stdout_show):
|
||||
exit_code = main(["show", snap_id, "--target-dir", self.backup_dir])
|
||||
self.assertEqual(exit_code, EXIT_SUCCESS)
|
||||
self.assertIn("Snapshot ID:", stdout_show.getvalue())
|
||||
self.assertIn(snap_id, stdout_show.getvalue())
|
||||
|
||||
# JSON mode
|
||||
stdout_json = io.StringIO()
|
||||
with patch("sys.stdout", stdout_json):
|
||||
exit_code = main(["show", snap_id, "--target-dir", self.backup_dir, "--json"])
|
||||
self.assertEqual(exit_code, EXIT_SUCCESS)
|
||||
data = json.loads(stdout_json.getvalue().strip())
|
||||
self.assertEqual(data["snapshot_id"], snap_id)
|
||||
|
||||
def test_extract_command(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
|
||||
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
|
||||
|
||||
dest_file = os.path.join(self.temp_dir, "extracted_hostname.txt")
|
||||
# Extract filename
|
||||
sample_path = [f for f in os.listdir(self.mock_etc) if f == "hostname"][0]
|
||||
exit_code = main([
|
||||
"extract", snap_id,
|
||||
"--file", sample_path,
|
||||
"--out", dest_file,
|
||||
"--target-dir", self.backup_dir
|
||||
])
|
||||
self.assertEqual(exit_code, EXIT_SUCCESS)
|
||||
self.assertTrue(os.path.isfile(dest_file))
|
||||
with open(dest_file, "r") as f:
|
||||
self.assertEqual(f.read(), "test-host.local\n")
|
||||
|
||||
def test_diff_command(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
|
||||
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
|
||||
|
||||
# Modify sample.conf on mock etc
|
||||
with open(os.path.join(self.mock_etc, "sample.conf"), "w") as f:
|
||||
f.write("key=modified_value\n")
|
||||
|
||||
# Test live diff
|
||||
stdout_diff = io.StringIO()
|
||||
with patch("sys.stdout", stdout_diff):
|
||||
exit_code = main([
|
||||
"diff", snap_id,
|
||||
"--target-dir", self.backup_dir,
|
||||
"--target-root", self.temp_dir,
|
||||
"--json"
|
||||
])
|
||||
self.assertEqual(exit_code, EXIT_SUCCESS)
|
||||
diff_data = json.loads(stdout_diff.getvalue().strip())
|
||||
self.assertEqual(diff_data["type"], "live_vs_snapshot")
|
||||
self.assertTrue(any("sample.conf" in f for f in diff_data["files"]["modified"]))
|
||||
|
||||
def test_restore_dry_run_exits_with_code_5(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
|
||||
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
|
||||
|
||||
# Default restore (no --force) must return EXIT_DRY_RUN (5)
|
||||
stdout_restore = io.StringIO()
|
||||
with patch("sys.stdout", stdout_restore):
|
||||
exit_code = main([
|
||||
"restore", snap_id,
|
||||
"--target-dir", self.backup_dir,
|
||||
"--target-root", self.temp_dir
|
||||
])
|
||||
self.assertEqual(exit_code, EXIT_DRY_RUN)
|
||||
self.assertIn("RESTORE EXECUTION PLAN (Dry Run)", stdout_restore.getvalue())
|
||||
|
||||
def test_restore_force_executes_successfully(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
|
||||
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
|
||||
|
||||
# Alter sample.conf
|
||||
with open(os.path.join(self.mock_etc, "sample.conf"), "w") as f:
|
||||
f.write("key=tampered_value\n")
|
||||
|
||||
# Restore with --force and non-root test override
|
||||
pid_file = os.path.join(self.temp_dir, "restore_test.pid")
|
||||
stdout_restore = io.StringIO()
|
||||
with patch("sys.stdout", stdout_restore), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
exit_code = main([
|
||||
"restore", snap_id,
|
||||
"--force",
|
||||
"--target-dir", self.backup_dir,
|
||||
"--target-root", self.temp_dir,
|
||||
"--pid-path", pid_file,
|
||||
"--json"
|
||||
])
|
||||
self.assertEqual(exit_code, EXIT_SUCCESS)
|
||||
res = json.loads(stdout_restore.getvalue().strip())
|
||||
self.assertEqual(res["status"], "success")
|
||||
self.assertTrue(res["safety_snapshot_id"].startswith("pre_restore_"))
|
||||
|
||||
# Check sample.conf restored
|
||||
with open(os.path.join(self.mock_etc, "sample.conf"), "r") as f:
|
||||
self.assertEqual(f.read(), "key=value\n")
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Unit tests for DiffEngine."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from linux_backuper.core.archiver import SnapshotArchiver
|
||||
from linux_backuper.core.diff import DiffEngine
|
||||
from linux_backuper.models import SnapshotManifest
|
||||
|
||||
class TestDiffEngine(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.test_dir = tempfile.mkdtemp(prefix="test_diff_")
|
||||
self.backup_dir = os.path.join(self.test_dir, "backups")
|
||||
os.makedirs(self.backup_dir, exist_ok=True)
|
||||
|
||||
self.mock_root = os.path.join(self.test_dir, "root")
|
||||
self.mock_etc = os.path.join(self.mock_root, "etc")
|
||||
os.makedirs(self.mock_etc, exist_ok=True)
|
||||
|
||||
# File A
|
||||
with open(os.path.join(self.mock_etc, "hosts"), "w") as f:
|
||||
f.write("127.0.0.1 localhost\n")
|
||||
# File B
|
||||
with open(os.path.join(self.mock_etc, "issue"), "w") as f:
|
||||
f.write("Test Linux\n")
|
||||
|
||||
# Snapshot 1
|
||||
archiver = SnapshotArchiver(target_dir=self.backup_dir)
|
||||
entries1, sha1, bytes1, _ = archiver.collect_file_list([self.mock_etc])
|
||||
|
||||
# Write fake meta/packages.txt into archive
|
||||
temp_meta = os.path.join(self.test_dir, "meta1")
|
||||
os.makedirs(temp_meta, exist_ok=True)
|
||||
pkg_file1 = os.path.join(temp_meta, "packages.txt")
|
||||
with open(pkg_file1, "w") as f:
|
||||
f.write("bash 5.1.0\ncoreutils 8.32\ncurl 7.74.0\n")
|
||||
|
||||
entries1.append((pkg_file1, "meta/packages.txt"))
|
||||
sha1["meta/packages.txt"] = "dummy"
|
||||
|
||||
m1 = SnapshotManifest(
|
||||
schema_version="1.0",
|
||||
snapshot_id="snap1",
|
||||
created_at="2026-10-01T12:00:00Z",
|
||||
hostname="host1",
|
||||
profile="quick",
|
||||
compression="gzip",
|
||||
os={"distro_id": "debian", "distro_name": "Debian", "version_id": "12", "kernel": "6.1", "arch": "x86_64"},
|
||||
package_manager="dpkg",
|
||||
package_count=3,
|
||||
included_paths=[self.mock_etc],
|
||||
stats={"file_count": len(entries1), "uncompressed_bytes": bytes1, "compressed_bytes": 0},
|
||||
files_sha256=sha1
|
||||
)
|
||||
self.archive1 = archiver.create_snapshot_archive("snap1", m1, entries1)
|
||||
|
||||
# Modify file A, delete file B, add file C for Snapshot 2
|
||||
with open(os.path.join(self.mock_etc, "hosts"), "w") as f:
|
||||
f.write("127.0.0.1 localhost\n192.168.1.1 router\n")
|
||||
os.remove(os.path.join(self.mock_etc, "issue"))
|
||||
with open(os.path.join(self.mock_etc, "resolv.conf"), "w") as f:
|
||||
f.write("nameserver 1.1.1.1\n")
|
||||
|
||||
entries2, sha2, bytes2, _ = archiver.collect_file_list([self.mock_etc])
|
||||
|
||||
temp_meta2 = os.path.join(self.test_dir, "meta2")
|
||||
os.makedirs(temp_meta2, exist_ok=True)
|
||||
pkg_file2 = os.path.join(temp_meta2, "packages.txt")
|
||||
with open(pkg_file2, "w") as f:
|
||||
f.write("bash 5.2.0\ncoreutils 8.32\nwget 1.21\n") # bash upgraded, curl removed, wget added
|
||||
|
||||
entries2.append((pkg_file2, "meta/packages.txt"))
|
||||
sha2["meta/packages.txt"] = "dummy2"
|
||||
|
||||
m2 = SnapshotManifest(
|
||||
schema_version="1.0",
|
||||
snapshot_id="snap2",
|
||||
created_at="2026-10-02T12:00:00Z",
|
||||
hostname="host1",
|
||||
profile="quick",
|
||||
compression="gzip",
|
||||
os={"distro_id": "debian", "distro_name": "Debian", "version_id": "12", "kernel": "6.1", "arch": "x86_64"},
|
||||
package_manager="dpkg",
|
||||
package_count=3,
|
||||
included_paths=[self.mock_etc],
|
||||
stats={"file_count": len(entries2), "uncompressed_bytes": bytes2, "compressed_bytes": 0},
|
||||
files_sha256=sha2
|
||||
)
|
||||
self.archive2 = archiver.create_snapshot_archive("snap2", m2, entries2)
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.test_dir, ignore_errors=True)
|
||||
|
||||
def test_diff_snapshots(self):
|
||||
engine = DiffEngine(target_dir=self.backup_dir)
|
||||
res = engine.diff_snapshots("snap1", "snap2")
|
||||
|
||||
self.assertEqual(res["type"], "snapshot_vs_snapshot")
|
||||
self.assertEqual(res["snapshot_1"], "snap1")
|
||||
self.assertEqual(res["snapshot_2"], "snap2")
|
||||
|
||||
files = res["files"]
|
||||
# hosts is modified
|
||||
self.assertTrue(any("hosts" in f for f in files["modified"]))
|
||||
# resolv.conf is added
|
||||
self.assertTrue(any("resolv.conf" in f for f in files["added"]))
|
||||
# issue is removed
|
||||
self.assertTrue(any("issue" in f for f in files["removed"]))
|
||||
|
||||
# Check packages
|
||||
pkgs = res["packages"]
|
||||
self.assertIn("wget", pkgs["added"])
|
||||
self.assertIn("curl", pkgs["removed"])
|
||||
self.assertIn("bash", pkgs["changed"])
|
||||
self.assertEqual(pkgs["changed"]["bash"]["old"], "5.1.0")
|
||||
self.assertEqual(pkgs["changed"]["bash"]["new"], "5.2.0")
|
||||
|
||||
def test_diff_with_live(self):
|
||||
engine = DiffEngine(target_dir=self.backup_dir)
|
||||
# Compare live mock_root against snap1
|
||||
# Currently mock_root has modified hosts, deleted issue, added resolv.conf
|
||||
res = engine.diff_with_live("snap1", target_root=self.mock_root)
|
||||
|
||||
self.assertEqual(res["type"], "live_vs_snapshot")
|
||||
files = res["files"]
|
||||
self.assertTrue(any("hosts" in f for f in files["modified"]))
|
||||
self.assertTrue(any("issue" in f for f in files["missing_on_live"]))
|
||||
self.assertTrue(any("resolv.conf" in f for f in files["added_on_live"]))
|
||||
|
||||
def test_generate_unified_file_diff(self):
|
||||
engine = DiffEngine(target_dir=self.backup_dir)
|
||||
diff_text = engine.generate_unified_file_diff("snap1", "etc/hosts", target_root=self.mock_root)
|
||||
self.assertIsNotNone(diff_text)
|
||||
self.assertIn("+192.168.1.1 router", diff_text)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Unit tests for SafeRestoreEngine."""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from linux_backuper.core.archiver import SnapshotArchiver
|
||||
from linux_backuper.core.restore import SafeRestoreEngine, DryRunException
|
||||
from linux_backuper.models import SnapshotManifest
|
||||
|
||||
class TestSafeRestoreEngine(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.test_dir = tempfile.mkdtemp(prefix="test_restore_")
|
||||
self.backup_dir = os.path.join(self.test_dir, "backups")
|
||||
os.makedirs(self.backup_dir, exist_ok=True)
|
||||
|
||||
self.mock_root = os.path.join(self.test_dir, "root")
|
||||
self.mock_etc = os.path.join(self.mock_root, "etc")
|
||||
os.makedirs(self.mock_etc, exist_ok=True)
|
||||
|
||||
# Create files to back up
|
||||
self.hosts_path = os.path.join(self.mock_etc, "hosts")
|
||||
with open(self.hosts_path, "w") as f:
|
||||
f.write("127.0.0.1 localhost\n")
|
||||
|
||||
self.resolv_path = os.path.join(self.mock_etc, "resolv.conf")
|
||||
with open(self.resolv_path, "w") as f:
|
||||
f.write("nameserver 8.8.8.8\n")
|
||||
|
||||
self.fstab_path = os.path.join(self.mock_etc, "fstab")
|
||||
with open(self.fstab_path, "w") as f:
|
||||
f.write("/dev/sda1 / ext4 defaults 0 1\n")
|
||||
|
||||
# Create netplan file (sensitive network)
|
||||
self.netplan_dir = os.path.join(self.mock_etc, "netplan")
|
||||
os.makedirs(self.netplan_dir, exist_ok=True)
|
||||
self.net_cfg = os.path.join(self.netplan_dir, "01-netcfg.yaml")
|
||||
with open(self.net_cfg, "w") as f:
|
||||
f.write("network: {version: 2}\n")
|
||||
|
||||
# Create base snapshot
|
||||
archiver = SnapshotArchiver(target_dir=self.backup_dir)
|
||||
entries, sha, uncompressed, _ = archiver.collect_file_list([self.mock_etc])
|
||||
|
||||
m = SnapshotManifest(
|
||||
schema_version="1.0",
|
||||
snapshot_id="test_snap",
|
||||
created_at="2026-10-01T12:00:00Z",
|
||||
hostname="host1",
|
||||
profile="quick",
|
||||
compression="gzip",
|
||||
os={"distro_id": "debian", "distro_name": "Debian", "version_id": "12", "kernel": "6.1", "arch": "x86_64"},
|
||||
package_manager="dpkg",
|
||||
package_count=0,
|
||||
included_paths=[self.mock_etc],
|
||||
stats={"file_count": len(entries), "uncompressed_bytes": uncompressed, "compressed_bytes": 0},
|
||||
files_sha256=sha
|
||||
)
|
||||
self.archive_path = archiver.create_snapshot_archive("test_snap", m, entries)
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.test_dir, ignore_errors=True)
|
||||
|
||||
def test_plan_restore_skips_dynamic_and_fstab(self):
|
||||
engine = SafeRestoreEngine(target_dir=self.backup_dir)
|
||||
plan = engine.plan_restore("test_snap", target_root=self.mock_root, include_fstab=False)
|
||||
|
||||
actions_by_path = {item.rel_path: item for item in plan.items}
|
||||
|
||||
# resolv.conf must be skipped (dynamic system file)
|
||||
resolv_item = [item for item in plan.items if "resolv.conf" in item.rel_path][0]
|
||||
self.assertEqual(resolv_item.action, "skip")
|
||||
self.assertIn("volatile", resolv_item.reason.lower())
|
||||
|
||||
# fstab must be skipped unless include_fstab is set
|
||||
fstab_item = [item for item in plan.items if "fstab" in item.rel_path][0]
|
||||
self.assertEqual(fstab_item.action, "skip")
|
||||
self.assertIn("fstab", fstab_item.reason.lower())
|
||||
|
||||
# netplan must be flagged as sensitive network
|
||||
net_item = [item for item in plan.items if "01-netcfg.yaml" in item.rel_path][0]
|
||||
self.assertTrue(net_item.is_sensitive_network)
|
||||
|
||||
def test_dry_run_raises_and_modifies_nothing(self):
|
||||
# Modify hosts on mock_root
|
||||
with open(self.hosts_path, "w") as f:
|
||||
f.write("corrupted hosts content\n")
|
||||
|
||||
engine = SafeRestoreEngine(target_dir=self.backup_dir)
|
||||
plan = engine.plan_restore("test_snap", target_root=self.mock_root)
|
||||
|
||||
with self.assertRaises(DryRunException):
|
||||
engine.execute_restore(plan, force=False)
|
||||
|
||||
# Verify hosts content was NOT modified
|
||||
with open(self.hosts_path, "r") as f:
|
||||
self.assertEqual(f.read(), "corrupted hosts content\n")
|
||||
|
||||
def test_execute_restore_with_force_creates_safety_snapshot_and_restores(self):
|
||||
# Corrupt hosts
|
||||
with open(self.hosts_path, "w") as f:
|
||||
f.write("corrupted content\n")
|
||||
|
||||
# Delete netplan config
|
||||
os.remove(self.net_cfg)
|
||||
|
||||
engine = SafeRestoreEngine(target_dir=self.backup_dir)
|
||||
plan = engine.plan_restore("test_snap", target_root=self.mock_root)
|
||||
|
||||
# Allow non-root flock fallback
|
||||
pid_file = os.path.join(self.test_dir, "test.pid")
|
||||
with patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
res = engine.execute_restore(plan, force=True, pid_path=pid_file)
|
||||
|
||||
self.assertEqual(res["status"], "success")
|
||||
self.assertTrue(res["safety_snapshot_id"].startswith("pre_restore_"))
|
||||
self.assertTrue(os.path.isfile(res["safety_archive_path"]))
|
||||
|
||||
# Verify hosts restored
|
||||
with open(self.hosts_path, "r") as f:
|
||||
self.assertEqual(f.read(), "127.0.0.1 localhost\n")
|
||||
|
||||
# Verify netplan recreated
|
||||
self.assertTrue(os.path.isfile(self.net_cfg))
|
||||
with open(self.net_cfg, "r") as f:
|
||||
self.assertEqual(f.read(), "network: {version: 2}\n")
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user