feat: implement slice 4 major release upgrade and configuration engine
This commit is contained in:
1 parent
dcb224150f
commit
6e18bdf7b7
4 files changed
+252
-28
No files matched your search
@@ -9,7 +9,7 @@
|
||||
- [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + detector + tests)
|
||||
- [x] Slice 2 — pre-flight health & auto-remediation engine
|
||||
- [x] Slice 3 — package managers (apt, dnf, pacman) & routine updates
|
||||
- [ ] Slice 4 — major release upgrade & configuration engine
|
||||
- [x] Slice 4 — major release upgrade & configuration engine
|
||||
- [ ] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm)
|
||||
- [ ] Slice 6 — documentation (man page, README, user/admin/developer guides)
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"thresholds": {
|
||||
"min_boot_mb": 250,
|
||||
"min_var_mb": 1024,
|
||||
"min_root_mb": 1024,
|
||||
"min_ram_mb": 300
|
||||
},
|
||||
"behavior": {
|
||||
"auto_remediate": true,
|
||||
"non_interactive": false,
|
||||
"check_ac_power": true,
|
||||
"clean_after_update": false
|
||||
},
|
||||
"logging": {
|
||||
"log_file": "/var/log/linux-updater.log",
|
||||
"verbose": false
|
||||
}
|
||||
}
|
||||
+85
-27
@@ -19,33 +19,38 @@ def create_parser() -> argparse.ArgumentParser:
|
||||
common.add_argument(
|
||||
"-c", "--config",
|
||||
type=str,
|
||||
default="/etc/linux-updater.json",
|
||||
help="Path to JSON configuration file.",
|
||||
default=argparse.SUPPRESS,
|
||||
help="Path to JSON configuration file (default: /etc/linux-updater.json).",
|
||||
)
|
||||
common.add_argument(
|
||||
"-y", "--yes", "--non-interactive",
|
||||
dest="non_interactive",
|
||||
action="store_true",
|
||||
default=argparse.SUPPRESS,
|
||||
help="Run without interactive confirmation prompts (ideal for cron and automation).",
|
||||
)
|
||||
common.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
default=argparse.SUPPRESS,
|
||||
help="Simulate execution without modifying system state.",
|
||||
)
|
||||
common.add_argument(
|
||||
"--no-remediation",
|
||||
action="store_true",
|
||||
default=argparse.SUPPRESS,
|
||||
help="Disable automatic remediation of failed pre-flight health checks.",
|
||||
)
|
||||
common.add_argument(
|
||||
"--skip-preflight",
|
||||
action="store_true",
|
||||
default=argparse.SUPPRESS,
|
||||
help="Skip pre-flight health checks (not recommended).",
|
||||
)
|
||||
common.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
default=argparse.SUPPRESS,
|
||||
help="Output structured JSON results.",
|
||||
)
|
||||
|
||||
@@ -154,22 +159,29 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
if args.command is None:
|
||||
args.command = "update"
|
||||
|
||||
non_interactive = getattr(args, "non_interactive", False)
|
||||
dry_run = getattr(args, "dry_run", False)
|
||||
no_remediation = getattr(args, "no_remediation", False)
|
||||
skip_preflight = getattr(args, "skip_preflight", False)
|
||||
json_output = getattr(args, "json", False)
|
||||
config_path = getattr(args, "config", "/etc/linux-updater.json")
|
||||
|
||||
detector = DistroDetector()
|
||||
distro = detector.detect()
|
||||
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print(f"Linux System Updater v{__version__}")
|
||||
print(f"Detected System: {distro.pretty_name} (Family: {distro.family.value})")
|
||||
|
||||
if distro.family == DistroFamily.UNKNOWN:
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print(f"Error: Unsupported or unrecognized Linux distribution: {distro.distro_id}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
config = UpdaterConfig.load(Path(args.config) if args.config else None)
|
||||
if args.non_interactive:
|
||||
config = UpdaterConfig.load(Path(config_path) if config_path else None)
|
||||
if non_interactive:
|
||||
config.non_interactive = True
|
||||
if args.no_remediation:
|
||||
if no_remediation:
|
||||
config.auto_remediate = False
|
||||
|
||||
runner = CommandRunner(verbose=config.verbose, log_file=Path(config.log_file) if config.log_file else None)
|
||||
@@ -180,7 +192,7 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
# 1. Health Command
|
||||
if args.command == "health":
|
||||
report = checker.run_all_checks()
|
||||
if args.json:
|
||||
if json_output:
|
||||
print(json.dumps(report.to_dict(), indent=2))
|
||||
else:
|
||||
format_health_report(report)
|
||||
@@ -188,16 +200,16 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
|
||||
# 2. Clean Command
|
||||
if args.command == "clean":
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print("Cleaning package cache...")
|
||||
res_clean = manager.clean_cache()
|
||||
res_auto = None
|
||||
if getattr(args, "all", False):
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print("Removing unused dependencies...")
|
||||
res_auto = manager.autoremove()
|
||||
|
||||
if args.json:
|
||||
if json_output:
|
||||
print(json.dumps({
|
||||
"clean_cache": res_clean.to_dict(),
|
||||
"autoremove": res_auto.to_dict() if res_auto else None,
|
||||
@@ -207,16 +219,16 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
return 0
|
||||
|
||||
# 3. Pre-flight health checks (for update, check, release-upgrade)
|
||||
if not args.skip_preflight:
|
||||
if not skip_preflight:
|
||||
report = checker.run_all_checks()
|
||||
if not report.passed:
|
||||
if config.auto_remediate:
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print("Pre-flight checks failed. Attempting automated safe remediation...")
|
||||
remediated_any = False
|
||||
for r in report.results:
|
||||
if r.status == CheckStatus.FAIL and remediation.can_remediate(r):
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print(f"-> Remediating: {r.name} ({r.remediation_id})...")
|
||||
if remediation.remediate(r):
|
||||
remediated_any = True
|
||||
@@ -225,7 +237,7 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
report = checker.run_all_checks()
|
||||
|
||||
if not report.passed:
|
||||
if args.json:
|
||||
if json_output:
|
||||
print(json.dumps({"error": "preflight_failed", "report": report.to_dict()}, indent=2))
|
||||
else:
|
||||
format_health_report(report)
|
||||
@@ -234,10 +246,10 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
|
||||
# 4. Check Command
|
||||
if args.command == "check":
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print("Checking for available package updates...")
|
||||
updates = manager.check_updates()
|
||||
if args.json:
|
||||
if json_output:
|
||||
print(json.dumps({
|
||||
"updates_count": len(updates),
|
||||
"updates": [{"package": u.package, "current_version": u.current_version, "new_version": u.new_version, "repo": u.repo} for u in updates]
|
||||
@@ -253,7 +265,7 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
# 5. Update Command
|
||||
if args.command == "update":
|
||||
packages = getattr(args, "packages", None)
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
if packages:
|
||||
print(f"Preparing to update specific packages: {', '.join(packages)}")
|
||||
else:
|
||||
@@ -264,10 +276,10 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
if not packages and not config.non_interactive:
|
||||
updates = manager.check_updates()
|
||||
if not updates:
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print("System is already up to date. No updates needed.")
|
||||
return 0
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print(f"\nAvailable Updates ({len(updates)}):")
|
||||
print("-" * 65)
|
||||
for u in updates[:20]:
|
||||
@@ -277,36 +289,36 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
print("-" * 65)
|
||||
|
||||
# Interactive confirmation gate
|
||||
if not config.non_interactive and not args.dry_run:
|
||||
if not config.non_interactive and not dry_run:
|
||||
if not prompt_confirmation():
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print("Operation cancelled by user.")
|
||||
return 3
|
||||
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print("\nApplying updates...")
|
||||
|
||||
res = manager.apply_updates(
|
||||
packages=packages,
|
||||
dry_run=args.dry_run,
|
||||
dry_run=dry_run,
|
||||
non_interactive=config.non_interactive,
|
||||
)
|
||||
|
||||
if not res.success:
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print(f"\nUpdate failed with exit code {res.return_code}: {res.stderr}", file=sys.stderr)
|
||||
else:
|
||||
print(json.dumps({"success": False, "result": res.to_dict()}, indent=2))
|
||||
return 1
|
||||
|
||||
if config.clean_after_update:
|
||||
if not args.json:
|
||||
if not json_output:
|
||||
print("Cleaning orphan packages...")
|
||||
manager.autoremove()
|
||||
|
||||
reboot = manager.is_reboot_required()
|
||||
|
||||
if args.json:
|
||||
if json_output:
|
||||
print(json.dumps({
|
||||
"success": True,
|
||||
"reboot_required": reboot.required,
|
||||
@@ -320,6 +332,52 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
|
||||
return 0
|
||||
|
||||
# 6. Release-Upgrade Command
|
||||
if args.command == "release-upgrade":
|
||||
target = getattr(args, "target_release", None)
|
||||
if not json_output:
|
||||
print("\n" + "=" * 65)
|
||||
print(" WARNING: MAJOR DISTRIBUTION RELEASE UPGRADE")
|
||||
print("=" * 65)
|
||||
print(f"Target Release: {target if target else 'Latest available'}")
|
||||
print("This operation performs a major upgrade of core system components.")
|
||||
print("Ensure you have a recent system backup or snapshot before proceeding.")
|
||||
print("=" * 65 + "\n")
|
||||
|
||||
if not config.non_interactive and not dry_run:
|
||||
prompt_msg = f"Are you absolutely sure you want to proceed with upgrade to {target or 'new release'}? [y/N]: "
|
||||
if not prompt_confirmation(prompt=prompt_msg):
|
||||
if not json_output:
|
||||
print("Release upgrade cancelled by user.")
|
||||
return 3
|
||||
|
||||
if not json_output:
|
||||
print("\nStarting major release upgrade...")
|
||||
|
||||
res = manager.release_upgrade(target_release=target, non_interactive=config.non_interactive)
|
||||
if not res.success:
|
||||
if not json_output:
|
||||
print(f"\nRelease upgrade failed: {res.stderr}", file=sys.stderr)
|
||||
else:
|
||||
print(json.dumps({"success": False, "result": res.to_dict()}, indent=2))
|
||||
return 1
|
||||
|
||||
reboot = manager.is_reboot_required()
|
||||
if json_output:
|
||||
print(json.dumps({
|
||||
"success": True,
|
||||
"release_upgrade": True,
|
||||
"target_release": target,
|
||||
"reboot_required": reboot.required,
|
||||
}, indent=2))
|
||||
else:
|
||||
print("\nRelease upgrade completed successfully!")
|
||||
if reboot.required:
|
||||
print("\n[!] ATTENTION: A system reboot is required to boot into the new release.")
|
||||
return 2
|
||||
|
||||
return 0
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from linux_updater.cli import main
|
||||
from linux_updater.config import UpdaterConfig
|
||||
from linux_updater.models import CommandResult, DistroFamily, DistroInfo, RebootStatus
|
||||
|
||||
|
||||
class TestCLIIntegration(unittest.TestCase):
|
||||
@patch("linux_updater.cli.DistroDetector.detect")
|
||||
def test_cli_distro_unknown_returns_code_1(self, mock_detect):
|
||||
mock_detect.return_value = DistroInfo(
|
||||
family=DistroFamily.UNKNOWN,
|
||||
distro_id="solaris",
|
||||
version_id="11",
|
||||
pretty_name="Solaris",
|
||||
)
|
||||
code = main(["--json", "health"])
|
||||
self.assertEqual(code, 1)
|
||||
|
||||
@patch("linux_updater.cli.DistroDetector.detect")
|
||||
@patch("linux_updater.cli.get_manager")
|
||||
def test_cli_health_success_returns_code_0(self, mock_get_manager, mock_detect):
|
||||
mock_detect.return_value = DistroInfo(
|
||||
family=DistroFamily.DEBIAN,
|
||||
distro_id="ubuntu",
|
||||
version_id="24.04",
|
||||
pretty_name="Ubuntu 24.04",
|
||||
)
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_lock_files.return_value = []
|
||||
mock_manager.is_reboot_required.return_value = RebootStatus(required=False)
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
with patch("os.statvfs") as mock_statvfs:
|
||||
mock_stat = MagicMock()
|
||||
mock_stat.f_bavail = 5 * 1024 * 1024
|
||||
mock_stat.f_frsize = 1024
|
||||
mock_statvfs.return_value = mock_stat
|
||||
|
||||
code = main(["--json", "health"])
|
||||
self.assertEqual(code, 0)
|
||||
|
||||
@patch("linux_updater.cli.DistroDetector.detect")
|
||||
@patch("linux_updater.cli.get_manager")
|
||||
def test_cli_user_abort_returns_code_3(self, mock_get_manager, mock_detect):
|
||||
mock_detect.return_value = DistroInfo(
|
||||
family=DistroFamily.DEBIAN,
|
||||
distro_id="ubuntu",
|
||||
version_id="24.04",
|
||||
pretty_name="Ubuntu 24.04",
|
||||
)
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_lock_files.return_value = []
|
||||
mock_manager.is_reboot_required.return_value = RebootStatus(required=False)
|
||||
mock_manager.check_updates.return_value = [
|
||||
MagicMock(package="test-pkg", current_version="1.0", new_version="2.0")
|
||||
]
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
with patch("os.statvfs") as mock_statvfs:
|
||||
mock_stat = MagicMock()
|
||||
mock_stat.f_bavail = 5 * 1024 * 1024
|
||||
mock_stat.f_frsize = 1024
|
||||
mock_statvfs.return_value = mock_stat
|
||||
|
||||
# User answers 'n' to confirmation prompt
|
||||
with patch("linux_updater.cli.prompt_confirmation", return_value=False):
|
||||
code = main(["update"])
|
||||
self.assertEqual(code, 3)
|
||||
|
||||
@patch("linux_updater.cli.DistroDetector.detect")
|
||||
@patch("linux_updater.cli.get_manager")
|
||||
def test_cli_update_reboot_required_returns_code_2(self, mock_get_manager, mock_detect):
|
||||
mock_detect.return_value = DistroInfo(
|
||||
family=DistroFamily.DEBIAN,
|
||||
distro_id="ubuntu",
|
||||
version_id="24.04",
|
||||
pretty_name="Ubuntu 24.04",
|
||||
)
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_lock_files.return_value = []
|
||||
mock_manager.check_updates.return_value = []
|
||||
mock_manager.apply_updates.return_value = CommandResult(0, "success", "", True)
|
||||
mock_manager.is_reboot_required.return_value = RebootStatus(required=True, reason="kernel upgraded")
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
with patch("os.statvfs") as mock_statvfs:
|
||||
mock_stat = MagicMock()
|
||||
mock_stat.f_bavail = 5 * 1024 * 1024
|
||||
mock_stat.f_frsize = 1024
|
||||
mock_statvfs.return_value = mock_stat
|
||||
|
||||
code = main(["-y", "update"])
|
||||
self.assertEqual(code, 2)
|
||||
|
||||
@patch("linux_updater.cli.DistroDetector.detect")
|
||||
@patch("linux_updater.cli.get_manager")
|
||||
def test_cli_release_upgrade_calls_manager_with_target(self, mock_get_manager, mock_detect):
|
||||
mock_detect.return_value = DistroInfo(
|
||||
family=DistroFamily.RHEL,
|
||||
distro_id="fedora",
|
||||
version_id="40",
|
||||
pretty_name="Fedora 40",
|
||||
)
|
||||
mock_manager = MagicMock()
|
||||
mock_manager.get_lock_files.return_value = []
|
||||
mock_manager.release_upgrade.return_value = CommandResult(0, "success", "", True)
|
||||
mock_manager.is_reboot_required.return_value = RebootStatus(required=False)
|
||||
mock_get_manager.return_value = mock_manager
|
||||
|
||||
with patch("os.statvfs") as mock_statvfs:
|
||||
mock_stat = MagicMock()
|
||||
mock_stat.f_bavail = 10 * 1024 * 1024
|
||||
mock_stat.f_frsize = 1024
|
||||
mock_statvfs.return_value = mock_stat
|
||||
|
||||
code = main(["-y", "release-upgrade", "--target-release", "41"])
|
||||
self.assertEqual(code, 0)
|
||||
mock_manager.release_upgrade.assert_called_once_with(
|
||||
target_release="41",
|
||||
non_interactive=True,
|
||||
)
|
||||
|
||||
def test_config_file_and_cli_overrides(self):
|
||||
config_data = {
|
||||
"thresholds": {"min_boot_mb": 500},
|
||||
"behavior": {"auto_remediate": False, "non_interactive": False},
|
||||
}
|
||||
with tempfile.NamedTemporaryFile("w", delete=False) as t:
|
||||
json.dump(config_data, t)
|
||||
t_path = Path(t.name)
|
||||
|
||||
try:
|
||||
cfg = UpdaterConfig.load(t_path)
|
||||
self.assertEqual(cfg.min_boot_mb, 500)
|
||||
self.assertFalse(cfg.auto_remediate)
|
||||
self.assertFalse(cfg.non_interactive)
|
||||
finally:
|
||||
if t_path.exists():
|
||||
t_path.unlink()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user