feat: real-time streaming runner, --releasever alias, enriched help examples, and Fedora offline upgrade guidance
This commit is contained in:
1 parent
5940327b54
commit
b1c0f22ce7
8 files changed
+247
-37
No files matched your search
+98
-11
@@ -59,8 +59,22 @@ def create_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="linux-updater",
|
||||
description="Unified, safe multi-distribution Linux system updater and health inspector.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
parents=[common],
|
||||
epilog="""
|
||||
Examples:
|
||||
linux-updater health # Run pre-flight health diagnostic checks
|
||||
linux-updater check # Check for available updates without applying
|
||||
sudo linux-updater update # Update system packages interactively
|
||||
sudo linux-updater update -y # Non-interactive automated update
|
||||
sudo linux-updater update --packages curl # Selectively update specific package(s)
|
||||
sudo linux-updater release-upgrade -t 44 # Upgrade distribution release (Fedora/RHEL/Debian/Ubuntu)
|
||||
sudo linux-updater clean --all # Clean package cache and unused dependencies
|
||||
|
||||
Subcommand Help:
|
||||
Run 'linux-updater <subcommand> --help' for options specific to that subcommand.
|
||||
Example: 'linux-updater release-upgrade --help'
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-v", "--version",
|
||||
@@ -76,7 +90,15 @@ def create_parser() -> argparse.ArgumentParser:
|
||||
"update",
|
||||
parents=[common],
|
||||
help="Inspect health, auto-remediate safe issues, and apply package updates.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description="Inspect health, auto-remediate safe issues, and apply package updates.",
|
||||
epilog="""
|
||||
Examples:
|
||||
sudo linux-updater update
|
||||
sudo linux-updater update -y
|
||||
sudo linux-updater update --dry-run
|
||||
sudo linux-updater update --packages nginx redis
|
||||
""",
|
||||
)
|
||||
update_parser.add_argument(
|
||||
"--packages",
|
||||
@@ -90,7 +112,13 @@ def create_parser() -> argparse.ArgumentParser:
|
||||
"check",
|
||||
parents=[common],
|
||||
help="Check system health and list available updates without making modifications.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description="Check system health and list available updates without making modifications.",
|
||||
epilog="""
|
||||
Examples:
|
||||
linux-updater check
|
||||
linux-updater check --json
|
||||
""",
|
||||
)
|
||||
|
||||
# Subcommand: release-upgrade
|
||||
@@ -98,12 +126,26 @@ def create_parser() -> argparse.ArgumentParser:
|
||||
"release-upgrade",
|
||||
parents=[common],
|
||||
help="Perform a major distribution release upgrade with additional safety guardrails.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description="Perform a major distribution release upgrade with safety checks (e.g. Fedora, Ubuntu, AlmaLinux/Rocky).",
|
||||
epilog="""
|
||||
Target Release Specification:
|
||||
On Fedora and Red Hat-based systems, you must specify the target release version.
|
||||
Both '-t / --target-release' and '--releasever' are supported.
|
||||
|
||||
Examples:
|
||||
sudo linux-updater release-upgrade -t 44 # Fedora: upgrade to version 44
|
||||
sudo linux-updater release-upgrade --releasever 44 # Fedora: alias syntax
|
||||
sudo linux-updater release-upgrade -t 24.04 # Ubuntu/Debian: upgrade to 24.04
|
||||
sudo linux-updater release-upgrade -t 9 # AlmaLinux / Rocky: upgrade to EL 9
|
||||
sudo linux-updater release-upgrade -t 44 --dry-run # Simulate upgrade without applying
|
||||
""",
|
||||
)
|
||||
release_parser.add_argument(
|
||||
"-t", "--target-release",
|
||||
"-t", "--target-release", "--releasever",
|
||||
dest="target_release",
|
||||
type=str,
|
||||
help="Specify the target distribution version number/codename (e.g. 24.04, 41).",
|
||||
help="Specify target distribution version number/codename (e.g. 44 for Fedora, 24.04 for Ubuntu, 9 for AlmaLinux).",
|
||||
)
|
||||
|
||||
# Subcommand: clean
|
||||
@@ -111,7 +153,13 @@ def create_parser() -> argparse.ArgumentParser:
|
||||
"clean",
|
||||
parents=[common],
|
||||
help="Clean downloaded package cache and remove orphaned packages.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description="Clean downloaded package cache and remove orphaned packages.",
|
||||
epilog="""
|
||||
Examples:
|
||||
sudo linux-updater clean
|
||||
sudo linux-updater clean --all
|
||||
""",
|
||||
)
|
||||
clean_parser.add_argument(
|
||||
"--all",
|
||||
@@ -124,7 +172,14 @@ def create_parser() -> argparse.ArgumentParser:
|
||||
"health",
|
||||
parents=[common],
|
||||
help="Run only the pre-flight health diagnostic checks.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
description="Run only the pre-flight health diagnostic checks and print a formatted report.",
|
||||
epilog="""
|
||||
Examples:
|
||||
linux-updater health
|
||||
linux-updater health --json
|
||||
linux-updater health --no-remediation
|
||||
""",
|
||||
)
|
||||
|
||||
return parser
|
||||
@@ -247,6 +302,9 @@ def _run(
|
||||
json_output: bool,
|
||||
config_path: str,
|
||||
) -> int:
|
||||
if json_output:
|
||||
os.environ["LINUX_UPDATER_NO_STREAM"] = "1"
|
||||
|
||||
config = UpdaterConfig.load(Path(config_path) if config_path else None)
|
||||
if non_interactive:
|
||||
config.non_interactive = True
|
||||
@@ -430,6 +488,30 @@ def _run(
|
||||
# 6. Release-Upgrade Command
|
||||
if args.command == "release-upgrade":
|
||||
target = getattr(args, "target_release", None)
|
||||
|
||||
if distro.distro_id.lower() == "fedora" and not target:
|
||||
current_ver = distro.version_id.strip() if distro.version_id else ""
|
||||
suggested = f"-t {int(current_ver) + 1}" if current_ver.isdigit() else "-t <version>"
|
||||
if not json_output:
|
||||
print(
|
||||
f"\nError: Fedora major release upgrade requires specifying the target version.\n"
|
||||
f"Current system version: Fedora {distro.version_id or 'unknown'}\n\n"
|
||||
f"Usage:\n"
|
||||
f" sudo linux-updater release-upgrade -t <version>\n"
|
||||
f" sudo linux-updater release-upgrade --releasever <version>\n\n"
|
||||
f"Examples:\n"
|
||||
f" sudo linux-updater release-upgrade {suggested}\n"
|
||||
f" sudo linux-updater release-upgrade {suggested} --dry-run\n",
|
||||
file=sys.stderr,
|
||||
)
|
||||
else:
|
||||
print(json.dumps({
|
||||
"success": False,
|
||||
"error": "Target release version required for Fedora",
|
||||
"current_version": distro.version_id,
|
||||
}, indent=2))
|
||||
return 1
|
||||
|
||||
if not json_output:
|
||||
print("\n" + "=" * 65)
|
||||
print(" WARNING: MAJOR DISTRIBUTION RELEASE UPGRADE")
|
||||
@@ -470,9 +552,14 @@ def _run(
|
||||
"reboot_required": reboot.required,
|
||||
}, indent=2))
|
||||
else:
|
||||
print("\nRelease upgrade completed successfully!")
|
||||
if reboot.required:
|
||||
print("\n[!] ATTENTION: A system reboot is required to boot into the new release.")
|
||||
print("\nRelease upgrade preparation completed successfully!")
|
||||
if distro.distro_id.lower() == "fedora" and not dry_run:
|
||||
print("\n[!] ATTENTION: Fedora offline upgrade packages have been downloaded.")
|
||||
print(" To execute the upgrade and reboot into the new release, run:")
|
||||
print(" sudo dnf system-upgrade reboot")
|
||||
return 2
|
||||
elif reboot.required:
|
||||
print(f"\n[!] ATTENTION: A system reboot is required to boot into the new release ({reboot.reason}).")
|
||||
return 2
|
||||
|
||||
return 0
|
||||
|
||||
@@ -30,6 +30,7 @@ class CommandRunner:
|
||||
check: bool = False,
|
||||
env: Optional[Dict[str, str]] = None,
|
||||
timeout: Optional[int] = None,
|
||||
stream: bool = False,
|
||||
) -> CommandResult:
|
||||
full_env = os.environ.copy()
|
||||
if env:
|
||||
@@ -38,16 +39,48 @@ class CommandRunner:
|
||||
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)
|
||||
if stream and not os.environ.get("LINUX_UPDATER_NO_STREAM"):
|
||||
import selectors
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
env=full_env,
|
||||
)
|
||||
stdout_acc: List[str] = []
|
||||
stderr_acc: List[str] = []
|
||||
|
||||
sel = selectors.DefaultSelector()
|
||||
sel.register(proc.stdout, selectors.EVENT_READ, data=(sys.stdout, stdout_acc))
|
||||
sel.register(proc.stderr, selectors.EVENT_READ, data=(sys.stderr, stderr_acc))
|
||||
|
||||
while sel.get_map():
|
||||
events = sel.select(timeout=0.2)
|
||||
for key, _ in events:
|
||||
raw = os.read(key.fileobj.fileno(), 1024)
|
||||
if not raw:
|
||||
sel.unregister(key.fileobj)
|
||||
continue
|
||||
text = raw.decode("utf-8", errors="replace")
|
||||
key.data[0].write(text)
|
||||
key.data[0].flush()
|
||||
key.data[1].append(text)
|
||||
|
||||
proc.wait(timeout=timeout)
|
||||
stdout = "".join(stdout_acc)
|
||||
stderr = "".join(stderr_acc)
|
||||
success = (proc.returncode == 0)
|
||||
else:
|
||||
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}")
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ class AptManager(PackageManager):
|
||||
'-o', 'Dpkg::Options::=--force-confold',
|
||||
])
|
||||
|
||||
return self.runner.run(cmd, env=self._env(non_interactive))
|
||||
return self.runner.run(cmd, env=self._env(non_interactive), stream=not dry_run)
|
||||
|
||||
def release_upgrade(
|
||||
self,
|
||||
@@ -88,7 +88,7 @@ class AptManager(PackageManager):
|
||||
cmd.append("-d")
|
||||
if non_interactive:
|
||||
cmd.extend(["-f", "DistUpgradeViewNonInteractive"])
|
||||
return self.runner.run(cmd, env=self._env(non_interactive))
|
||||
return self.runner.run(cmd, env=self._env(non_interactive), stream=not dry_run)
|
||||
|
||||
# Standard Debian dist-upgrade
|
||||
cmd = ["apt-get", "dist-upgrade", "-y"]
|
||||
@@ -99,7 +99,7 @@ class AptManager(PackageManager):
|
||||
'-o', 'Dpkg::Options::=--force-confdef',
|
||||
'-o', 'Dpkg::Options::=--force-confold',
|
||||
])
|
||||
return self.runner.run(cmd, env=self._env(non_interactive))
|
||||
return self.runner.run(cmd, env=self._env(non_interactive), stream=not dry_run)
|
||||
|
||||
def clean_cache(self) -> CommandResult:
|
||||
return self.runner.run(["apt-get", "clean"])
|
||||
|
||||
@@ -68,7 +68,7 @@ class DnfManager(PackageManager):
|
||||
if packages:
|
||||
cmd.extend(packages)
|
||||
|
||||
res = self.runner.run(cmd)
|
||||
res = self.runner.run(cmd, stream=not dry_run)
|
||||
if dry_run and res.return_code == 1:
|
||||
combined = res.stdout + res.stderr
|
||||
if "Operation aborted" in combined or "Nothing to do" in combined:
|
||||
@@ -224,15 +224,30 @@ class DnfManager(PackageManager):
|
||||
)
|
||||
return CommandResult(return_code=1, stdout="", stderr=msg, success=False)
|
||||
|
||||
if not target_release:
|
||||
current_ver = distro.version_id.strip() if distro.version_id else ""
|
||||
suggested = f"-t {int(current_ver) + 1}" if current_ver.isdigit() else "-t <target_version>"
|
||||
err_msg = (
|
||||
"Fedora major release upgrade requires specifying the target release version.\n"
|
||||
f"Current system version: Fedora {distro.version_id or 'unknown'}\n\n"
|
||||
"Usage:\n"
|
||||
f" sudo linux-updater release-upgrade -t <version>\n"
|
||||
f" sudo linux-updater release-upgrade --releasever <version>\n\n"
|
||||
"Examples:\n"
|
||||
f" sudo linux-updater release-upgrade {suggested}\n"
|
||||
f" sudo linux-updater release-upgrade {suggested} --dry-run"
|
||||
)
|
||||
self.runner._log(f"[ERROR] {err_msg}")
|
||||
return CommandResult(return_code=1, stdout="", stderr=err_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}")
|
||||
cmd.append(f"--releasever={target_release}")
|
||||
|
||||
res = self.runner.run(cmd)
|
||||
res = self.runner.run(cmd, stream=not dry_run)
|
||||
if dry_run and res.return_code == 1:
|
||||
combined = res.stdout + res.stderr
|
||||
if "Operation aborted" in combined or "Nothing to do" in combined:
|
||||
@@ -278,7 +293,7 @@ class DnfManager(PackageManager):
|
||||
)
|
||||
else:
|
||||
self.runner._log("[UPGRADE] Starting Leapp in-place upgrade ('leapp upgrade')...")
|
||||
res = self.runner.run(["leapp", "upgrade"])
|
||||
res = self.runner.run(["leapp", "upgrade"], stream=True)
|
||||
if res.return_code != 0:
|
||||
err_msg = (
|
||||
f"Leapp in-place upgrade failed with exit code {res.return_code}.\n"
|
||||
@@ -325,7 +340,7 @@ class DnfManager(PackageManager):
|
||||
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"])
|
||||
return self.runner.run(["leapp", "upgrade"], stream=True)
|
||||
|
||||
# 4. Fallback for other DNF-based systems
|
||||
check = self.runner.run([self.binary, "system-upgrade", "--help"])
|
||||
@@ -352,7 +367,7 @@ class DnfManager(PackageManager):
|
||||
if target_release:
|
||||
cmd.append(f"--releasever={target_release}")
|
||||
|
||||
res = self.runner.run(cmd)
|
||||
res = self.runner.run(cmd, stream=not dry_run)
|
||||
if dry_run and res.return_code == 1:
|
||||
combined = res.stdout + res.stderr
|
||||
if "Operation aborted" in combined or "Nothing to do" in combined:
|
||||
@@ -373,6 +388,17 @@ class DnfManager(PackageManager):
|
||||
return self.runner.run(cmd)
|
||||
|
||||
def is_reboot_required(self) -> RebootStatus:
|
||||
# Check if dnf system-upgrade downloaded packages are staged
|
||||
system_upgrade_dir = Path("/var/lib/dnf/system-upgrade")
|
||||
if system_upgrade_dir.exists():
|
||||
try:
|
||||
if any(system_upgrade_dir.iterdir()):
|
||||
return RebootStatus(
|
||||
required=True,
|
||||
reason="System upgrade packages downloaded. Run: 'sudo dnf system-upgrade reboot' to perform the upgrade.",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# Check needs-restarting -r
|
||||
if shutil.which("needs-restarting"):
|
||||
res = self.runner.run(["needs-restarting", "-r"])
|
||||
|
||||
@@ -67,7 +67,7 @@ class PacmanManager(PackageManager):
|
||||
if dry_run:
|
||||
cmd.append("-p")
|
||||
|
||||
return self.runner.run(cmd)
|
||||
return self.runner.run(cmd, stream=not dry_run)
|
||||
|
||||
def release_upgrade(
|
||||
self,
|
||||
@@ -81,7 +81,7 @@ class PacmanManager(PackageManager):
|
||||
cmd.append("-p")
|
||||
elif non_interactive:
|
||||
cmd.append("--noconfirm")
|
||||
return self.runner.run(cmd)
|
||||
return self.runner.run(cmd, stream=not dry_run)
|
||||
|
||||
def clean_cache(self) -> CommandResult:
|
||||
return self.runner.run(["pacman", "-Sc", "--noconfirm"])
|
||||
|
||||
Reference in new issue
Block a user