389 lines
18 KiB
Python
389 lines
18 KiB
Python
import shutil
|
|
from pathlib import Path
|
|
from typing import List, Optional, Tuple
|
|
|
|
from linux_updater.core.runner import CommandRunner
|
|
from linux_updater.managers.base import PackageManager
|
|
from linux_updater.models import CommandResult, DistroInfo, PackageUpdate, RebootStatus
|
|
|
|
|
|
class DnfManager(PackageManager):
|
|
def __init__(
|
|
self,
|
|
runner: Optional[CommandRunner] = None,
|
|
binary: Optional[str] = None,
|
|
distro_info: Optional[DistroInfo] = None,
|
|
) -> None:
|
|
self.runner = runner or CommandRunner()
|
|
self.distro_info = distro_info
|
|
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 dry_run:
|
|
cmd.append("--assumeno")
|
|
elif non_interactive:
|
|
cmd.append("-y")
|
|
|
|
if packages:
|
|
cmd.extend(packages)
|
|
|
|
res = self.runner.run(cmd)
|
|
if dry_run and res.return_code == 1:
|
|
combined = res.stdout + res.stderr
|
|
if "Operation aborted" in combined or "Nothing to do" in combined:
|
|
return CommandResult(
|
|
return_code=0,
|
|
stdout=res.stdout,
|
|
stderr=res.stderr,
|
|
success=True,
|
|
)
|
|
return res
|
|
|
|
def _get_distro_info(self) -> DistroInfo:
|
|
if self.distro_info is None:
|
|
from linux_updater.core.detector import DistroDetector
|
|
self.distro_info = DistroDetector().detect()
|
|
return self.distro_info
|
|
|
|
def _ensure_fedora_upgrade_dependencies(self) -> Tuple[bool, str]:
|
|
"""Ensures python3-dnf-plugins-core is installed for Fedora system-upgrade."""
|
|
check = self.runner.run([self.binary, "system-upgrade", "--help"])
|
|
if check.return_code == 0:
|
|
return True, "Fedora system-upgrade plugin is available."
|
|
|
|
self.runner._log("[UPGRADE] Fedora system-upgrade plugin not found. Attempting automatic installation of 'python3-dnf-plugins-core'...")
|
|
res = self.runner.run([self.binary, "install", "-y", "python3-dnf-plugins-core"])
|
|
if res.return_code != 0:
|
|
res = self.runner.run([self.binary, "install", "-y", "dnf-plugins-core"])
|
|
|
|
if res.return_code != 0:
|
|
err_msg = (
|
|
"Failed to automatically install Fedora upgrade plugin ('python3-dnf-plugins-core').\n"
|
|
f"DNF exited with code {res.return_code}.\n"
|
|
f"Details:\n{res.stderr or res.stdout}\n"
|
|
"Troubleshooting:\n"
|
|
"1. Verify internet connectivity and repository mirrors.\n"
|
|
"2. Try installing manually: sudo dnf install -y python3-dnf-plugins-core\n"
|
|
"3. Refresh repository metadata: sudo dnf makecache"
|
|
)
|
|
self.runner._log(f"[ERROR] {err_msg}")
|
|
return False, err_msg
|
|
|
|
check_after = self.runner.run([self.binary, "system-upgrade", "--help"])
|
|
if check_after.return_code != 0:
|
|
err_msg = (
|
|
"Package 'python3-dnf-plugins-core' was installed, but 'dnf system-upgrade' remains unavailable.\n"
|
|
"Troubleshooting: Please check DNF plugin configuration under /etc/dnf/plugins/."
|
|
)
|
|
self.runner._log(f"[ERROR] {err_msg}")
|
|
return False, err_msg
|
|
|
|
return True, "Fedora system-upgrade plugin successfully installed."
|
|
|
|
def _ensure_elevate_dependencies(self, distro_id: str, version_id: str) -> Tuple[bool, str]:
|
|
"""Ensures ELevate and Leapp components are installed for AlmaLinux, Rocky, or CentOS."""
|
|
if shutil.which("leapp"):
|
|
return True, "Leapp upgrade framework is already installed."
|
|
|
|
major = version_id.split(".")[0] if version_id else "9"
|
|
pretty = distro_id.title()
|
|
self.runner._log(
|
|
f"[UPGRADE] Leapp upgrade framework is not installed on {pretty} {version_id}. "
|
|
f"Attempting automatic installation of ELevate components for Enterprise Linux {major}..."
|
|
)
|
|
|
|
# 1. Install ELevate release repository package
|
|
elevate_rpm_url = f"http://repo.almalinux.org/elevate/elevate-release-latest-el{major}.noarch.rpm"
|
|
self.runner._log(f"[UPGRADE] Installing ELevate repository package from {elevate_rpm_url}...")
|
|
res_repo = self.runner.run([self.binary, "install", "-y", elevate_rpm_url])
|
|
if res_repo.return_code != 0:
|
|
res_repo = self.runner.run([self.binary, "install", "-y", "elevate-release"])
|
|
|
|
if res_repo.return_code != 0:
|
|
err_msg = (
|
|
f"Failed to install ELevate repository package for {pretty} EL{major}.\n"
|
|
f"DNF exited with code {res_repo.return_code}.\n"
|
|
f"Details:\n{res_repo.stderr or res_repo.stdout}\n"
|
|
"Troubleshooting:\n"
|
|
f"1. Verify internet connectivity to http://repo.almalinux.org.\n"
|
|
f"2. Manually install repository: sudo dnf install -y {elevate_rpm_url}\n"
|
|
"3. Ensure DNF base repositories are functioning properly."
|
|
)
|
|
self.runner._log(f"[ERROR] {err_msg}")
|
|
return False, err_msg
|
|
|
|
# 2. Determine target data package based on distribution
|
|
data_pkg = f"leapp-data-{distro_id}" if distro_id in ("almalinux", "rocky", "centos") else "leapp-data-almalinux"
|
|
pkgs_to_install = ["leapp-upgrade", data_pkg]
|
|
self.runner._log(f"[UPGRADE] Installing Leapp packages: {' '.join(pkgs_to_install)}...")
|
|
res_pkgs = self.runner.run([self.binary, "install", "-y"] + pkgs_to_install)
|
|
if res_pkgs.return_code != 0:
|
|
res_pkgs = self.runner.run([self.binary, "install", "-y", "leapp", data_pkg])
|
|
|
|
if res_pkgs.return_code != 0:
|
|
err_msg = (
|
|
f"Failed to install Leapp upgrade packages ({', '.join(pkgs_to_install)}).\n"
|
|
f"DNF exited with code {res_pkgs.return_code}.\n"
|
|
f"Details:\n{res_pkgs.stderr or res_pkgs.stdout}\n"
|
|
"Troubleshooting:\n"
|
|
f"1. Manually install via: sudo dnf install -y leapp-upgrade {data_pkg}\n"
|
|
"2. Check if ELevate repository is enabled: dnf repolist | grep -i elevate\n"
|
|
"3. Inspect /var/log/dnf.log for dependency conflict details."
|
|
)
|
|
self.runner._log(f"[ERROR] {err_msg}")
|
|
return False, err_msg
|
|
|
|
if not shutil.which("leapp"):
|
|
err_msg = (
|
|
"Leapp packages were installed, but 'leapp' binary was not found in system PATH.\n"
|
|
"Troubleshooting: Verify that /usr/bin and /usr/sbin are in PATH."
|
|
)
|
|
self.runner._log(f"[ERROR] {err_msg}")
|
|
return False, err_msg
|
|
|
|
return True, "ELevate / Leapp components successfully installed."
|
|
|
|
def _check_rhel_subscription(self) -> Tuple[bool, str]:
|
|
"""Validates that Red Hat Enterprise Linux has an active subscription."""
|
|
if shutil.which("subscription-manager"):
|
|
res = self.runner.run(["subscription-manager", "status"])
|
|
if res.return_code != 0:
|
|
err_msg = (
|
|
"Red Hat Enterprise Linux requires an active Red Hat subscription for major release upgrades.\n"
|
|
"'subscription-manager' reported that this system is not registered or has no active entitlements.\n"
|
|
f"Details:\n{res.stdout or res.stderr}\n"
|
|
"Troubleshooting:\n"
|
|
"1. Register system: sudo subscription-manager register --auto-attach\n"
|
|
"2. Check entitlement status: sudo subscription-manager status\n"
|
|
"3. Refer to Red Hat Solution 4263361 for Leapp repository setup."
|
|
)
|
|
self.runner._log(f"[ERROR] {err_msg}")
|
|
return False, err_msg
|
|
return True, "Subscription status verified."
|
|
|
|
def release_upgrade(
|
|
self,
|
|
target_release: Optional[str] = None,
|
|
dry_run: bool = False,
|
|
non_interactive: bool = False,
|
|
) -> CommandResult:
|
|
distro = self._get_distro_info()
|
|
distro_id = distro.distro_id.lower()
|
|
|
|
# 1. Fedora workflow (dnf system-upgrade)
|
|
if distro_id == "fedora":
|
|
ok, msg = self._ensure_fedora_upgrade_dependencies()
|
|
if not ok:
|
|
if dry_run:
|
|
return CommandResult(
|
|
return_code=0,
|
|
stdout=f"[DRY-RUN] Release upgrade simulation for Fedora (target: {target_release or 'latest'})\nNote: {msg}",
|
|
stderr="",
|
|
success=True,
|
|
)
|
|
return CommandResult(return_code=1, stdout="", stderr=msg, success=False)
|
|
|
|
cmd = [self.binary, "system-upgrade", "download"]
|
|
if dry_run:
|
|
cmd.append("--assumeno")
|
|
elif non_interactive:
|
|
cmd.append("-y")
|
|
if target_release:
|
|
cmd.append(f"--releasever={target_release}")
|
|
|
|
res = self.runner.run(cmd)
|
|
if dry_run and res.return_code == 1:
|
|
combined = res.stdout + res.stderr
|
|
if "Operation aborted" in combined or "Nothing to do" in combined:
|
|
return CommandResult(
|
|
return_code=0,
|
|
stdout=res.stdout,
|
|
stderr=res.stderr,
|
|
success=True,
|
|
)
|
|
return res
|
|
|
|
# 2. AlmaLinux / Rocky / CentOS workflow (ELevate + Leapp)
|
|
if distro_id in ("almalinux", "rocky", "centos"):
|
|
ok, msg = self._ensure_elevate_dependencies(distro_id, distro.version_id)
|
|
if not ok:
|
|
if dry_run:
|
|
return CommandResult(
|
|
return_code=0,
|
|
stdout=f"[DRY-RUN] Release upgrade simulation for {distro.pretty_name} (target: {target_release or 'next major'})\nDependency status:\n{msg}",
|
|
stderr="",
|
|
success=True,
|
|
)
|
|
return CommandResult(return_code=1, stdout="", stderr=msg, success=False)
|
|
|
|
if dry_run:
|
|
self.runner._log("[UPGRADE] Running Leapp pre-upgrade diagnostic ('leapp preupgrade')...")
|
|
res = self.runner.run(["leapp", "preupgrade"])
|
|
report_file = Path("/var/log/leapp/leapp-report.txt")
|
|
report_hint = f"\nLeapp pre-upgrade report saved to {report_file}." if report_file.exists() else ""
|
|
if res.return_code != 0:
|
|
self.runner._log(f"[WARN] Leapp pre-upgrade detected inhibitors or required answers (exit code {res.return_code}).{report_hint}")
|
|
return CommandResult(
|
|
return_code=0,
|
|
stdout=f"[DRY-RUN] Leapp pre-upgrade evaluation finished with code {res.return_code}.\n{res.stdout}{report_hint}",
|
|
stderr=res.stderr,
|
|
success=True,
|
|
)
|
|
return CommandResult(
|
|
return_code=0,
|
|
stdout=f"[DRY-RUN] Leapp pre-upgrade evaluation completed successfully!{report_hint}",
|
|
stderr="",
|
|
success=True,
|
|
)
|
|
else:
|
|
self.runner._log("[UPGRADE] Starting Leapp in-place upgrade ('leapp upgrade')...")
|
|
res = self.runner.run(["leapp", "upgrade"])
|
|
if res.return_code != 0:
|
|
err_msg = (
|
|
f"Leapp in-place upgrade failed with exit code {res.return_code}.\n"
|
|
f"Details:\n{res.stderr or res.stdout}\n"
|
|
"Troubleshooting:\n"
|
|
"1. Review report: cat /var/log/leapp/leapp-report.txt\n"
|
|
"2. Resolve any inhibitor items or missing answer files.\n"
|
|
"3. Re-run: sudo linux-updater release-upgrade"
|
|
)
|
|
self.runner._log(f"[ERROR] {err_msg}")
|
|
return CommandResult(return_code=res.return_code, stdout=res.stdout, stderr=err_msg, success=False)
|
|
return res
|
|
|
|
# 3. Official RHEL workflow (subscription-manager + Leapp)
|
|
if distro_id == "rhel":
|
|
ok, msg = self._check_rhel_subscription()
|
|
if not ok:
|
|
if dry_run:
|
|
return CommandResult(
|
|
return_code=0,
|
|
stdout=f"[DRY-RUN] Simulation for RHEL release upgrade.\nSubscription warning:\n{msg}",
|
|
stderr="",
|
|
success=True,
|
|
)
|
|
return CommandResult(return_code=1, stdout="", stderr=msg, success=False)
|
|
|
|
if not shutil.which("leapp"):
|
|
self.runner._log("[UPGRADE] Installing Red Hat Leapp upgrade framework ('leapp-upgrade')...")
|
|
res_inst = self.runner.run([self.binary, "install", "-y", "leapp-upgrade"])
|
|
if res_inst.return_code != 0:
|
|
err_msg = (
|
|
f"Failed to install 'leapp-upgrade' from Red Hat repositories (exit code {res_inst.return_code}).\n"
|
|
f"Details:\n{res_inst.stderr or res_inst.stdout}\n"
|
|
"Troubleshooting:\n"
|
|
"1. Verify active Red Hat subscription includes upgrade channels.\n"
|
|
"2. Install manually: sudo dnf install -y leapp-upgrade"
|
|
)
|
|
self.runner._log(f"[ERROR] {err_msg}")
|
|
if dry_run:
|
|
return CommandResult(return_code=0, stdout=f"[DRY-RUN] Simulation for RHEL.\n{err_msg}", stderr="", success=True)
|
|
return CommandResult(return_code=1, stdout="", stderr=err_msg, success=False)
|
|
|
|
if dry_run:
|
|
res = self.runner.run(["leapp", "preupgrade"])
|
|
return CommandResult(return_code=0, stdout=f"[DRY-RUN] Leapp pre-upgrade simulation:\n{res.stdout}", stderr="", success=True)
|
|
else:
|
|
return self.runner.run(["leapp", "upgrade"])
|
|
|
|
# 4. Fallback for other DNF-based systems
|
|
check = self.runner.run([self.binary, "system-upgrade", "--help"])
|
|
if check.return_code != 0:
|
|
if dry_run:
|
|
return CommandResult(
|
|
return_code=0,
|
|
stdout=f"[DRY-RUN] Release upgrade simulation for {distro.pretty_name} (target: {target_release or 'latest'})",
|
|
stderr="",
|
|
success=True,
|
|
)
|
|
return CommandResult(
|
|
return_code=1,
|
|
stdout="",
|
|
stderr=f"Major release upgrade for {distro.pretty_name} is not natively supported or requires external tools.",
|
|
success=False,
|
|
)
|
|
|
|
cmd = [self.binary, "system-upgrade", "download"]
|
|
if dry_run:
|
|
cmd.append("--assumeno")
|
|
elif non_interactive:
|
|
cmd.append("-y")
|
|
if target_release:
|
|
cmd.append(f"--releasever={target_release}")
|
|
|
|
res = self.runner.run(cmd)
|
|
if dry_run and res.return_code == 1:
|
|
combined = res.stdout + res.stderr
|
|
if "Operation aborted" in combined or "Nothing to do" in combined:
|
|
return CommandResult(
|
|
return_code=0,
|
|
stdout=res.stdout,
|
|
stderr=res.stderr,
|
|
success=True,
|
|
)
|
|
return res
|
|
|
|
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"),
|
|
]
|