feat: implement slice 3 package managers (apt, dnf, pacman) and update workflows
This commit is contained in:
1 parent
62ce7e63f8
commit
dcb224150f
8 files changed
+779
-43
No files matched your search
@@ -8,7 +8,7 @@
|
|||||||
## Slices
|
## Slices
|
||||||
- [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + detector + tests)
|
- [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + detector + tests)
|
||||||
- [x] Slice 2 — pre-flight health & auto-remediation engine
|
- [x] Slice 2 — pre-flight health & auto-remediation engine
|
||||||
- [ ] Slice 3 — package managers (apt, dnf, pacman) & routine updates
|
- [x] Slice 3 — package managers (apt, dnf, pacman) & routine updates
|
||||||
- [ ] Slice 4 — major release upgrade & configuration engine
|
- [ ] Slice 4 — major release upgrade & configuration engine
|
||||||
- [ ] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm)
|
- [ ] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm)
|
||||||
- [ ] Slice 6 — documentation (man page, README, user/admin/developer guides)
|
- [ ] Slice 6 — documentation (man page, README, user/admin/developer guides)
|
||||||
|
|||||||
+174
-41
@@ -1,4 +1,5 @@
|
|||||||
import argparse
|
import argparse
|
||||||
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import sys
|
import sys
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
@@ -6,7 +7,11 @@ from typing import List, Optional
|
|||||||
from linux_updater import __version__
|
from linux_updater import __version__
|
||||||
from linux_updater.config import UpdaterConfig
|
from linux_updater.config import UpdaterConfig
|
||||||
from linux_updater.core.detector import DistroDetector
|
from linux_updater.core.detector import DistroDetector
|
||||||
from linux_updater.models import DistroFamily
|
from linux_updater.core.health import HealthChecker
|
||||||
|
from linux_updater.core.remediation import RemediationEngine
|
||||||
|
from linux_updater.core.runner import CommandRunner
|
||||||
|
from linux_updater.managers import get_manager
|
||||||
|
from linux_updater.models import CheckStatus, DistroFamily
|
||||||
|
|
||||||
|
|
||||||
def create_parser() -> argparse.ArgumentParser:
|
def create_parser() -> argparse.ArgumentParser:
|
||||||
@@ -118,6 +123,30 @@ def create_parser() -> argparse.ArgumentParser:
|
|||||||
return parser
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
def format_health_report(report) -> None:
|
||||||
|
print("\nPre-flight Health Diagnostics:")
|
||||||
|
print("-" * 65)
|
||||||
|
for res in report.results:
|
||||||
|
status_symbol = "[ PASS ]" if res.status.value == "PASS" else (
|
||||||
|
"[ WARN ]" if res.status.value == "WARN" else "[ FAIL ]"
|
||||||
|
)
|
||||||
|
print(f"{status_symbol} {res.name:<22} {res.message}")
|
||||||
|
print("-" * 65)
|
||||||
|
status_text = "PASSED" if report.passed else "FAILED"
|
||||||
|
print(f"Overall Pre-flight Status: {status_text}\n")
|
||||||
|
|
||||||
|
|
||||||
|
def prompt_confirmation(prompt: str = "Do you want to proceed with updates? [Y/n]: ") -> bool:
|
||||||
|
try:
|
||||||
|
choice = input(prompt).strip().lower()
|
||||||
|
if not choice or choice in ("y", "yes", "tak", "t"):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
except (KeyboardInterrupt, EOFError):
|
||||||
|
print("\nAborted.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def main(argv: Optional[List[str]] = None) -> int:
|
def main(argv: Optional[List[str]] = None) -> int:
|
||||||
parser = create_parser()
|
parser = create_parser()
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
@@ -132,61 +161,165 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
print(f"Linux System Updater v{__version__}")
|
print(f"Linux System Updater v{__version__}")
|
||||||
print(f"Detected System: {distro.pretty_name} (Family: {distro.family.value})")
|
print(f"Detected System: {distro.pretty_name} (Family: {distro.family.value})")
|
||||||
|
|
||||||
|
if distro.family == DistroFamily.UNKNOWN:
|
||||||
|
if not args.json:
|
||||||
|
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)
|
config = UpdaterConfig.load(Path(args.config) if args.config else None)
|
||||||
if args.non_interactive:
|
if args.non_interactive:
|
||||||
config.non_interactive = True
|
config.non_interactive = True
|
||||||
if args.no_remediation:
|
if args.no_remediation:
|
||||||
config.auto_remediate = False
|
config.auto_remediate = False
|
||||||
|
|
||||||
# Create dummy manager for health checks when specific manager isn't wired yet
|
runner = CommandRunner(verbose=config.verbose, log_file=Path(config.log_file) if config.log_file else None)
|
||||||
from linux_updater.managers.base import PackageManager
|
manager = get_manager(distro.family, runner=runner)
|
||||||
from linux_updater.models import RebootStatus
|
|
||||||
|
|
||||||
class FallbackManager(PackageManager):
|
|
||||||
@property
|
|
||||||
def name(self) -> str:
|
|
||||||
return distro.family.value
|
|
||||||
def refresh_repositories(self): pass
|
|
||||||
def check_updates(self): return []
|
|
||||||
def apply_updates(self, packages=None, dry_run=False, non_interactive=False): pass
|
|
||||||
def release_upgrade(self, target_release=None, non_interactive=False): pass
|
|
||||||
def clean_cache(self): pass
|
|
||||||
def autoremove(self): pass
|
|
||||||
def is_reboot_required(self) -> RebootStatus:
|
|
||||||
reboot_p = Path("/var/run/reboot-required")
|
|
||||||
return RebootStatus(required=reboot_p.exists(), reason="reboot-required flag found" if reboot_p.exists() else "")
|
|
||||||
def get_lock_files(self) -> List[Path]:
|
|
||||||
if distro.family == DistroFamily.DEBIAN:
|
|
||||||
return [Path("/var/lib/dpkg/lock-frontend"), Path("/var/lib/dpkg/lock")]
|
|
||||||
elif distro.family == DistroFamily.RHEL:
|
|
||||||
return [Path("/var/lib/rpm/.rpm.lock")]
|
|
||||||
elif distro.family == DistroFamily.ARCH:
|
|
||||||
return [Path("/var/lib/pacman/db.lck")]
|
|
||||||
return []
|
|
||||||
|
|
||||||
manager = FallbackManager()
|
|
||||||
from linux_updater.core.health import HealthChecker
|
|
||||||
checker = HealthChecker(config=config, manager=manager)
|
checker = HealthChecker(config=config, manager=manager)
|
||||||
|
remediation = RemediationEngine(manager=manager)
|
||||||
|
|
||||||
|
# 1. Health Command
|
||||||
if args.command == "health":
|
if args.command == "health":
|
||||||
report = checker.run_all_checks()
|
report = checker.run_all_checks()
|
||||||
if args.json:
|
if args.json:
|
||||||
import json
|
|
||||||
print(json.dumps(report.to_dict(), indent=2))
|
print(json.dumps(report.to_dict(), indent=2))
|
||||||
else:
|
else:
|
||||||
print("\nPre-flight Health Diagnostics:")
|
format_health_report(report)
|
||||||
print("-" * 65)
|
|
||||||
for res in report.results:
|
|
||||||
status_symbol = "[ PASS ]" if res.status.value == "PASS" else (
|
|
||||||
"[ WARN ]" if res.status.value == "WARN" else "[ FAIL ]"
|
|
||||||
)
|
|
||||||
print(f"{status_symbol} {res.name:<22} {res.message}")
|
|
||||||
print("-" * 65)
|
|
||||||
status_text = "PASSED" if report.passed else "FAILED"
|
|
||||||
print(f"Overall Pre-flight Status: {status_text}\n")
|
|
||||||
|
|
||||||
return 0 if report.passed else 1
|
return 0 if report.passed else 1
|
||||||
|
|
||||||
|
# 2. Clean Command
|
||||||
|
if args.command == "clean":
|
||||||
|
if not args.json:
|
||||||
|
print("Cleaning package cache...")
|
||||||
|
res_clean = manager.clean_cache()
|
||||||
|
res_auto = None
|
||||||
|
if getattr(args, "all", False):
|
||||||
|
if not args.json:
|
||||||
|
print("Removing unused dependencies...")
|
||||||
|
res_auto = manager.autoremove()
|
||||||
|
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps({
|
||||||
|
"clean_cache": res_clean.to_dict(),
|
||||||
|
"autoremove": res_auto.to_dict() if res_auto else None,
|
||||||
|
}, indent=2))
|
||||||
|
else:
|
||||||
|
print("Clean operation completed successfully.")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# 3. Pre-flight health checks (for update, check, release-upgrade)
|
||||||
|
if not args.skip_preflight:
|
||||||
|
report = checker.run_all_checks()
|
||||||
|
if not report.passed:
|
||||||
|
if config.auto_remediate:
|
||||||
|
if not args.json:
|
||||||
|
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:
|
||||||
|
print(f"-> Remediating: {r.name} ({r.remediation_id})...")
|
||||||
|
if remediation.remediate(r):
|
||||||
|
remediated_any = True
|
||||||
|
if remediated_any:
|
||||||
|
# Re-run checks
|
||||||
|
report = checker.run_all_checks()
|
||||||
|
|
||||||
|
if not report.passed:
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps({"error": "preflight_failed", "report": report.to_dict()}, indent=2))
|
||||||
|
else:
|
||||||
|
format_health_report(report)
|
||||||
|
print("Error: Pre-flight checks failed and could not be remediated. Aborting updates.", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# 4. Check Command
|
||||||
|
if args.command == "check":
|
||||||
|
if not args.json:
|
||||||
|
print("Checking for available package updates...")
|
||||||
|
updates = manager.check_updates()
|
||||||
|
if args.json:
|
||||||
|
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]
|
||||||
|
}, indent=2))
|
||||||
|
else:
|
||||||
|
print(f"\nAvailable Updates ({len(updates)}):")
|
||||||
|
print("-" * 65)
|
||||||
|
for u in updates:
|
||||||
|
print(f"• {u.package:<30} {u.current_version} -> {u.new_version}")
|
||||||
|
print("-" * 65)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# 5. Update Command
|
||||||
|
if args.command == "update":
|
||||||
|
packages = getattr(args, "packages", None)
|
||||||
|
if not args.json:
|
||||||
|
if packages:
|
||||||
|
print(f"Preparing to update specific packages: {', '.join(packages)}")
|
||||||
|
else:
|
||||||
|
print("Checking available updates...")
|
||||||
|
|
||||||
|
# If not selective, query updates for preview in interactive mode
|
||||||
|
updates = []
|
||||||
|
if not packages and not config.non_interactive:
|
||||||
|
updates = manager.check_updates()
|
||||||
|
if not updates:
|
||||||
|
if not args.json:
|
||||||
|
print("System is already up to date. No updates needed.")
|
||||||
|
return 0
|
||||||
|
if not args.json:
|
||||||
|
print(f"\nAvailable Updates ({len(updates)}):")
|
||||||
|
print("-" * 65)
|
||||||
|
for u in updates[:20]:
|
||||||
|
print(f"• {u.package:<30} {u.current_version} -> {u.new_version}")
|
||||||
|
if len(updates) > 20:
|
||||||
|
print(f"... and {len(updates) - 20} more packages.")
|
||||||
|
print("-" * 65)
|
||||||
|
|
||||||
|
# Interactive confirmation gate
|
||||||
|
if not config.non_interactive and not args.dry_run:
|
||||||
|
if not prompt_confirmation():
|
||||||
|
if not args.json:
|
||||||
|
print("Operation cancelled by user.")
|
||||||
|
return 3
|
||||||
|
|
||||||
|
if not args.json:
|
||||||
|
print("\nApplying updates...")
|
||||||
|
|
||||||
|
res = manager.apply_updates(
|
||||||
|
packages=packages,
|
||||||
|
dry_run=args.dry_run,
|
||||||
|
non_interactive=config.non_interactive,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not res.success:
|
||||||
|
if not args.json:
|
||||||
|
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:
|
||||||
|
print("Cleaning orphan packages...")
|
||||||
|
manager.autoremove()
|
||||||
|
|
||||||
|
reboot = manager.is_reboot_required()
|
||||||
|
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps({
|
||||||
|
"success": True,
|
||||||
|
"reboot_required": reboot.required,
|
||||||
|
"reboot_reason": reboot.reason,
|
||||||
|
}, indent=2))
|
||||||
|
else:
|
||||||
|
print("\nUpdates applied successfully!")
|
||||||
|
if reboot.required:
|
||||||
|
print(f"\n[!] ATTENTION: A system reboot is required ({reboot.reason}).")
|
||||||
|
return 2
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
|
from linux_updater.models import CommandResult
|
||||||
|
|
||||||
|
|
||||||
|
class CommandRunner:
|
||||||
|
def __init__(self, verbose: bool = False, log_file: Optional[Path] = None) -> None:
|
||||||
|
self.verbose = verbose
|
||||||
|
self.log_file = log_file
|
||||||
|
|
||||||
|
def _log(self, text: str) -> None:
|
||||||
|
if self.verbose:
|
||||||
|
print(f"[RUNNER] {text}", file=sys.stderr)
|
||||||
|
if self.log_file:
|
||||||
|
try:
|
||||||
|
with open(str(self.log_file), "a", encoding="utf-8") as f:
|
||||||
|
f.write(f"{text}\n")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def run(
|
||||||
|
self,
|
||||||
|
cmd: List[str],
|
||||||
|
check: bool = False,
|
||||||
|
env: Optional[Dict[str, str]] = None,
|
||||||
|
timeout: Optional[int] = None,
|
||||||
|
) -> CommandResult:
|
||||||
|
full_env = os.environ.copy()
|
||||||
|
if env:
|
||||||
|
full_env.update(env)
|
||||||
|
|
||||||
|
self._log(f"Executing: {' '.join(cmd)}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
cmd,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
env=full_env,
|
||||||
|
timeout=timeout,
|
||||||
|
)
|
||||||
|
stdout = proc.stdout.decode("utf-8", errors="replace")
|
||||||
|
stderr = proc.stderr.decode("utf-8", errors="replace")
|
||||||
|
success = (proc.returncode == 0)
|
||||||
|
|
||||||
|
self._log(f"Exit code: {proc.returncode}")
|
||||||
|
|
||||||
|
if check and not success:
|
||||||
|
raise subprocess.CalledProcessError(proc.returncode, cmd, output=stdout, stderr=stderr)
|
||||||
|
|
||||||
|
return CommandResult(
|
||||||
|
return_code=proc.returncode,
|
||||||
|
stdout=stdout,
|
||||||
|
stderr=stderr,
|
||||||
|
success=success,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
self._log(f"Command execution error: {e}")
|
||||||
|
if check:
|
||||||
|
raise
|
||||||
|
return CommandResult(
|
||||||
|
return_code=1,
|
||||||
|
stdout="",
|
||||||
|
stderr=str(e),
|
||||||
|
success=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
def stream_run(
|
||||||
|
self,
|
||||||
|
cmd: List[str],
|
||||||
|
env: Optional[Dict[str, str]] = None,
|
||||||
|
) -> CommandResult:
|
||||||
|
full_env = os.environ.copy()
|
||||||
|
if env:
|
||||||
|
full_env.update(env)
|
||||||
|
|
||||||
|
self._log(f"Stream executing: {' '.join(cmd)}")
|
||||||
|
|
||||||
|
stdout_lines: List[str] = []
|
||||||
|
try:
|
||||||
|
proc = subprocess.Popen(
|
||||||
|
cmd,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.STDOUT,
|
||||||
|
env=full_env,
|
||||||
|
universal_newlines=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Stream output in real time
|
||||||
|
if proc.stdout:
|
||||||
|
for line in proc.stdout:
|
||||||
|
sys.stdout.write(line)
|
||||||
|
sys.stdout.flush()
|
||||||
|
stdout_lines.append(line)
|
||||||
|
|
||||||
|
proc.wait()
|
||||||
|
return CommandResult(
|
||||||
|
return_code=proc.returncode,
|
||||||
|
stdout="".join(stdout_lines),
|
||||||
|
stderr="",
|
||||||
|
success=(proc.returncode == 0),
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
return CommandResult(
|
||||||
|
return_code=1,
|
||||||
|
stdout="".join(stdout_lines),
|
||||||
|
stderr=str(e),
|
||||||
|
success=False,
|
||||||
|
)
|
||||||
@@ -1 +1,22 @@
|
|||||||
# Package managers subsystem
|
from typing import Optional
|
||||||
|
|
||||||
|
from linux_updater.core.runner import CommandRunner
|
||||||
|
from linux_updater.managers.base import PackageManager
|
||||||
|
from linux_updater.managers.apt import AptManager
|
||||||
|
from linux_updater.managers.dnf import DnfManager
|
||||||
|
from linux_updater.managers.pacman import PacmanManager
|
||||||
|
from linux_updater.models import DistroFamily
|
||||||
|
|
||||||
|
|
||||||
|
def get_manager(family: DistroFamily, runner: Optional[CommandRunner] = None) -> PackageManager:
|
||||||
|
if family == DistroFamily.DEBIAN:
|
||||||
|
return AptManager(runner=runner)
|
||||||
|
elif family == DistroFamily.RHEL:
|
||||||
|
return DnfManager(runner=runner)
|
||||||
|
elif family == DistroFamily.ARCH:
|
||||||
|
return PacmanManager(runner=runner)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"No package manager available for distribution family: {family}")
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["PackageManager", "AptManager", "DnfManager", "PacmanManager", "get_manager"]
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
|
from linux_updater.core.runner import CommandRunner
|
||||||
|
from linux_updater.managers.base import PackageManager
|
||||||
|
from linux_updater.models import CommandResult, PackageUpdate, RebootStatus
|
||||||
|
|
||||||
|
|
||||||
|
class AptManager(PackageManager):
|
||||||
|
def __init__(self, runner: Optional[CommandRunner] = None) -> None:
|
||||||
|
self.runner = runner or CommandRunner()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def name(self) -> str:
|
||||||
|
return "apt"
|
||||||
|
|
||||||
|
def _env(self, non_interactive: bool = False) -> Dict[str, str]:
|
||||||
|
env: Dict[str, str] = {}
|
||||||
|
if non_interactive:
|
||||||
|
env["DEBIAN_FRONTEND"] = "noninteractive"
|
||||||
|
return env
|
||||||
|
|
||||||
|
def refresh_repositories(self) -> CommandResult:
|
||||||
|
cmd = ["apt-get", "update"]
|
||||||
|
return self.runner.run(cmd, env=self._env(True))
|
||||||
|
|
||||||
|
def check_updates(self) -> List[PackageUpdate]:
|
||||||
|
cmd = ["apt-get", "-s", "upgrade"]
|
||||||
|
res = self.runner.run(cmd, env=self._env(True))
|
||||||
|
updates: List[PackageUpdate] = []
|
||||||
|
|
||||||
|
# Inst libssl3 [3.0.13-0ubuntu3.1] (3.0.13-0ubuntu3.4 Ubuntu:24.04/noble-updates [amd64])
|
||||||
|
pattern = re.compile(r"^Inst\s+(\S+)\s+\[([^\]]+)\]\s+\((\S+)\s+([^)]*)\)")
|
||||||
|
pattern_new = re.compile(r"^Inst\s+(\S+)\s+\((\S+)\s+([^)]*)\)")
|
||||||
|
|
||||||
|
for line in res.stdout.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
match = pattern.match(line)
|
||||||
|
if match:
|
||||||
|
pkg, old_ver, new_ver, repo = match.groups()
|
||||||
|
updates.append(PackageUpdate(package=pkg, current_version=old_ver, new_version=new_ver, repo=repo))
|
||||||
|
continue
|
||||||
|
match_new = pattern_new.match(line)
|
||||||
|
if match_new:
|
||||||
|
pkg, new_ver, repo = match_new.groups()
|
||||||
|
updates.append(PackageUpdate(package=pkg, current_version="none", new_version=new_ver, repo=repo))
|
||||||
|
|
||||||
|
return updates
|
||||||
|
|
||||||
|
def apply_updates(
|
||||||
|
self,
|
||||||
|
packages: Optional[List[str]] = None,
|
||||||
|
dry_run: bool = False,
|
||||||
|
non_interactive: bool = False,
|
||||||
|
) -> CommandResult:
|
||||||
|
cmd = ["apt-get"]
|
||||||
|
if packages:
|
||||||
|
cmd.extend(["install", "--only-upgrade", "-y"])
|
||||||
|
cmd.extend(packages)
|
||||||
|
else:
|
||||||
|
cmd.extend(["upgrade", "-y"])
|
||||||
|
|
||||||
|
if dry_run:
|
||||||
|
cmd.append("-s")
|
||||||
|
|
||||||
|
if non_interactive:
|
||||||
|
cmd.extend([
|
||||||
|
'-o', 'Dpkg::Options::=--force-confdef',
|
||||||
|
'-o', 'Dpkg::Options::=--force-confold',
|
||||||
|
])
|
||||||
|
|
||||||
|
return self.runner.run(cmd, env=self._env(non_interactive))
|
||||||
|
|
||||||
|
def release_upgrade(
|
||||||
|
self,
|
||||||
|
target_release: Optional[str] = None,
|
||||||
|
non_interactive: bool = False,
|
||||||
|
) -> CommandResult:
|
||||||
|
# Check if do-release-upgrade is available (Ubuntu)
|
||||||
|
import shutil
|
||||||
|
if shutil.which("do-release-upgrade"):
|
||||||
|
cmd = ["do-release-upgrade"]
|
||||||
|
if non_interactive:
|
||||||
|
cmd.extend(["-f", "DistUpgradeViewNonInteractive"])
|
||||||
|
return self.runner.run(cmd, env=self._env(non_interactive))
|
||||||
|
|
||||||
|
# Standard Debian dist-upgrade
|
||||||
|
cmd = ["apt-get", "dist-upgrade", "-y"]
|
||||||
|
if non_interactive:
|
||||||
|
cmd.extend([
|
||||||
|
'-o', 'Dpkg::Options::=--force-confdef',
|
||||||
|
'-o', 'Dpkg::Options::=--force-confold',
|
||||||
|
])
|
||||||
|
return self.runner.run(cmd, env=self._env(non_interactive))
|
||||||
|
|
||||||
|
def clean_cache(self) -> CommandResult:
|
||||||
|
return self.runner.run(["apt-get", "clean"])
|
||||||
|
|
||||||
|
def autoremove(self) -> CommandResult:
|
||||||
|
return self.runner.run(["apt-get", "autoremove", "-y"], env=self._env(True))
|
||||||
|
|
||||||
|
def is_reboot_required(self) -> RebootStatus:
|
||||||
|
flag = Path("/var/run/reboot-required")
|
||||||
|
if flag.exists():
|
||||||
|
pkgs_file = Path("/var/run/reboot-required.pkgs")
|
||||||
|
reason = "Reboot required by system packages"
|
||||||
|
if pkgs_file.exists():
|
||||||
|
try:
|
||||||
|
pkgs = [p.strip() for p in pkgs_file.read_text().splitlines() if p.strip()]
|
||||||
|
if pkgs:
|
||||||
|
reason = f"Packages requiring reboot: {', '.join(pkgs[:5])}"
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return RebootStatus(required=True, reason=reason)
|
||||||
|
return RebootStatus(required=False)
|
||||||
|
|
||||||
|
def get_lock_files(self) -> List[Path]:
|
||||||
|
return [
|
||||||
|
Path("/var/lib/dpkg/lock-frontend"),
|
||||||
|
Path("/var/lib/dpkg/lock"),
|
||||||
|
Path("/var/lib/apt/lists/lock"),
|
||||||
|
]
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from linux_updater.core.runner import CommandRunner
|
||||||
|
from linux_updater.managers.base import PackageManager
|
||||||
|
from linux_updater.models import CommandResult, PackageUpdate, RebootStatus
|
||||||
|
|
||||||
|
|
||||||
|
class DnfManager(PackageManager):
|
||||||
|
def __init__(self, runner: Optional[CommandRunner] = None, binary: Optional[str] = None) -> None:
|
||||||
|
self.runner = runner or CommandRunner()
|
||||||
|
if binary is not None:
|
||||||
|
self.binary = binary
|
||||||
|
else:
|
||||||
|
self.binary = "yum" if (not shutil.which("dnf") and shutil.which("yum")) else "dnf"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def name(self) -> str:
|
||||||
|
return self.binary
|
||||||
|
|
||||||
|
def refresh_repositories(self) -> CommandResult:
|
||||||
|
cmd = [self.binary, "makecache"]
|
||||||
|
return self.runner.run(cmd)
|
||||||
|
|
||||||
|
def check_updates(self) -> List[PackageUpdate]:
|
||||||
|
cmd = [self.binary, "check-update"]
|
||||||
|
res = self.runner.run(cmd)
|
||||||
|
|
||||||
|
# DNF returns exit code 100 when updates are found, 0 when clean
|
||||||
|
if res.return_code not in (0, 100):
|
||||||
|
return []
|
||||||
|
|
||||||
|
updates: List[PackageUpdate] = []
|
||||||
|
lines = res.stdout.splitlines()
|
||||||
|
|
||||||
|
for line in lines:
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("Last metadata") or line.startswith("Security:") or "Obsoleting Packages" in line:
|
||||||
|
continue
|
||||||
|
parts = line.split()
|
||||||
|
if len(parts) >= 3:
|
||||||
|
pkg = parts[0]
|
||||||
|
new_ver = parts[1]
|
||||||
|
repo = parts[2]
|
||||||
|
updates.append(PackageUpdate(package=pkg, current_version="installed", new_version=new_ver, repo=repo))
|
||||||
|
|
||||||
|
return updates
|
||||||
|
|
||||||
|
def apply_updates(
|
||||||
|
self,
|
||||||
|
packages: Optional[List[str]] = None,
|
||||||
|
dry_run: bool = False,
|
||||||
|
non_interactive: bool = False,
|
||||||
|
) -> CommandResult:
|
||||||
|
cmd = [self.binary, "upgrade"]
|
||||||
|
if non_interactive:
|
||||||
|
cmd.append("-y")
|
||||||
|
if dry_run:
|
||||||
|
cmd.append("--assumeno")
|
||||||
|
if packages:
|
||||||
|
cmd.extend(packages)
|
||||||
|
|
||||||
|
return self.runner.run(cmd)
|
||||||
|
|
||||||
|
def release_upgrade(
|
||||||
|
self,
|
||||||
|
target_release: Optional[str] = None,
|
||||||
|
non_interactive: bool = False,
|
||||||
|
) -> CommandResult:
|
||||||
|
cmd = [self.binary, "system-upgrade", "download"]
|
||||||
|
if non_interactive:
|
||||||
|
cmd.append("-y")
|
||||||
|
if target_release:
|
||||||
|
cmd.append(f"--releasever={target_release}")
|
||||||
|
return self.runner.run(cmd)
|
||||||
|
|
||||||
|
def clean_cache(self) -> CommandResult:
|
||||||
|
return self.runner.run([self.binary, "clean", "all"])
|
||||||
|
|
||||||
|
def autoremove(self) -> CommandResult:
|
||||||
|
cmd = [self.binary, "autoremove"]
|
||||||
|
cmd.append("-y")
|
||||||
|
return self.runner.run(cmd)
|
||||||
|
|
||||||
|
def is_reboot_required(self) -> RebootStatus:
|
||||||
|
# Check needs-restarting -r
|
||||||
|
if shutil.which("needs-restarting"):
|
||||||
|
res = self.runner.run(["needs-restarting", "-r"])
|
||||||
|
# Exit code 1 indicates reboot is required
|
||||||
|
if res.return_code == 1:
|
||||||
|
return RebootStatus(required=True, reason="needs-restarting reported pending reboot")
|
||||||
|
return RebootStatus(required=False)
|
||||||
|
|
||||||
|
def get_lock_files(self) -> List[Path]:
|
||||||
|
return [
|
||||||
|
Path("/var/lib/rpm/.rpm.lock"),
|
||||||
|
Path("/var/run/dnf.pid"),
|
||||||
|
]
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from linux_updater.core.runner import CommandRunner
|
||||||
|
from linux_updater.managers.base import PackageManager
|
||||||
|
from linux_updater.models import CommandResult, PackageUpdate, RebootStatus
|
||||||
|
|
||||||
|
|
||||||
|
class PacmanManager(PackageManager):
|
||||||
|
def __init__(self, runner: Optional[CommandRunner] = None) -> None:
|
||||||
|
self.runner = runner or CommandRunner()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def name(self) -> str:
|
||||||
|
return "pacman"
|
||||||
|
|
||||||
|
def refresh_repositories(self) -> CommandResult:
|
||||||
|
return self.runner.run(["pacman", "-Sy"])
|
||||||
|
|
||||||
|
def check_updates(self) -> List[PackageUpdate]:
|
||||||
|
# Prefer checkupdates if installed (safe non-root update check)
|
||||||
|
cmd = ["checkupdates"] if shutil.which("checkupdates") else ["pacman", "-Qu"]
|
||||||
|
res = self.runner.run(cmd)
|
||||||
|
|
||||||
|
updates: List[PackageUpdate] = []
|
||||||
|
for line in res.stdout.splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or "->" not in line:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Format: package old_version -> new_version [repo]
|
||||||
|
try:
|
||||||
|
left, right = line.split("->", 1)
|
||||||
|
left_parts = left.strip().split()
|
||||||
|
right_parts = right.strip().split()
|
||||||
|
|
||||||
|
pkg = left_parts[0]
|
||||||
|
old_ver = left_parts[1] if len(left_parts) > 1 else "unknown"
|
||||||
|
new_ver = right_parts[0] if right_parts else "unknown"
|
||||||
|
repo = right_parts[1].strip("[]") if len(right_parts) > 1 else None
|
||||||
|
|
||||||
|
updates.append(PackageUpdate(package=pkg, current_version=old_ver, new_version=new_ver, repo=repo))
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
|
||||||
|
return updates
|
||||||
|
|
||||||
|
def apply_updates(
|
||||||
|
self,
|
||||||
|
packages: Optional[List[str]] = None,
|
||||||
|
dry_run: bool = False,
|
||||||
|
non_interactive: bool = False,
|
||||||
|
) -> CommandResult:
|
||||||
|
if packages:
|
||||||
|
cmd = ["pacman", "-S"]
|
||||||
|
if non_interactive:
|
||||||
|
cmd.append("--noconfirm")
|
||||||
|
if dry_run:
|
||||||
|
cmd.append("-p")
|
||||||
|
cmd.extend(packages)
|
||||||
|
else:
|
||||||
|
cmd = ["pacman", "-Su"]
|
||||||
|
if non_interactive:
|
||||||
|
cmd.append("--noconfirm")
|
||||||
|
if dry_run:
|
||||||
|
cmd.append("-p")
|
||||||
|
|
||||||
|
return self.runner.run(cmd)
|
||||||
|
|
||||||
|
def release_upgrade(
|
||||||
|
self,
|
||||||
|
target_release: Optional[str] = None,
|
||||||
|
non_interactive: bool = False,
|
||||||
|
) -> CommandResult:
|
||||||
|
# Arch is a rolling release distribution - system upgrade is a full sync
|
||||||
|
cmd = ["pacman", "-Syu"]
|
||||||
|
if non_interactive:
|
||||||
|
cmd.append("--noconfirm")
|
||||||
|
return self.runner.run(cmd)
|
||||||
|
|
||||||
|
def clean_cache(self) -> CommandResult:
|
||||||
|
return self.runner.run(["pacman", "-Sc", "--noconfirm"])
|
||||||
|
|
||||||
|
def autoremove(self) -> CommandResult:
|
||||||
|
# Find orphan packages
|
||||||
|
orphans_res = self.runner.run(["pacman", "-Qtdq"])
|
||||||
|
orphans = [p.strip() for p in orphans_res.stdout.splitlines() if p.strip()]
|
||||||
|
if not orphans:
|
||||||
|
return CommandResult(return_code=0, stdout="No orphan packages to remove.", stderr="", success=True)
|
||||||
|
|
||||||
|
cmd = ["pacman", "-Rns", "--noconfirm"] + orphans
|
||||||
|
return self.runner.run(cmd)
|
||||||
|
|
||||||
|
def is_reboot_required(self) -> RebootStatus:
|
||||||
|
# On Arch, if running kernel version does not match /usr/lib/modules/<uname>, reboot is required
|
||||||
|
try:
|
||||||
|
running_kernel = os.uname().release
|
||||||
|
modules_dir = Path("/usr/lib/modules") / running_kernel
|
||||||
|
if Path("/usr/lib/modules").exists() and not modules_dir.exists():
|
||||||
|
return RebootStatus(
|
||||||
|
required=True,
|
||||||
|
reason=f"Running kernel {running_kernel} modules directory missing (kernel upgraded)",
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return RebootStatus(required=False)
|
||||||
|
|
||||||
|
def get_lock_files(self) -> List[Path]:
|
||||||
|
return [Path("/var/lib/pacman/db.lck")]
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
from linux_updater.models import CommandResult, DistroFamily, RebootStatus
|
||||||
|
from linux_updater.core.runner import CommandRunner
|
||||||
|
from linux_updater.managers.apt import AptManager
|
||||||
|
from linux_updater.managers.dnf import DnfManager
|
||||||
|
from linux_updater.managers.pacman import PacmanManager
|
||||||
|
|
||||||
|
|
||||||
|
class TestPackageManagers(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.mock_runner = MagicMock(spec=CommandRunner)
|
||||||
|
|
||||||
|
def test_apt_parse_updates(self):
|
||||||
|
manager = AptManager(runner=self.mock_runner)
|
||||||
|
simulated_output = """Reading package lists... Done
|
||||||
|
Building dependency tree... Done
|
||||||
|
The following packages will be upgraded:
|
||||||
|
libssl3 nginx
|
||||||
|
Inst libssl3 [3.0.13-0ubuntu3.1] (3.0.13-0ubuntu3.4 Ubuntu:24.04/noble-updates [amd64])
|
||||||
|
Inst nginx [1.24.0-2ubuntu7] (1.24.0-2ubuntu7.1 Ubuntu:24.04/noble-updates [amd64])
|
||||||
|
Conf libssl3 (3.0.13-0ubuntu3.4 Ubuntu:24.04/noble-updates [amd64])
|
||||||
|
Conf nginx (1.24.0-2ubuntu7.1 Ubuntu:24.04/noble-updates [amd64])
|
||||||
|
"""
|
||||||
|
self.mock_runner.run.return_value = CommandResult(
|
||||||
|
return_code=0,
|
||||||
|
stdout=simulated_output,
|
||||||
|
stderr="",
|
||||||
|
success=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
updates = manager.check_updates()
|
||||||
|
self.assertEqual(len(updates), 2)
|
||||||
|
self.assertEqual(updates[0].package, "libssl3")
|
||||||
|
self.assertEqual(updates[0].current_version, "3.0.13-0ubuntu3.1")
|
||||||
|
self.assertEqual(updates[0].new_version, "3.0.13-0ubuntu3.4")
|
||||||
|
self.assertEqual(updates[1].package, "nginx")
|
||||||
|
|
||||||
|
def test_apt_apply_updates_command(self):
|
||||||
|
manager = AptManager(runner=self.mock_runner)
|
||||||
|
self.mock_runner.run.return_value = CommandResult(0, "", "", True)
|
||||||
|
|
||||||
|
# Full upgrade
|
||||||
|
manager.apply_updates(dry_run=False, non_interactive=True)
|
||||||
|
call_args = self.mock_runner.run.call_args[0][0]
|
||||||
|
self.assertIn("upgrade", call_args)
|
||||||
|
self.assertIn("-y", call_args)
|
||||||
|
|
||||||
|
# Selective upgrade
|
||||||
|
manager.apply_updates(packages=["nginx", "curl"], dry_run=False, non_interactive=True)
|
||||||
|
call_args2 = self.mock_runner.run.call_args[0][0]
|
||||||
|
self.assertIn("install", call_args2)
|
||||||
|
self.assertIn("--only-upgrade", call_args2)
|
||||||
|
self.assertIn("nginx", call_args2)
|
||||||
|
self.assertIn("curl", call_args2)
|
||||||
|
|
||||||
|
def test_dnf_check_updates_exit_code_100(self):
|
||||||
|
manager = DnfManager(runner=self.mock_runner)
|
||||||
|
simulated_output = """
|
||||||
|
Last metadata expiration check: 0:15:32 ago on Fri 02 Oct 2026.
|
||||||
|
systemd.x86_64 252-32.el9_4.1 baseos
|
||||||
|
openssl.x86_64 1:3.0.7-27.el9_4 baseos
|
||||||
|
"""
|
||||||
|
# Code 100 means updates available
|
||||||
|
self.mock_runner.run.return_value = CommandResult(
|
||||||
|
return_code=100,
|
||||||
|
stdout=simulated_output,
|
||||||
|
stderr="",
|
||||||
|
success=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
updates = manager.check_updates()
|
||||||
|
self.assertEqual(len(updates), 2)
|
||||||
|
self.assertEqual(updates[0].package, "systemd.x86_64")
|
||||||
|
self.assertEqual(updates[0].new_version, "252-32.el9_4.1")
|
||||||
|
self.assertEqual(updates[0].repo, "baseos")
|
||||||
|
|
||||||
|
def test_dnf_apply_updates_command(self):
|
||||||
|
manager = DnfManager(runner=self.mock_runner)
|
||||||
|
self.mock_runner.run.return_value = CommandResult(0, "", "", True)
|
||||||
|
|
||||||
|
# Full upgrade
|
||||||
|
manager.apply_updates(dry_run=False, non_interactive=True)
|
||||||
|
call_args = self.mock_runner.run.call_args[0][0]
|
||||||
|
self.assertEqual(call_args, ["dnf", "upgrade", "-y"])
|
||||||
|
|
||||||
|
# Selective upgrade
|
||||||
|
manager.apply_updates(packages=["systemd"], dry_run=False, non_interactive=True)
|
||||||
|
call_args2 = self.mock_runner.run.call_args[0][0]
|
||||||
|
self.assertEqual(call_args2, ["dnf", "upgrade", "-y", "systemd"])
|
||||||
|
|
||||||
|
def test_pacman_parse_updates(self):
|
||||||
|
manager = PacmanManager(runner=self.mock_runner)
|
||||||
|
simulated_output = """linux 6.8.9.arch1-1 -> 6.8.10.arch1-1
|
||||||
|
systemd 255.5-1 -> 255.6-1 [extra]
|
||||||
|
"""
|
||||||
|
self.mock_runner.run.return_value = CommandResult(
|
||||||
|
return_code=0,
|
||||||
|
stdout=simulated_output,
|
||||||
|
stderr="",
|
||||||
|
success=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
updates = manager.check_updates()
|
||||||
|
self.assertEqual(len(updates), 2)
|
||||||
|
self.assertEqual(updates[0].package, "linux")
|
||||||
|
self.assertEqual(updates[0].current_version, "6.8.9.arch1-1")
|
||||||
|
self.assertEqual(updates[0].new_version, "6.8.10.arch1-1")
|
||||||
|
self.assertEqual(updates[1].package, "systemd")
|
||||||
|
|
||||||
|
def test_pacman_apply_updates_command(self):
|
||||||
|
manager = PacmanManager(runner=self.mock_runner)
|
||||||
|
self.mock_runner.run.return_value = CommandResult(0, "", "", True)
|
||||||
|
|
||||||
|
# Full upgrade
|
||||||
|
manager.apply_updates(dry_run=False, non_interactive=True)
|
||||||
|
call_args = self.mock_runner.run.call_args[0][0]
|
||||||
|
self.assertEqual(call_args, ["pacman", "-Su", "--noconfirm"])
|
||||||
|
|
||||||
|
# Selective upgrade
|
||||||
|
manager.apply_updates(packages=["linux"], dry_run=False, non_interactive=True)
|
||||||
|
call_args2 = self.mock_runner.run.call_args[0][0]
|
||||||
|
self.assertEqual(call_args2, ["pacman", "-S", "--noconfirm", "linux"])
|
||||||
|
|
||||||
|
def test_apt_reboot_required(self):
|
||||||
|
manager = AptManager(runner=self.mock_runner)
|
||||||
|
with patch.object(Path, "exists") as mock_exists:
|
||||||
|
mock_exists.return_value = True
|
||||||
|
status = manager.is_reboot_required()
|
||||||
|
self.assertTrue(status.required)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user