feat: add root check, singleton lock, RHEL/Fedora upgrade auto-installer & container tests for AlmaLinux 9 and Arch Linux
This commit is contained in:
1 parent
507a3fd310
commit
44c9423166
10 files changed
+711
-27
No files matched your search
@@ -9,3 +9,4 @@ dist/
|
|||||||
build/
|
build/
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
.eggs/
|
.eggs/
|
||||||
|
linux-updater-*/
|
||||||
@@ -12,9 +12,13 @@
|
|||||||
- [x] Slice 4 — major release upgrade & configuration engine
|
- [x] Slice 4 — major release upgrade & configuration engine
|
||||||
- [x] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm)
|
- [x] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm)
|
||||||
- [x] Slice 6 — documentation (man page, README, user/admin/developer guides)
|
- [x] Slice 6 — documentation (man page, README, user/admin/developer guides)
|
||||||
|
- [x] Slice 7 — safety guardrails: root privilege check on mutating commands & singleton concurrency flock
|
||||||
|
- [x] Slice 8 — upgrade dependency auto-installation (ELevate/Leapp/dnf-plugins-core) & container test suites (AlmaLinux 9, Arch Linux)
|
||||||
|
|
||||||
## Notes for a fresh session
|
## Notes for a fresh session
|
||||||
- Project: Multi-distribution Linux system updater in Python.
|
- Project: Multi-distribution Linux system updater in Python.
|
||||||
- Process: Software Factory 4-gate workflow.
|
- Process: Software Factory 4-gate workflow.
|
||||||
- All 4 Gates APPROVED on 2026-10-02.
|
- All 4 Gates APPROVED on 2026-10-02. Slices 1–8 fully implemented, tested, and verified.
|
||||||
- Scope: Debian/Ubuntu, RHEL 8/9/Fedora, Arch Linux. Pre-flight health checks with auto-remediation. Routine update + major release-upgrade. Selective package updates (--packages) + target release upgrade (--target-release). Pure Python standard library (compatible with Python >= 3.6). Packaging for .tar.gz, .deb, and .rpm. MAN page (Section 8) + user, admin, developer documentation.
|
- Scope: Debian/Ubuntu, RHEL 8/9/Fedora/CentOS/Rocky/AlmaLinux, Arch Linux. Pre-flight health checks with auto-remediation. Routine update + major release-upgrade. Selective package updates (--packages) + target release upgrade (--target-release). Pure Python standard library (compatible with Python >= 3.6). Packaging for .tar.gz, .deb, and .rpm. MAN page (Section 8) + user, admin, developer documentation.
|
||||||
|
- Safety: Root privilege checks on mutating operations (`update`, `release-upgrade`, `clean`), while non-root is allowed for inspection (`health`, `check`, `--dry-run`). Advisory flock singleton lock (`/var/run/linux-updater.pid` with fallback to `/tmp/linux-updater-<uid>.pid`). Automatic dependency management for major upgrades (ELevate `leapp-upgrade` on AlmaLinux/Rocky, `dnf-plugins-core` on Fedora) with clear English error reporting and troubleshooting guidance.
|
||||||
|
- Test suites: 47 local unit tests pass (100%). Podman container integration test suite (`tests/containers/run_tests.sh`) successfully verified across Debian 12, Ubuntu 22.04, Fedora 40, AlmaLinux 8, AlmaLinux 9, and Arch Linux.
|
||||||
+69
-1
@@ -9,6 +9,7 @@ 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.core.health import HealthChecker
|
from linux_updater.core.health import HealthChecker
|
||||||
|
from linux_updater.core.lock import InstanceLock
|
||||||
from linux_updater.core.remediation import RemediationEngine
|
from linux_updater.core.remediation import RemediationEngine
|
||||||
from linux_updater.core.runner import CommandRunner
|
from linux_updater.core.runner import CommandRunner
|
||||||
from linux_updater.managers import get_manager
|
from linux_updater.managers import get_manager
|
||||||
@@ -153,6 +154,12 @@ def prompt_confirmation(prompt: str = "Do you want to proceed with updates? [Y/n
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def check_root_privileges() -> bool:
|
||||||
|
if hasattr(os, "geteuid"):
|
||||||
|
return os.geteuid() == 0
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
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)
|
||||||
@@ -179,6 +186,67 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
print(f"Error: Unsupported or unrecognized Linux distribution: {distro.distro_id}", file=sys.stderr)
|
print(f"Error: Unsupported or unrecognized Linux distribution: {distro.distro_id}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
# Root privilege check for mutating operations
|
||||||
|
mutating_commands = {"update", "release-upgrade", "clean"}
|
||||||
|
if args.command in mutating_commands and not dry_run:
|
||||||
|
if not check_root_privileges():
|
||||||
|
if json_output:
|
||||||
|
print(json.dumps({
|
||||||
|
"success": False,
|
||||||
|
"error": "permission_denied",
|
||||||
|
"message": f"Root privileges (sudo) are required to execute '{args.command}'."
|
||||||
|
}, indent=2))
|
||||||
|
else:
|
||||||
|
print(
|
||||||
|
f"Error: Root privileges (sudo) are required to execute '{args.command}'.\n"
|
||||||
|
f"Please run with: sudo linux-updater {args.command}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
# Concurrency control: singleton instance lock
|
||||||
|
instance_lock = InstanceLock()
|
||||||
|
if not instance_lock.acquire():
|
||||||
|
holder_pid = instance_lock.get_holder_pid()
|
||||||
|
holder_msg = f" (PID {holder_pid})" if holder_pid else ""
|
||||||
|
if json_output:
|
||||||
|
print(json.dumps({
|
||||||
|
"success": False,
|
||||||
|
"error": "already_running",
|
||||||
|
"message": f"Another instance of linux-updater is already running{holder_msg}."
|
||||||
|
}, indent=2))
|
||||||
|
else:
|
||||||
|
print(
|
||||||
|
f"Error: Another instance of linux-updater is already running{holder_msg}. Aborting.",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
try:
|
||||||
|
return _run(
|
||||||
|
args=args,
|
||||||
|
distro=distro,
|
||||||
|
non_interactive=non_interactive,
|
||||||
|
dry_run=dry_run,
|
||||||
|
no_remediation=no_remediation,
|
||||||
|
skip_preflight=skip_preflight,
|
||||||
|
json_output=json_output,
|
||||||
|
config_path=config_path,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
instance_lock.release()
|
||||||
|
|
||||||
|
|
||||||
|
def _run(
|
||||||
|
args: argparse.Namespace,
|
||||||
|
distro,
|
||||||
|
non_interactive: bool,
|
||||||
|
dry_run: bool,
|
||||||
|
no_remediation: bool,
|
||||||
|
skip_preflight: bool,
|
||||||
|
json_output: bool,
|
||||||
|
config_path: str,
|
||||||
|
) -> int:
|
||||||
config = UpdaterConfig.load(Path(config_path) if config_path else None)
|
config = UpdaterConfig.load(Path(config_path) if config_path else None)
|
||||||
if non_interactive:
|
if non_interactive:
|
||||||
config.non_interactive = True
|
config.non_interactive = True
|
||||||
@@ -212,7 +280,7 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
runner = CommandRunner(verbose=config.verbose, log_file=resolved_log)
|
runner = CommandRunner(verbose=config.verbose, log_file=resolved_log)
|
||||||
if resolved_log:
|
if resolved_log:
|
||||||
runner._log(f"=== Linux System Updater v1.0.0 started (Distro: {distro.pretty_name}, PID: {os.getpid()}) ===")
|
runner._log(f"=== Linux System Updater v1.0.0 started (Distro: {distro.pretty_name}, PID: {os.getpid()}) ===")
|
||||||
manager = get_manager(distro.family, runner=runner)
|
manager = get_manager(distro.family, runner=runner, distro_info=distro)
|
||||||
checker = HealthChecker(config=config, manager=manager)
|
checker = HealthChecker(config=config, manager=manager)
|
||||||
remediation = RemediationEngine(manager=manager)
|
remediation = RemediationEngine(manager=manager)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class InstanceLock:
|
||||||
|
def __init__(self, lock_path: Optional[Path] = None) -> None:
|
||||||
|
self.custom_path = lock_path is not None
|
||||||
|
self.lock_path = lock_path or Path("/var/run/linux-updater.pid")
|
||||||
|
self.fd: Optional[int] = None
|
||||||
|
self.acquired: bool = False
|
||||||
|
|
||||||
|
def acquire(self) -> bool:
|
||||||
|
"""Attempts to acquire exclusive advisory flock. Returns False if already locked."""
|
||||||
|
try:
|
||||||
|
import fcntl
|
||||||
|
except ImportError:
|
||||||
|
# Non-Unix environment fallback
|
||||||
|
self.acquired = True
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Ensure parent directory exists or fallback to /tmp
|
||||||
|
try:
|
||||||
|
self.lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self.fd = os.open(str(self.lock_path), os.O_RDWR | os.O_CREAT, 0o644)
|
||||||
|
except (PermissionError, OSError):
|
||||||
|
if not self.custom_path:
|
||||||
|
uid = os.getuid() if hasattr(os, "getuid") else 0
|
||||||
|
self.lock_path = Path(f"/tmp/linux-updater-{uid}.pid")
|
||||||
|
try:
|
||||||
|
self.fd = os.open(str(self.lock_path), os.O_RDWR | os.O_CREAT, 0o644)
|
||||||
|
except Exception:
|
||||||
|
self.acquired = True
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
os.ftruncate(self.fd, 0)
|
||||||
|
os.write(self.fd, f"{os.getpid()}\n".encode("utf-8"))
|
||||||
|
try:
|
||||||
|
os.fsync(self.fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self.acquired = True
|
||||||
|
return True
|
||||||
|
except (BlockingIOError, IOError, OSError):
|
||||||
|
self.acquired = False
|
||||||
|
return False
|
||||||
|
|
||||||
|
def get_holder_pid(self) -> Optional[int]:
|
||||||
|
try:
|
||||||
|
if self.lock_path.exists():
|
||||||
|
content = self.lock_path.read_text(encoding="utf-8").strip()
|
||||||
|
if content and content.isdigit():
|
||||||
|
return int(content)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
def release(self) -> None:
|
||||||
|
if self.fd is not None and self.acquired:
|
||||||
|
try:
|
||||||
|
import fcntl
|
||||||
|
fcntl.flock(self.fd, fcntl.LOCK_UN)
|
||||||
|
os.close(self.fd)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self.fd = None
|
||||||
|
self.acquired = False
|
||||||
|
try:
|
||||||
|
if self.lock_path.exists():
|
||||||
|
self.lock_path.unlink()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __enter__(self) -> "InstanceLock":
|
||||||
|
if not self.acquire():
|
||||||
|
holder = self.get_holder_pid()
|
||||||
|
holder_msg = f" (PID {holder})" if holder else ""
|
||||||
|
raise RuntimeError(f"Another instance of linux-updater is already running{holder_msg}.")
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
|
||||||
|
self.release()
|
||||||
@@ -5,14 +5,18 @@ from linux_updater.managers.base import PackageManager
|
|||||||
from linux_updater.managers.apt import AptManager
|
from linux_updater.managers.apt import AptManager
|
||||||
from linux_updater.managers.dnf import DnfManager
|
from linux_updater.managers.dnf import DnfManager
|
||||||
from linux_updater.managers.pacman import PacmanManager
|
from linux_updater.managers.pacman import PacmanManager
|
||||||
from linux_updater.models import DistroFamily
|
from linux_updater.models import DistroFamily, DistroInfo
|
||||||
|
|
||||||
|
|
||||||
def get_manager(family: DistroFamily, runner: Optional[CommandRunner] = None) -> PackageManager:
|
def get_manager(
|
||||||
|
family: DistroFamily,
|
||||||
|
runner: Optional[CommandRunner] = None,
|
||||||
|
distro_info: Optional[DistroInfo] = None,
|
||||||
|
) -> PackageManager:
|
||||||
if family == DistroFamily.DEBIAN:
|
if family == DistroFamily.DEBIAN:
|
||||||
return AptManager(runner=runner)
|
return AptManager(runner=runner)
|
||||||
elif family == DistroFamily.RHEL:
|
elif family == DistroFamily.RHEL:
|
||||||
return DnfManager(runner=runner)
|
return DnfManager(runner=runner, distro_info=distro_info)
|
||||||
elif family == DistroFamily.ARCH:
|
elif family == DistroFamily.ARCH:
|
||||||
return PacmanManager(runner=runner)
|
return PacmanManager(runner=runner)
|
||||||
else:
|
else:
|
||||||
|
|||||||
+252
-16
@@ -1,15 +1,21 @@
|
|||||||
import shutil
|
import shutil
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List, Optional
|
from typing import List, Optional, Tuple
|
||||||
|
|
||||||
from linux_updater.core.runner import CommandRunner
|
from linux_updater.core.runner import CommandRunner
|
||||||
from linux_updater.managers.base import PackageManager
|
from linux_updater.managers.base import PackageManager
|
||||||
from linux_updater.models import CommandResult, PackageUpdate, RebootStatus
|
from linux_updater.models import CommandResult, DistroInfo, PackageUpdate, RebootStatus
|
||||||
|
|
||||||
|
|
||||||
class DnfManager(PackageManager):
|
class DnfManager(PackageManager):
|
||||||
def __init__(self, runner: Optional[CommandRunner] = None, binary: Optional[str] = None) -> None:
|
def __init__(
|
||||||
|
self,
|
||||||
|
runner: Optional[CommandRunner] = None,
|
||||||
|
binary: Optional[str] = None,
|
||||||
|
distro_info: Optional[DistroInfo] = None,
|
||||||
|
) -> None:
|
||||||
self.runner = runner or CommandRunner()
|
self.runner = runner or CommandRunner()
|
||||||
|
self.distro_info = distro_info
|
||||||
if binary is not None:
|
if binary is not None:
|
||||||
self.binary = binary
|
self.binary = binary
|
||||||
else:
|
else:
|
||||||
@@ -74,36 +80,267 @@ class DnfManager(PackageManager):
|
|||||||
)
|
)
|
||||||
return res
|
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(
|
def release_upgrade(
|
||||||
self,
|
self,
|
||||||
target_release: Optional[str] = None,
|
target_release: Optional[str] = None,
|
||||||
dry_run: bool = False,
|
dry_run: bool = False,
|
||||||
non_interactive: bool = False,
|
non_interactive: bool = False,
|
||||||
) -> CommandResult:
|
) -> CommandResult:
|
||||||
import shutil
|
distro = self._get_distro_info()
|
||||||
if shutil.which("leapp"):
|
distro_id = distro.distro_id.lower()
|
||||||
cmd = ["leapp", "preupgrade" if dry_run else "upgrade"]
|
|
||||||
return self.runner.run(cmd)
|
|
||||||
|
|
||||||
# Check if dnf system-upgrade is available
|
# 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"])
|
check = self.runner.run([self.binary, "system-upgrade", "--help"])
|
||||||
if check.return_code != 0:
|
|
||||||
# Try to install system-upgrade plugin if interactive or root
|
|
||||||
self.runner.run([self.binary, "install", "-y", "dnf-plugins-core"])
|
|
||||||
check = self.runner.run([self.binary, "system-upgrade", "--help"])
|
|
||||||
|
|
||||||
if check.return_code != 0:
|
if check.return_code != 0:
|
||||||
if dry_run:
|
if dry_run:
|
||||||
return CommandResult(
|
return CommandResult(
|
||||||
return_code=0,
|
return_code=0,
|
||||||
stdout=f"[DRY-RUN] Release upgrade simulation for target release {target_release or 'latest'}",
|
stdout=f"[DRY-RUN] Release upgrade simulation for {distro.pretty_name} (target: {target_release or 'latest'})",
|
||||||
stderr="",
|
stderr="",
|
||||||
success=True,
|
success=True,
|
||||||
)
|
)
|
||||||
return CommandResult(
|
return CommandResult(
|
||||||
return_code=1,
|
return_code=1,
|
||||||
stdout="",
|
stdout="",
|
||||||
stderr="Major release upgrade requires 'dnf system-upgrade' (Fedora) or 'leapp' (RHEL/AlmaLinux). Please install the required upgrade framework.",
|
stderr=f"Major release upgrade for {distro.pretty_name} is not natively supported or requires external tools.",
|
||||||
success=False,
|
success=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -112,7 +349,6 @@ class DnfManager(PackageManager):
|
|||||||
cmd.append("--assumeno")
|
cmd.append("--assumeno")
|
||||||
elif non_interactive:
|
elif non_interactive:
|
||||||
cmd.append("-y")
|
cmd.append("-y")
|
||||||
|
|
||||||
if target_release:
|
if target_release:
|
||||||
cmd.append(f"--releasever={target_release}")
|
cmd.append(f"--releasever={target_release}")
|
||||||
|
|
||||||
|
|||||||
@@ -104,18 +104,123 @@ run_distro_test() {
|
|||||||
test -f /var/log/linux-updater/latest.log
|
test -f /var/log/linux-updater/latest.log
|
||||||
"
|
"
|
||||||
;;
|
;;
|
||||||
|
almalinux9)
|
||||||
|
IMAGE="docker.io/library/almalinux:9"
|
||||||
|
CMD="
|
||||||
|
set -e
|
||||||
|
dnf install -y -q python3 rpm-build procps-ng > /dev/null
|
||||||
|
rm -rf dist/rpm
|
||||||
|
echo '=== 1. Verifying Native Python on AlmaLinux 9 ==='
|
||||||
|
python3 --version
|
||||||
|
echo '=== 2. Building packages and RPM inside AlmaLinux 9 container ==='
|
||||||
|
python3 packaging/build_packages.py
|
||||||
|
echo '=== 3. Installing generated .rpm package ==='
|
||||||
|
rpm -Uvh --replacepkgs --replacefiles dist/rpm/RPMS/noarch/linux-updater-*.noarch.rpm
|
||||||
|
echo '=== 4. Testing installed command ==='
|
||||||
|
linux-updater --version
|
||||||
|
echo '=== 5. Testing pre-flight health checks ==='
|
||||||
|
linux-updater health
|
||||||
|
echo '=== 6. Testing root privilege guardrails ==='
|
||||||
|
id -u testuser >/dev/null 2>&1 || useradd -m testuser
|
||||||
|
if su - testuser -c 'linux-updater update'; then
|
||||||
|
echo 'FAIL: Unprivileged update succeeded without root!' >&2
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
echo 'OK: Unprivileged update correctly blocked.'
|
||||||
|
fi
|
||||||
|
echo 'OK: Verifying non-root dry-run and health check allowed:'
|
||||||
|
su - testuser -c 'linux-updater update --dry-run -y'
|
||||||
|
su - testuser -c 'linux-updater health'
|
||||||
|
echo '=== 7. Testing singleton concurrency lock ==='
|
||||||
|
python3 -c 'from linux_updater.core.lock import InstanceLock; import time; lock = InstanceLock(); lock.acquire(); time.sleep(3)' &
|
||||||
|
LOCK_PID=\$!
|
||||||
|
sleep 0.5
|
||||||
|
if linux-updater health; then
|
||||||
|
echo 'FAIL: Second instance succeeded despite active lock!' >&2
|
||||||
|
kill \$LOCK_PID 2>/dev/null || true
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
echo 'OK: Second instance correctly blocked by singleton lock.'
|
||||||
|
fi
|
||||||
|
wait \$LOCK_PID 2>/dev/null || true
|
||||||
|
echo '=== 8. Testing package updates (check, dry-run, actual) ==='
|
||||||
|
linux-updater check
|
||||||
|
linux-updater update --dry-run -y
|
||||||
|
linux-updater update -y
|
||||||
|
echo '=== 9. Testing major release upgrade (dry-run with ELevate) ==='
|
||||||
|
linux-updater release-upgrade --dry-run -y
|
||||||
|
echo '=== 10. Verifying standard /var/log/linux-updater logging ==='
|
||||||
|
ls -la /var/log/linux-updater
|
||||||
|
test -f /var/log/linux-updater/latest.log
|
||||||
|
echo '=== AlmaLinux 9 verification complete ==='
|
||||||
|
"
|
||||||
|
;;
|
||||||
|
archlinux)
|
||||||
|
IMAGE="docker.io/library/archlinux:latest"
|
||||||
|
EXTRA_FLAGS="--platform linux/amd64"
|
||||||
|
CMD="
|
||||||
|
set -e
|
||||||
|
sed -i 's/^DownloadUser/#DownloadUser/' /etc/pacman.conf
|
||||||
|
sed -i 's/^#DisableSandboxSyscalls/DisableSandboxSyscalls/' /etc/pacman.conf
|
||||||
|
pacman -Sy --noconfirm python tar gzip procps-ng which > /dev/null
|
||||||
|
rm -rf dist/linux-updater-*.tar.gz linux-updater-1.0.0
|
||||||
|
echo '=== 1. Verifying Python on Arch Linux ==='
|
||||||
|
python3 --version
|
||||||
|
echo '=== 2. Building packages (tarball distribution) ==='
|
||||||
|
python3 packaging/build_packages.py
|
||||||
|
echo '=== 3. Installing from generated tarball via install.sh ==='
|
||||||
|
tar -xzf dist/linux-updater-1.0.0.tar.gz
|
||||||
|
(cd linux-updater-1.0.0 && ./install.sh)
|
||||||
|
echo '=== 4. Testing installed command ==='
|
||||||
|
linux-updater --version
|
||||||
|
echo '=== 5. Testing pre-flight health checks ==='
|
||||||
|
linux-updater health
|
||||||
|
echo '=== 6. Testing root privilege guardrails ==='
|
||||||
|
id -u testuser >/dev/null 2>&1 || useradd -m testuser
|
||||||
|
if su - testuser -c 'linux-updater update'; then
|
||||||
|
echo 'FAIL: Unprivileged update succeeded without root!' >&2
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
echo 'OK: Unprivileged update correctly blocked.'
|
||||||
|
fi
|
||||||
|
echo 'OK: Verifying non-root dry-run and health check allowed:'
|
||||||
|
su - testuser -c 'linux-updater update --dry-run -y'
|
||||||
|
su - testuser -c 'linux-updater health'
|
||||||
|
echo '=== 7. Testing singleton concurrency lock ==='
|
||||||
|
python3 -c 'from linux_updater.core.lock import InstanceLock; import time; lock = InstanceLock(); lock.acquire(); time.sleep(3)' &
|
||||||
|
LOCK_PID=\$!
|
||||||
|
sleep 0.5
|
||||||
|
if linux-updater health; then
|
||||||
|
echo 'FAIL: Second instance succeeded despite active lock!' >&2
|
||||||
|
kill \$LOCK_PID 2>/dev/null || true
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
echo 'OK: Second instance correctly blocked by singleton lock.'
|
||||||
|
fi
|
||||||
|
wait \$LOCK_PID 2>/dev/null || true
|
||||||
|
echo '=== 8. Testing package updates (check & dry-run) ==='
|
||||||
|
linux-updater check
|
||||||
|
linux-updater update --dry-run -y
|
||||||
|
echo '=== 9. Testing rolling release upgrade (dry-run) ==='
|
||||||
|
linux-updater release-upgrade --dry-run -y
|
||||||
|
echo '=== 10. Verifying standard /var/log/linux-updater logging ==='
|
||||||
|
ls -la /var/log/linux-updater
|
||||||
|
test -f /var/log/linux-updater/latest.log
|
||||||
|
echo '=== Arch Linux verification complete ==='
|
||||||
|
"
|
||||||
|
;;
|
||||||
*)
|
*)
|
||||||
echo "Unknown distro: ${D}" >&2
|
echo "Unknown distro: ${D}" >&2
|
||||||
return 1
|
return 1
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
podman run --rm -v "${WORKSPACE}:/workspace:Z" -w /workspace "${IMAGE}" bash -c "${CMD}"
|
podman run --rm ${EXTRA_FLAGS} -v "${WORKSPACE}:/workspace:Z" -w /workspace "${IMAGE}" bash -c "${CMD}"
|
||||||
echo ">>> [SUCCESS] Testing for ${D} PASSED!"
|
echo ">>> [SUCCESS] Testing for ${D} PASSED!"
|
||||||
}
|
}
|
||||||
|
|
||||||
if [ "${DISTRO}" = "all" ]; then
|
if [ "${DISTRO}" = "all" ]; then
|
||||||
for target in debian ubuntu fedora almalinux8; do
|
for target in debian ubuntu fedora almalinux8 almalinux9 archlinux; do
|
||||||
run_distro_test "${target}"
|
run_distro_test "${target}"
|
||||||
done
|
done
|
||||||
else
|
else
|
||||||
|
|||||||
+57
-3
@@ -44,9 +44,10 @@ class TestCLIIntegration(unittest.TestCase):
|
|||||||
code = main(["--json", "health"])
|
code = main(["--json", "health"])
|
||||||
self.assertEqual(code, 0)
|
self.assertEqual(code, 0)
|
||||||
|
|
||||||
|
@patch("linux_updater.cli.check_root_privileges", return_value=True)
|
||||||
@patch("linux_updater.cli.DistroDetector.detect")
|
@patch("linux_updater.cli.DistroDetector.detect")
|
||||||
@patch("linux_updater.cli.get_manager")
|
@patch("linux_updater.cli.get_manager")
|
||||||
def test_cli_user_abort_returns_code_3(self, mock_get_manager, mock_detect):
|
def test_cli_user_abort_returns_code_3(self, mock_get_manager, mock_detect, mock_root):
|
||||||
mock_detect.return_value = DistroInfo(
|
mock_detect.return_value = DistroInfo(
|
||||||
family=DistroFamily.DEBIAN,
|
family=DistroFamily.DEBIAN,
|
||||||
distro_id="ubuntu",
|
distro_id="ubuntu",
|
||||||
@@ -72,9 +73,10 @@ class TestCLIIntegration(unittest.TestCase):
|
|||||||
code = main(["update"])
|
code = main(["update"])
|
||||||
self.assertEqual(code, 3)
|
self.assertEqual(code, 3)
|
||||||
|
|
||||||
|
@patch("linux_updater.cli.check_root_privileges", return_value=True)
|
||||||
@patch("linux_updater.cli.DistroDetector.detect")
|
@patch("linux_updater.cli.DistroDetector.detect")
|
||||||
@patch("linux_updater.cli.get_manager")
|
@patch("linux_updater.cli.get_manager")
|
||||||
def test_cli_update_reboot_required_returns_code_2(self, mock_get_manager, mock_detect):
|
def test_cli_update_reboot_required_returns_code_2(self, mock_get_manager, mock_detect, mock_root):
|
||||||
mock_detect.return_value = DistroInfo(
|
mock_detect.return_value = DistroInfo(
|
||||||
family=DistroFamily.DEBIAN,
|
family=DistroFamily.DEBIAN,
|
||||||
distro_id="ubuntu",
|
distro_id="ubuntu",
|
||||||
@@ -97,9 +99,10 @@ class TestCLIIntegration(unittest.TestCase):
|
|||||||
code = main(["-y", "update"])
|
code = main(["-y", "update"])
|
||||||
self.assertEqual(code, 2)
|
self.assertEqual(code, 2)
|
||||||
|
|
||||||
|
@patch("linux_updater.cli.check_root_privileges", return_value=True)
|
||||||
@patch("linux_updater.cli.DistroDetector.detect")
|
@patch("linux_updater.cli.DistroDetector.detect")
|
||||||
@patch("linux_updater.cli.get_manager")
|
@patch("linux_updater.cli.get_manager")
|
||||||
def test_cli_release_upgrade_calls_manager_with_target(self, mock_get_manager, mock_detect):
|
def test_cli_release_upgrade_calls_manager_with_target(self, mock_get_manager, mock_detect, mock_root):
|
||||||
mock_detect.return_value = DistroInfo(
|
mock_detect.return_value = DistroInfo(
|
||||||
family=DistroFamily.RHEL,
|
family=DistroFamily.RHEL,
|
||||||
distro_id="fedora",
|
distro_id="fedora",
|
||||||
@@ -126,6 +129,57 @@ class TestCLIIntegration(unittest.TestCase):
|
|||||||
non_interactive=True,
|
non_interactive=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@patch("linux_updater.cli.check_root_privileges", return_value=False)
|
||||||
|
@patch("linux_updater.cli.DistroDetector.detect")
|
||||||
|
def test_cli_root_required_for_mutating_commands(self, mock_detect, mock_root):
|
||||||
|
mock_detect.return_value = DistroInfo(
|
||||||
|
family=DistroFamily.DEBIAN,
|
||||||
|
distro_id="ubuntu",
|
||||||
|
version_id="24.04",
|
||||||
|
pretty_name="Ubuntu 24.04",
|
||||||
|
)
|
||||||
|
# Non-root user running update -> exit code 1
|
||||||
|
code = main(["update"])
|
||||||
|
self.assertEqual(code, 1)
|
||||||
|
|
||||||
|
@patch("linux_updater.cli.check_root_privileges", return_value=False)
|
||||||
|
@patch("linux_updater.cli.DistroDetector.detect")
|
||||||
|
@patch("linux_updater.cli.get_manager")
|
||||||
|
def test_cli_dry_run_allowed_without_root(self, mock_get_manager, mock_detect, mock_root):
|
||||||
|
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, "simulated", "", 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 = 5 * 1024 * 1024
|
||||||
|
mock_stat.f_frsize = 1024
|
||||||
|
mock_statvfs.return_value = mock_stat
|
||||||
|
|
||||||
|
code = main(["update", "--dry-run", "-y"])
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
|
||||||
|
@patch("linux_updater.cli.InstanceLock.acquire", return_value=False)
|
||||||
|
@patch("linux_updater.cli.DistroDetector.detect")
|
||||||
|
def test_cli_instance_lock_blocks_concurrent_execution(self, mock_detect, mock_acquire):
|
||||||
|
mock_detect.return_value = DistroInfo(
|
||||||
|
family=DistroFamily.DEBIAN,
|
||||||
|
distro_id="ubuntu",
|
||||||
|
version_id="24.04",
|
||||||
|
pretty_name="Ubuntu 24.04",
|
||||||
|
)
|
||||||
|
code = main(["health"])
|
||||||
|
self.assertEqual(code, 1)
|
||||||
|
|
||||||
def test_config_file_and_cli_overrides(self):
|
def test_config_file_and_cli_overrides(self):
|
||||||
config_data = {
|
config_data = {
|
||||||
"thresholds": {"min_boot_mb": 500},
|
"thresholds": {"min_boot_mb": 500},
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from linux_updater.core.lock import InstanceLock
|
||||||
|
|
||||||
|
|
||||||
|
class TestInstanceLock(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.NamedTemporaryFile(delete=False)
|
||||||
|
self.tmp.close()
|
||||||
|
self.lock_path = Path(self.tmp.name)
|
||||||
|
if self.lock_path.exists():
|
||||||
|
self.lock_path.unlink()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
if self.lock_path.exists():
|
||||||
|
self.lock_path.unlink()
|
||||||
|
|
||||||
|
def test_acquire_and_release(self):
|
||||||
|
lock = InstanceLock(lock_path=self.lock_path)
|
||||||
|
self.assertTrue(lock.acquire())
|
||||||
|
self.assertTrue(self.lock_path.exists())
|
||||||
|
self.assertEqual(lock.get_holder_pid(), os.getpid())
|
||||||
|
|
||||||
|
lock.release()
|
||||||
|
self.assertFalse(lock.acquired)
|
||||||
|
self.assertFalse(self.lock_path.exists())
|
||||||
|
|
||||||
|
def test_second_instance_blocked(self):
|
||||||
|
lock1 = InstanceLock(lock_path=self.lock_path)
|
||||||
|
self.assertTrue(lock1.acquire())
|
||||||
|
|
||||||
|
lock2 = InstanceLock(lock_path=self.lock_path)
|
||||||
|
self.assertFalse(lock2.acquire())
|
||||||
|
self.assertEqual(lock2.get_holder_pid(), os.getpid())
|
||||||
|
|
||||||
|
lock1.release()
|
||||||
|
|
||||||
|
# Now lock2 can acquire
|
||||||
|
self.assertTrue(lock2.acquire())
|
||||||
|
lock2.release()
|
||||||
|
|
||||||
|
def test_context_manager(self):
|
||||||
|
with InstanceLock(lock_path=self.lock_path) as lock:
|
||||||
|
self.assertTrue(lock.acquired)
|
||||||
|
self.assertEqual(lock.get_holder_pid(), os.getpid())
|
||||||
|
|
||||||
|
# Second lock fails inside context manager
|
||||||
|
lock2 = InstanceLock(lock_path=self.lock_path)
|
||||||
|
self.assertFalse(lock2.acquire())
|
||||||
|
|
||||||
|
# Released after exit
|
||||||
|
self.assertFalse(self.lock_path.exists())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -131,6 +131,73 @@ systemd 255.5-1 -> 255.6-1 [extra]
|
|||||||
status = manager.is_reboot_required()
|
status = manager.is_reboot_required()
|
||||||
self.assertTrue(status.required)
|
self.assertTrue(status.required)
|
||||||
|
|
||||||
|
def test_dnf_fedora_auto_install_upgrade_plugin(self):
|
||||||
|
from linux_updater.models import DistroInfo
|
||||||
|
fedora_info = DistroInfo(
|
||||||
|
family=DistroFamily.RHEL,
|
||||||
|
distro_id="fedora",
|
||||||
|
version_id="40",
|
||||||
|
pretty_name="Fedora Linux 40",
|
||||||
|
)
|
||||||
|
manager = DnfManager(runner=self.mock_runner, distro_info=fedora_info)
|
||||||
|
|
||||||
|
# Simulation: 1st check fails, dnf install succeeds, 2nd check succeeds, then dnf system-upgrade download runs
|
||||||
|
self.mock_runner.run.side_effect = [
|
||||||
|
CommandResult(1, "", "unknown command", False), # system-upgrade --help fails
|
||||||
|
CommandResult(0, "Installed python3-dnf-plugins-core", "", True), # install plugin
|
||||||
|
CommandResult(0, "Usage: dnf system-upgrade", "", True), # system-upgrade --help succeeds
|
||||||
|
CommandResult(0, "Download complete", "", True), # dnf system-upgrade download
|
||||||
|
]
|
||||||
|
|
||||||
|
res = manager.release_upgrade(target_release="41", dry_run=False, non_interactive=True)
|
||||||
|
self.assertTrue(res.success)
|
||||||
|
# Verify python3-dnf-plugins-core install was triggered
|
||||||
|
called_cmds = [call[0][0] for call in self.mock_runner.run.call_args_list]
|
||||||
|
self.assertEqual(called_cmds[1], ["dnf", "install", "-y", "python3-dnf-plugins-core"])
|
||||||
|
self.assertIn("--releasever=41", called_cmds[3])
|
||||||
|
|
||||||
|
def test_dnf_almalinux_auto_install_elevate_and_leapp(self):
|
||||||
|
from linux_updater.models import DistroInfo
|
||||||
|
alma_info = DistroInfo(
|
||||||
|
family=DistroFamily.RHEL,
|
||||||
|
distro_id="almalinux",
|
||||||
|
version_id="9.4",
|
||||||
|
pretty_name="AlmaLinux 9.4 (Seafoam Ocelot)",
|
||||||
|
)
|
||||||
|
manager = DnfManager(runner=self.mock_runner, distro_info=alma_info)
|
||||||
|
|
||||||
|
# Simulation: leapp not in PATH, install elevate-release succeeds, install leapp-upgrade succeeds, leapp preupgrade runs
|
||||||
|
with patch("shutil.which") as mock_which:
|
||||||
|
mock_which.side_effect = lambda binary: "dnf" if binary == "dnf" else ("/usr/bin/leapp" if binary == "leapp" and len(self.mock_runner.run.call_args_list) >= 2 else None)
|
||||||
|
self.mock_runner.run.side_effect = [
|
||||||
|
CommandResult(0, "Installed elevate-release", "", True), # elevate-release rpm
|
||||||
|
CommandResult(0, "Installed leapp-upgrade leapp-data-almalinux", "", True), # leapp pkgs
|
||||||
|
CommandResult(0, "REPORT: all checks passed", "", True), # leapp preupgrade
|
||||||
|
]
|
||||||
|
|
||||||
|
res = manager.release_upgrade(dry_run=True)
|
||||||
|
self.assertTrue(res.success)
|
||||||
|
called_cmds = [call[0][0] for call in self.mock_runner.run.call_args_list]
|
||||||
|
self.assertIn("http://repo.almalinux.org/elevate/elevate-release-latest-el9.noarch.rpm", called_cmds[0])
|
||||||
|
self.assertEqual(called_cmds[1], ["dnf", "install", "-y", "leapp-upgrade", "leapp-data-almalinux"])
|
||||||
|
|
||||||
|
def test_dnf_almalinux_elevate_failure_provides_clear_english_troubleshooting(self):
|
||||||
|
from linux_updater.models import DistroInfo
|
||||||
|
alma_info = DistroInfo(
|
||||||
|
family=DistroFamily.RHEL,
|
||||||
|
distro_id="almalinux",
|
||||||
|
version_id="9.4",
|
||||||
|
pretty_name="AlmaLinux 9.4",
|
||||||
|
)
|
||||||
|
manager = DnfManager(runner=self.mock_runner, distro_info=alma_info)
|
||||||
|
|
||||||
|
with patch("shutil.which", return_value=None):
|
||||||
|
self.mock_runner.run.return_value = CommandResult(1, "", "Network is unreachable", False)
|
||||||
|
res = manager.release_upgrade(dry_run=False)
|
||||||
|
self.assertFalse(res.success)
|
||||||
|
self.assertIn("Failed to install ELevate repository package", res.stderr)
|
||||||
|
self.assertIn("Troubleshooting:", res.stderr)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
Reference in new issue
Block a user