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