15 Commits
Author SHA1 Message Date
soda64 8d4157b42d feat(ci): automatically link published packages to repository in Gitea
Build and Publish Release / Build Packages and Publish (push) Successful in 15s
2026-10-02 20:12:37 +02:00
soda64 57f49822bb feat(ci): use secrets.PACKAGES_GENERATION for Gitea Package Registry
Build and Publish Release / Build Packages and Publish (push) Successful in 15s
2026-10-02 20:06:16 +02:00
soda64 d5cf44cb57 fix(ci): purge stale release assets before attaching fresh binaries for idempotency
Build and Publish Release / Build Packages and Publish (push) Successful in 15s
2026-10-02 19:58:44 +02:00
soda64 63120e4793 fix(ci): restrict release asset attachments to binary packages only
Build and Publish Release / Build Packages and Publish (push) Successful in 14s
2026-10-02 19:57:43 +02:00
soda64 0bc914ac8a fix(ci): import build_packages via path in tests and enhance release workflow
Build and Publish Release / Build Packages and Publish (push) Successful in 16s
2026-10-02 19:51:40 +02:00
soda64 8921c2da13 feat(ci): add Gitea Actions release workflow and bump version to 1.3.0
Build and Publish Release / Build Packages and Publish (push) Failing after 52s
2026-10-02 19:48:20 +02:00
soda64 ab50abe0c0 chore(release): bump version to 1.2.0, update CLI help examples and documentation 2026-10-02 19:34:36 +02:00
soda64 74b0976d2f fix(dnf): add -y to dnf5 offline reboot and dnf system-upgrade reboot to prevent stdin hang 2026-10-02 19:16:19 +02:00
soda64 89cee406df chore(release): bump version to 1.1.0 2026-10-02 19:09:28 +02:00
soda64 426e8e5b6e feat(reboot): wire automated and interactive system reboot on update and release-upgrade 2026-10-02 18:39:41 +02:00
soda64 61875621ed fix(apt): always enforce noninteractive environment and dpkg conflict options for update and release-upgrade 2026-10-02 18:23:58 +02:00
soda64 1b109613bf fix(managers): ensure dnf and pacman always receive non-interactive flags after CLI prompt confirmation 2026-10-02 18:20:10 +02:00
soda64 b1c0f22ce7 feat: real-time streaming runner, --releasever alias, enriched help examples, and Fedora offline upgrade guidance 2026-10-02 18:18:05 +02:00
soda64 5940327b54 docs: update 00-status.md with Proxmox KVM crash testbed verification and Gitea remote 2026-10-02 17:46:17 +02:00
soda64 76c6a2fc5f fix(apt,packaging): add needrestart non-interactive env vars and enforce GNU tar format for dpkg compatibility 2026-10-02 17:45:47 +02:00
18 changed files with 816 additions and 95 deletions

No files matched your search

+148
View File
@@ -0,0 +1,148 @@
name: Build and Publish Release
on:
push:
tags:
- 'v*'
workflow_dispatch:
jobs:
release:
name: Build Packages and Publish
runs-on: fedora
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
- name: Verify Build Environment
run: |
echo "=== Runner System Info ==="
uname -a
python3 --version
if ! command -v rpmbuild &>/dev/null; then
echo "Installing rpm-build..."
sudo dnf install -y rpm-build
else
echo "rpmbuild is already available: $(which rpmbuild)"
fi
- name: Run Test Suite
run: |
echo "=== Running Unit Tests ==="
python3 -m unittest discover tests
- name: Build Distribution Packages
run: |
echo "=== Building Packages (.rpm, .deb, .tar.gz) ==="
python3 packaging/build_packages.py
echo "=== Built Artifacts ==="
ls -lh dist/*.tar.gz dist/*.deb 2>/dev/null || true
ls -lh dist/rpm/RPMS/*/*.rpm 2>/dev/null || true
- name: Publish to Gitea Package Registry
env:
PKG_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }}
run: |
echo "=== Publishing to Gitea Package Registry ==="
RPM_FILE=$(find dist/rpm/RPMS -name "*.rpm" 2>/dev/null | head -n 1)
DEB_FILE=$(ls dist/*.deb 2>/dev/null | head -n 1)
if [ -n "$RPM_FILE" ] && [ -f "$RPM_FILE" ]; then
echo "Uploading RPM: $RPM_FILE"
HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" -X PUT \
-u "${{ github.actor }}:${PKG_TOKEN}" \
--upload-file "$RPM_FILE" \
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/rpm/upload")
echo "RPM Registry HTTP status: $HTTP_CODE"
fi
if [ -n "$DEB_FILE" ] && [ -f "$DEB_FILE" ]; then
echo "Uploading DEB: $DEB_FILE"
HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" -X PUT \
-u "${{ github.actor }}:${PKG_TOKEN}" \
--upload-file "$DEB_FILE" \
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/debian/pool/stable/main/upload")
echo "Debian Registry HTTP status: $HTTP_CODE"
fi
# Link packages to this repository in Gitea
REPO_NAME=$(basename "${{ github.repository }}")
echo "Linking RPM package 'linux-updater' to repository ${REPO_NAME}..."
LINK_RPM=$(curl -k -s -w " (HTTP %{http_code})" -X POST \
-H "Authorization: token ${PKG_TOKEN}" \
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/rpm/linux-updater/-/link/${REPO_NAME}")
echo "RPM link result: $LINK_RPM"
echo "Linking Debian package 'linux-updater' to repository ${REPO_NAME}..."
LINK_DEB=$(curl -k -s -w " (HTTP %{http_code})" -X POST \
-H "Authorization: token ${PKG_TOKEN}" \
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/debian/linux-updater/-/link/${REPO_NAME}")
echo "Debian link result: $LINK_DEB"
- name: Attach Artifacts to Gitea Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SERVER_URL: ${{ github.server_url }}
REPO: ${{ github.repository }}
TAG_REF: ${{ github.ref_name }}
run: |
echo "=== Attaching Assets to Release ==="
# Determine tag name (default to package version if workflow_dispatch on branch)
TAG="${TAG_REF}"
if [[ "$TAG" == "main" || "$TAG" == "" ]]; then
VER=$(python3 -c "import linux_updater; print(linux_updater.__version__)")
TAG="v${VER}"
fi
echo "Target Release Tag: $TAG"
# 1. Fetch release ID or create release if missing
REL_JSON=$(curl -k -s -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/tags/${TAG}")
REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$REL_JSON" 2>/dev/null || true)
if [ -z "$REL_ID" ]; then
echo "Release $TAG does not exist yet. Creating release..."
CREATE_DATA=$(python3 -c "import sys, json; print(json.dumps({'tag_name': sys.argv[1], 'name': 'Release ' + sys.argv[1], 'body': 'Automated build and release for ' + sys.argv[1]}))" "$TAG")
CREATE_RESP=$(curl -k -s -X POST \
-H "Authorization: token ${GITHUB_TOKEN}" \
-H "Content-Type: application/json" \
-d "$CREATE_DATA" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases")
REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$CREATE_RESP" 2>/dev/null || true)
echo "Create release response: $CREATE_RESP"
fi
echo "Release ID: $REL_ID"
if [ -n "$REL_ID" ]; then
# Clean up any existing assets for this release (ensures idempotency on re-runs)
EXISTING_ASSETS=$(curl -k -s -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets" || true)
ASSET_IDS=$(python3 -c "import sys, json; print(' '.join(str(a['id']) for a in json.loads(sys.argv[1])))" "$EXISTING_ASSETS" 2>/dev/null || true)
for aid in $ASSET_IDS; do
echo "Removing previous asset ID $aid..."
curl -k -s -X DELETE -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets/${aid}" || true
done
# Target only user-facing binaries (exclude internal rpm SOURCES and SRPMS)
ASSET_FILES=(
$(ls dist/*.tar.gz 2>/dev/null || true)
$(ls dist/*.deb 2>/dev/null || true)
$(ls dist/rpm/RPMS/*/*.rpm 2>/dev/null || true)
)
for f in "${ASSET_FILES[@]}"; do
if [ -f "$f" ]; then
fname=$(basename "$f")
echo "Uploading asset $fname from $f..."
curl -k -s -X POST \
-H "Authorization: token ${GITHUB_TOKEN}" \
-F "attachment=@${f}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets?name=${fname}" || echo "Asset upload note: $?"
fi
done
echo "Artifacts successfully attached to release $TAG!"
else
echo "Could not obtain release ID, skipping asset attachment."
fi
+20 -13
View File
@@ -49,7 +49,7 @@
python3 packaging/build_packages.py python3 packaging/build_packages.py
# Install generated deb: # Install generated deb:
sudo dpkg -i dist/linux-updater_1.0.0_all.deb sudo dpkg -i dist/linux-updater_1.3.0_all.deb
``` ```
### Option 2: Native `.rpm` Package (RHEL / Fedora / AlmaLinux / Rocky) ### Option 2: Native `.rpm` Package (RHEL / Fedora / AlmaLinux / Rocky)
@@ -63,8 +63,8 @@ sudo rpm -Uvh dist/rpm/RPMS/noarch/linux-updater-*.noarch.rpm
### Option 3: Standalone Tarball (All Linux Distributions) ### Option 3: Standalone Tarball (All Linux Distributions)
```bash ```bash
tar -xzf dist/linux-updater-1.0.0.tar.gz tar -xzf dist/linux-updater-1.3.0.tar.gz
cd linux-updater-1.0.0 cd linux-updater-1.3.0
sudo ./install.sh sudo ./install.sh
``` ```
@@ -85,19 +85,25 @@ linux-updater check
# 4. Simulate a routine system update (dry run): # 4. Simulate a routine system update (dry run):
linux-updater update --dry-run linux-updater update --dry-run
# 5. Apply routine updates interactively (with confirmation prompt): # 5. Apply routine updates interactively (prompts for reboot if required):
sudo linux-updater update sudo linux-updater update
# 6. Apply updates non-interactively (e.g. from cron or Ansible): # 6. Apply updates non-interactively with automated reboot:
sudo linux-updater -y update sudo linux-updater update -y --reboot
# 7. Selectively update specific packages: # 7. Selectively update specific packages:
sudo linux-updater -y update --packages openssl nginx sudo linux-updater update -y --packages openssl nginx
# 8. Simulate major distribution release upgrade: # 8. Major distribution release upgrade (interactive confirmation & prompt for reboot):
sudo linux-updater release-upgrade --dry-run -t 41 sudo linux-updater release-upgrade -t 44
# 9. Clean package cache and remove orphaned packages: # 9. Major release upgrade with alias syntax and automated reboot:
sudo linux-updater release-upgrade --releasever 44 --reboot
# 10. Simulate major distribution release upgrade:
sudo linux-updater release-upgrade --dry-run -t 44
# 11. Clean package cache and remove orphaned packages:
sudo linux-updater clean --all sudo linux-updater clean --all
``` ```
@@ -119,7 +125,8 @@ Default settings can be customized in `/etc/linux-updater.json`:
"auto_remediate": true, "auto_remediate": true,
"non_interactive": false, "non_interactive": false,
"check_ac_power": true, "check_ac_power": true,
"clean_after_update": false "clean_after_update": false,
"auto_reboot": false
}, },
"logging": { "logging": {
"log_dir": "/var/log/linux-updater", "log_dir": "/var/log/linux-updater",
@@ -137,9 +144,9 @@ CLI flags always take precedence over configuration file values.
| Code | Status | Meaning | | Code | Status | Meaning |
|---|---|---| |---|---|---|
| `0` | **Success** | All operations completed cleanly; no reboot required. | | `0` | **Success** | All operations completed cleanly (or automated reboot successfully initiated). |
| `1` | **Error** | Pre-flight check failed and unrecovered, or package manager command returned non-zero. | | `1` | **Error** | Pre-flight check failed and unrecovered, or package manager command returned non-zero. |
| `2` | **Reboot Required** | Operation succeeded, but a system reboot is required (kernel or core library updated). | | `2` | **Reboot Required** | Operation succeeded, but a system reboot is required (and `--reboot` was not supplied). |
| `3` | **Aborted** | User cancelled operation at interactive confirmation prompt. | | `3` | **Aborted** | User cancelled operation at interactive confirmation prompt. |
--- ---
+3 -3
View File
@@ -149,6 +149,6 @@ python3 packaging/build_packages.py
``` ```
Generated artifacts: Generated artifacts:
- `dist/linux-updater-1.0.0.tar.gz`: Standalone distribution archive containing `install.sh`. - `dist/linux-updater-1.3.0.tar.gz`: Standalone distribution archive containing `install.sh`.
- `dist/linux-updater_1.0.0_all.deb`: Native Debian/Ubuntu binary package. - `dist/linux-updater_1.3.0_all.deb`: Native Debian/Ubuntu binary package.
- `dist/rpm/RPMS/noarch/linux-updater-1.0.0-1.*.noarch.rpm`: Native RPM package. - `dist/rpm/RPMS/noarch/linux-updater-1.3.0-1.*.noarch.rpm`: Native RPM package.
@@ -22,3 +22,5 @@
- 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. - 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. - 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. - 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.
- Physical VM Testbed: 100% verified across 5 full Proxmox VE KVM virtual machines (`alma-crash`, `arch-crash`, `debian-crash`, `fedora-crash`, `ubuntu-crash`). All targets completed package installation (.deb, .rpm, .tar.gz), pre-flight health checks, live system updates, physical KVM reboots, post-reboot health verification, and clean rollback to baseline snapshots.
- Gitea Repository: `https://gitea.wired.synology.me/soda64/linux-updater.git` on branch `main`.
+31 -9
View File
@@ -27,7 +27,7 @@ linux-updater health
**Example Output:** **Example Output:**
```text ```text
Linux System Updater v1.0.0 Linux System Updater v1.3.0
Detected System: Ubuntu 24.04.1 LTS (Family: debian) Detected System: Ubuntu 24.04.1 LTS (Family: debian)
Pre-flight Health Diagnostics: Pre-flight Health Diagnostics:
@@ -53,7 +53,7 @@ linux-updater check
**Example Output:** **Example Output:**
```text ```text
Linux System Updater v1.0.0 Linux System Updater v1.3.0
Detected System: Fedora Linux 40 (Family: rhel) Detected System: Fedora Linux 40 (Family: rhel)
Checking available updates... Checking available updates...
@@ -76,8 +76,13 @@ sudo linux-updater update
1. **Pre-flight Checks:** Checks `/boot`, `/var`, `/`, locks, RAM, and power. 1. **Pre-flight Checks:** Checks `/boot`, `/var`, `/`, locks, RAM, and power.
2. **Review:** Shows list of available updates. 2. **Review:** Shows list of available updates.
3. **Confirmation:** Prompts `Proceed with updates? [Y/n]: ` 3. **Confirmation:** Prompts `Proceed with updates? [Y/n]: `
4. **Execution:** Runs native package upgrade transaction. 4. **Execution:** Runs native package upgrade transaction with real-time download and installation streaming.
5. **Reboot Notice:** Warns if a kernel or core library update requires a reboot. 5. **Reboot Management:**
- **Interactive prompt:** If a kernel or core library update requires a reboot, `linux-updater` asks:
`A system reboot is required to apply changes. Reboot now? [y/N]: `
(Pressing Enter defaults safely to `No`).
- **Automated reboot:** Pass `--reboot` to automatically trigger reboot upon successful updates:
`sudo linux-updater update -y --reboot`
### Selective Package Updates (`--packages`) ### Selective Package Updates (`--packages`)
If you only want to upgrade specific software (e.g. security patches for OpenSSL and Nginx) without touching the rest of the operating system: If you only want to upgrade specific software (e.g. security patches for OpenSSL and Nginx) without touching the rest of the operating system:
@@ -97,16 +102,28 @@ linux-updater update --dry-run
## 3. Major Distribution Release Upgrade (`release-upgrade`) ## 3. Major Distribution Release Upgrade (`release-upgrade`)
A major distribution upgrade transitions your system from one release version to the next (e.g., Ubuntu 22.04 LTS to 24.04 LTS, Debian 12 to 13, Fedora 40 to 41, or AlmaLinux 8 to 9). A major distribution upgrade transitions your system from one release version to the next (e.g., Ubuntu 22.04 LTS to 24.04 LTS, Debian 12 to 13, Fedora 43 to 44, or AlmaLinux 8 to 9).
### Target Release Specification (`-t` / `--releasever`)
On Fedora and Red Hat-based systems, you must specify the target release version. Both `-t` and `--releasever` are supported:
```bash
# Fedora: upgrade to version 44:
sudo linux-updater release-upgrade -t 44
sudo linux-updater release-upgrade --releasever 44
# With automated offline transaction reboot:
sudo linux-updater release-upgrade -t 44 --reboot
```
Because major upgrades modify thousands of core system packages, `linux-updater` introduces strict safety gates: Because major upgrades modify thousands of core system packages, `linux-updater` introduces strict safety gates:
```bash ```bash
# Simulate upgrade first: # Simulate upgrade first:
linux-updater release-upgrade --dry-run -t 41 linux-updater release-upgrade --dry-run -t 44
# Execute real upgrade: # Execute real upgrade:
sudo linux-updater release-upgrade -t 41 sudo linux-updater release-upgrade -t 44
``` ```
**Safety Banner:** **Safety Banner:**
@@ -114,14 +131,19 @@ sudo linux-updater release-upgrade -t 41
================================================================= =================================================================
WARNING: MAJOR DISTRIBUTION RELEASE UPGRADE WARNING: MAJOR DISTRIBUTION RELEASE UPGRADE
================================================================= =================================================================
Target Release: 41 Target Release: 44
This operation performs a major upgrade of core system components. This operation performs a major upgrade of core system components.
Ensure you have a recent system backup or snapshot before proceeding. Ensure you have a recent system backup or snapshot before proceeding.
================================================================= =================================================================
Are you absolutely sure you want to proceed with upgrade to 41? [y/N]: Are you absolutely sure you want to proceed with upgrade to 44? [y/N]:
``` ```
**Fedora Offline Upgrades:**
On Fedora, major release upgrades are downloaded as an offline transaction. Once download finishes:
- With `--reboot`: Automatically executes `dnf5 -y offline reboot` (or `dnf -y system-upgrade reboot`).
- Interactively: Prompts `A system reboot is required to execute the offline upgrade transaction. Reboot now? [y/N]: `.
--- ---
## 4. System Cleanup (`clean`) ## 4. System Cleanup (`clean`)
+1 -1
View File
@@ -1,4 +1,4 @@
"""Linux System Updater - Multi-distribution system updater and health checker.""" """Linux System Updater - Multi-distribution system updater and health checker."""
__version__ = "1.0.0" __version__ = "1.3.0"
__author__ = "Test Factory" __author__ = "Test Factory"
+220 -20
View File
@@ -55,12 +55,35 @@ def create_parser() -> argparse.ArgumentParser:
default=argparse.SUPPRESS, default=argparse.SUPPRESS,
help="Output structured JSON results.", help="Output structured JSON results.",
) )
common.add_argument(
"--reboot",
dest="auto_reboot",
action="store_true",
default=argparse.SUPPRESS,
help="Automatically reboot the system after a major release upgrade (or if reboot is required).",
)
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
prog="linux-updater", prog="linux-updater",
description="Unified, safe multi-distribution Linux system updater and health inspector.", description="Unified, safe multi-distribution Linux system updater and health inspector.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter, formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[common], 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 -y --reboot # Automated update with automatic reboot
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 release-upgrade -t 44 --reboot # Major upgrade with automated reboot
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( parser.add_argument(
"-v", "--version", "-v", "--version",
@@ -76,7 +99,16 @@ def create_parser() -> argparse.ArgumentParser:
"update", "update",
parents=[common], parents=[common],
help="Inspect health, auto-remediate safe issues, and apply package updates.", 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 -y --reboot
sudo linux-updater update --dry-run
sudo linux-updater update --packages nginx redis
""",
) )
update_parser.add_argument( update_parser.add_argument(
"--packages", "--packages",
@@ -90,7 +122,13 @@ def create_parser() -> argparse.ArgumentParser:
"check", "check",
parents=[common], parents=[common],
help="Check system health and list available updates without making modifications.", 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 # Subcommand: release-upgrade
@@ -98,12 +136,27 @@ def create_parser() -> argparse.ArgumentParser:
"release-upgrade", "release-upgrade",
parents=[common], parents=[common],
help="Perform a major distribution release upgrade with additional safety guardrails.", 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 -t 44 --reboot # Fedora: upgrade with automated offline reboot
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( release_parser.add_argument(
"-t", "--target-release", "-t", "--target-release", "--releasever",
dest="target_release",
type=str, 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 # Subcommand: clean
@@ -111,7 +164,13 @@ def create_parser() -> argparse.ArgumentParser:
"clean", "clean",
parents=[common], parents=[common],
help="Clean downloaded package cache and remove orphaned packages.", 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( clean_parser.add_argument(
"--all", "--all",
@@ -124,7 +183,14 @@ def create_parser() -> argparse.ArgumentParser:
"health", "health",
parents=[common], parents=[common],
help="Run only the pre-flight health diagnostic checks.", 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 return parser
@@ -143,17 +209,49 @@ def format_health_report(report) -> None:
print(f"Overall Pre-flight Status: {status_text}\n") print(f"Overall Pre-flight Status: {status_text}\n")
def prompt_confirmation(prompt: str = "Do you want to proceed with updates? [Y/n]: ") -> bool: def prompt_confirmation(
prompt: str = "Do you want to proceed with updates? [Y/n]: ",
default_yes: bool = True,
) -> bool:
try: try:
choice = input(prompt).strip().lower() choice = input(prompt).strip().lower()
if not choice or choice in ("y", "yes", "tak", "t"): if not choice:
return True return default_yes
return False return choice in ("y", "yes", "tak", "t")
except (KeyboardInterrupt, EOFError): except (KeyboardInterrupt, EOFError):
print("\nAborted.") print("\nAborted.")
return False return False
def trigger_system_reboot(
distro_id: str,
is_release_upgrade: bool = False,
runner: Optional[CommandRunner] = None,
) -> bool:
import shutil
if runner is None:
runner = CommandRunner()
cmd_candidates: List[List[str]] = []
if is_release_upgrade and distro_id.lower() == "fedora":
cmd_candidates.append(["dnf5", "-y", "offline", "reboot"])
cmd_candidates.append(["dnf", "-y", "system-upgrade", "reboot"])
cmd_candidates.append(["systemctl", "reboot"])
cmd_candidates.append(["reboot"])
for cmd in cmd_candidates:
exe = shutil.which(cmd[0]) or cmd[0]
try:
res = runner.run([exe] + cmd[1:])
if res.success:
return True
except Exception:
continue
return False
def check_root_privileges() -> bool: def check_root_privileges() -> bool:
if hasattr(os, "geteuid"): if hasattr(os, "geteuid"):
return os.geteuid() == 0 return os.geteuid() == 0
@@ -247,11 +345,16 @@ def _run(
json_output: bool, json_output: bool,
config_path: str, config_path: str,
) -> int: ) -> int:
if json_output:
os.environ["LINUX_UPDATER_NO_STREAM"] = "1"
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
if no_remediation: if no_remediation:
config.auto_remediate = False config.auto_remediate = False
if getattr(args, "auto_reboot", False):
config.auto_reboot = True
# Resolve log path according to standards (/var/log/linux-updater/) # Resolve log path according to standards (/var/log/linux-updater/)
resolved_log: Optional[Path] = None resolved_log: Optional[Path] = None
@@ -279,7 +382,7 @@ def _run(
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 v{__version__} started (Distro: {distro.pretty_name}, PID: {os.getpid()}) ===")
manager = get_manager(distro.family, runner=runner, distro_info=distro) 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)
@@ -414,22 +517,75 @@ def _run(
reboot = manager.is_reboot_required() reboot = manager.is_reboot_required()
if json_output: if json_output:
triggered = False
if config.auto_reboot and not dry_run:
triggered = trigger_system_reboot(distro.distro_id, is_release_upgrade=False, runner=runner)
print(json.dumps({ print(json.dumps({
"success": True, "success": True,
"reboot_required": reboot.required, "reboot_required": reboot.required,
"reboot_reason": reboot.reason, "reboot_reason": reboot.reason,
"reboot_triggered": triggered,
}, indent=2)) }, indent=2))
else: else:
print("\nUpdates applied successfully!") print("\nUpdates applied successfully!")
if reboot.required: if config.auto_reboot:
if dry_run:
print("[dry-run] Would execute: sudo systemctl reboot")
return 0
reason_msg = f" ({reboot.reason})" if reboot.required else ""
print(f"\nRebooting system automatically (--reboot enabled){reason_msg}...")
ok = trigger_system_reboot(distro.distro_id, is_release_upgrade=False, runner=runner)
if not ok:
print("Error: Failed to initiate system reboot. Please reboot manually.", file=sys.stderr)
return 1
return 0
elif reboot.required:
print(f"\n[!] ATTENTION: A system reboot is required ({reboot.reason}).") print(f"\n[!] ATTENTION: A system reboot is required ({reboot.reason}).")
return 2 if not config.non_interactive and not dry_run:
prompt_msg = "A system reboot is required to apply changes. Reboot now? [y/N]: "
if prompt_confirmation(prompt=prompt_msg, default_yes=False):
print("Rebooting system...")
ok = trigger_system_reboot(distro.distro_id, is_release_upgrade=False, runner=runner)
if not ok:
print("Error: Failed to initiate system reboot. Please reboot manually.", file=sys.stderr)
return 1
return 0
else:
print("Reboot cancelled. Please reboot your system manually at your earliest convenience.")
return 2
else:
print("Please reboot the system using: sudo systemctl reboot")
return 2
return 0 return 0
# 6. Release-Upgrade Command # 6. Release-Upgrade Command
if args.command == "release-upgrade": if args.command == "release-upgrade":
target = getattr(args, "target_release", None) 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: if not json_output:
print("\n" + "=" * 65) print("\n" + "=" * 65)
print(" WARNING: MAJOR DISTRIBUTION RELEASE UPGRADE") print(" WARNING: MAJOR DISTRIBUTION RELEASE UPGRADE")
@@ -441,7 +597,7 @@ def _run(
if not config.non_interactive and not dry_run: if not config.non_interactive and not dry_run:
prompt_msg = f"Are you absolutely sure you want to proceed with upgrade to {target or 'new release'}? [y/N]: " prompt_msg = f"Are you absolutely sure you want to proceed with upgrade to {target or 'new release'}? [y/N]: "
if not prompt_confirmation(prompt=prompt_msg): if not prompt_confirmation(prompt=prompt_msg, default_yes=False):
if not json_output: if not json_output:
print("Release upgrade cancelled by user.") print("Release upgrade cancelled by user.")
return 3 return 3
@@ -462,17 +618,61 @@ def _run(
return 1 return 1
reboot = manager.is_reboot_required() reboot = manager.is_reboot_required()
is_fedora = distro.distro_id.lower() == "fedora"
reboot_reason = (
"execute the offline upgrade transaction"
if is_fedora
else "boot into the new release"
)
reboot_cmd = (
"sudo dnf system-upgrade reboot"
if is_fedora
else "sudo systemctl reboot"
)
if json_output: if json_output:
triggered = False
if config.auto_reboot and not dry_run:
triggered = trigger_system_reboot(distro.distro_id, is_release_upgrade=True, runner=runner)
print(json.dumps({ print(json.dumps({
"success": True, "success": True,
"release_upgrade": True, "release_upgrade": True,
"target_release": target, "target_release": target,
"reboot_required": reboot.required, "reboot_required": True if not dry_run else reboot.required,
"reboot_triggered": triggered,
}, indent=2)) }, indent=2))
else: else:
print("\nRelease upgrade completed successfully!") print("\nRelease upgrade preparation completed successfully!")
if reboot.required: if dry_run:
print("\n[!] ATTENTION: A system reboot is required to boot into the new release.") if config.auto_reboot:
print(f"[dry-run] Would execute: {reboot_cmd}")
else:
print(f"[dry-run] A system reboot would be required ({reboot_cmd}).")
return 0
if config.auto_reboot:
print(f"\nRebooting system automatically to {reboot_reason} (--reboot enabled)...")
ok = trigger_system_reboot(distro.distro_id, is_release_upgrade=True, runner=runner)
if not ok:
print("Error: Failed to initiate system reboot. Please reboot manually.", file=sys.stderr)
return 1
return 0
elif not config.non_interactive:
prompt_msg = f"\nA system reboot is required to {reboot_reason}.\nReboot now? [y/N]: "
if prompt_confirmation(prompt=prompt_msg, default_yes=False):
print("Rebooting system...")
ok = trigger_system_reboot(distro.distro_id, is_release_upgrade=True, runner=runner)
if not ok:
print("Error: Failed to initiate system reboot. Please reboot manually.", file=sys.stderr)
return 1
return 0
else:
print(f"\n[!] ATTENTION: A system reboot is required.")
print(f" To complete the upgrade, run: {reboot_cmd}")
return 2
else:
print(f"\n[!] ATTENTION: A system reboot is required to {reboot_reason}.")
print(f" To execute the upgrade, run: {reboot_cmd}")
return 2 return 2
return 0 return 0
+4
View File
@@ -14,6 +14,7 @@ class UpdaterConfig:
non_interactive: bool = False, non_interactive: bool = False,
check_ac_power: bool = True, check_ac_power: bool = True,
clean_after_update: bool = False, clean_after_update: bool = False,
auto_reboot: bool = False,
log_dir: Optional[str] = "/var/log/linux-updater", log_dir: Optional[str] = "/var/log/linux-updater",
log_file: Optional[str] = None, log_file: Optional[str] = None,
verbose: bool = False, verbose: bool = False,
@@ -26,6 +27,7 @@ class UpdaterConfig:
self.non_interactive = non_interactive self.non_interactive = non_interactive
self.check_ac_power = check_ac_power self.check_ac_power = check_ac_power
self.clean_after_update = clean_after_update self.clean_after_update = clean_after_update
self.auto_reboot = auto_reboot
self.log_dir = log_dir self.log_dir = log_dir
self.log_file = log_file self.log_file = log_file
self.verbose = verbose self.verbose = verbose
@@ -57,6 +59,7 @@ class UpdaterConfig:
non_interactive=behavior.get("non_interactive", False), non_interactive=behavior.get("non_interactive", False),
check_ac_power=behavior.get("check_ac_power", True), check_ac_power=behavior.get("check_ac_power", True),
clean_after_update=behavior.get("clean_after_update", False), clean_after_update=behavior.get("clean_after_update", False),
auto_reboot=behavior.get("auto_reboot", False),
log_dir=logging.get("log_dir", "/var/log/linux-updater"), log_dir=logging.get("log_dir", "/var/log/linux-updater"),
log_file=logging.get("log_file", None), log_file=logging.get("log_file", None),
verbose=logging.get("verbose", False), verbose=logging.get("verbose", False),
@@ -75,6 +78,7 @@ class UpdaterConfig:
"non_interactive": self.non_interactive, "non_interactive": self.non_interactive,
"check_ac_power": self.check_ac_power, "check_ac_power": self.check_ac_power,
"clean_after_update": self.clean_after_update, "clean_after_update": self.clean_after_update,
"auto_reboot": self.auto_reboot,
}, },
"logging": { "logging": {
"log_dir": self.log_dir, "log_dir": self.log_dir,
+43 -10
View File
@@ -30,6 +30,7 @@ class CommandRunner:
check: bool = False, check: bool = False,
env: Optional[Dict[str, str]] = None, env: Optional[Dict[str, str]] = None,
timeout: Optional[int] = None, timeout: Optional[int] = None,
stream: bool = False,
) -> CommandResult: ) -> CommandResult:
full_env = os.environ.copy() full_env = os.environ.copy()
if env: if env:
@@ -38,16 +39,48 @@ class CommandRunner:
self._log(f"Executing: {' '.join(cmd)}") self._log(f"Executing: {' '.join(cmd)}")
try: try:
proc = subprocess.run( if stream and not os.environ.get("LINUX_UPDATER_NO_STREAM"):
cmd, import selectors
stdout=subprocess.PIPE, proc = subprocess.Popen(
stderr=subprocess.PIPE, cmd,
env=full_env, stdout=subprocess.PIPE,
timeout=timeout, stderr=subprocess.PIPE,
) env=full_env,
stdout = proc.stdout.decode("utf-8", errors="replace") )
stderr = proc.stderr.decode("utf-8", errors="replace") stdout_acc: List[str] = []
success = (proc.returncode == 0) 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}") self._log(f"Exit code: {proc.returncode}")
+8 -7
View File
@@ -19,6 +19,8 @@ class AptManager(PackageManager):
env: Dict[str, str] = {} env: Dict[str, str] = {}
if non_interactive: if non_interactive:
env["DEBIAN_FRONTEND"] = "noninteractive" env["DEBIAN_FRONTEND"] = "noninteractive"
env["NEEDRESTART_MODE"] = "a"
env["NEEDRESTART_SUSPEND"] = "1"
return env return env
def refresh_repositories(self) -> CommandResult: def refresh_repositories(self) -> CommandResult:
@@ -63,14 +65,13 @@ class AptManager(PackageManager):
if dry_run: if dry_run:
cmd.append("-s") cmd.append("-s")
else:
if non_interactive:
cmd.extend([ cmd.extend([
'-o', 'Dpkg::Options::=--force-confdef', '-o', 'Dpkg::Options::=--force-confdef',
'-o', 'Dpkg::Options::=--force-confold', '-o', 'Dpkg::Options::=--force-confold',
]) ])
return self.runner.run(cmd, env=self._env(non_interactive)) return self.runner.run(cmd, env=self._env(True), stream=not dry_run)
def release_upgrade( def release_upgrade(
self, self,
@@ -84,20 +85,20 @@ class AptManager(PackageManager):
cmd = ["do-release-upgrade"] cmd = ["do-release-upgrade"]
if dry_run: if dry_run:
cmd.append("-d") cmd.append("-d")
if non_interactive: else:
cmd.extend(["-f", "DistUpgradeViewNonInteractive"]) cmd.extend(["-f", "DistUpgradeViewNonInteractive"])
return self.runner.run(cmd, env=self._env(non_interactive)) return self.runner.run(cmd, env=self._env(True), stream=not dry_run)
# Standard Debian dist-upgrade # Standard Debian dist-upgrade
cmd = ["apt-get", "dist-upgrade", "-y"] cmd = ["apt-get", "dist-upgrade", "-y"]
if dry_run: if dry_run:
cmd.append("-s") cmd.append("-s")
if non_interactive: else:
cmd.extend([ cmd.extend([
'-o', 'Dpkg::Options::=--force-confdef', '-o', 'Dpkg::Options::=--force-confdef',
'-o', 'Dpkg::Options::=--force-confold', '-o', 'Dpkg::Options::=--force-confold',
]) ])
return self.runner.run(cmd, env=self._env(non_interactive)) return self.runner.run(cmd, env=self._env(True), stream=not dry_run)
def clean_cache(self) -> CommandResult: def clean_cache(self) -> CommandResult:
return self.runner.run(["apt-get", "clean"]) return self.runner.run(["apt-get", "clean"])
+36 -10
View File
@@ -62,13 +62,13 @@ class DnfManager(PackageManager):
cmd = [self.binary, "upgrade"] cmd = [self.binary, "upgrade"]
if dry_run: if dry_run:
cmd.append("--assumeno") cmd.append("--assumeno")
elif non_interactive: else:
cmd.append("-y") cmd.append("-y")
if packages: if packages:
cmd.extend(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: if dry_run and res.return_code == 1:
combined = res.stdout + res.stderr combined = res.stdout + res.stderr
if "Operation aborted" in combined or "Nothing to do" in combined: 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) 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"] cmd = [self.binary, "system-upgrade", "download"]
if dry_run: if dry_run:
cmd.append("--assumeno") cmd.append("--assumeno")
elif non_interactive: else:
cmd.append("-y") 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: if dry_run and res.return_code == 1:
combined = res.stdout + res.stderr combined = res.stdout + res.stderr
if "Operation aborted" in combined or "Nothing to do" in combined: if "Operation aborted" in combined or "Nothing to do" in combined:
@@ -278,7 +293,7 @@ class DnfManager(PackageManager):
) )
else: else:
self.runner._log("[UPGRADE] Starting Leapp in-place upgrade ('leapp upgrade')...") 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: if res.return_code != 0:
err_msg = ( err_msg = (
f"Leapp in-place upgrade failed with exit code {res.return_code}.\n" 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"]) 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) return CommandResult(return_code=0, stdout=f"[DRY-RUN] Leapp pre-upgrade simulation:\n{res.stdout}", stderr="", success=True)
else: else:
return self.runner.run(["leapp", "upgrade"]) return self.runner.run(["leapp", "upgrade"], stream=True)
# 4. Fallback for other DNF-based systems # 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"])
@@ -347,12 +362,12 @@ class DnfManager(PackageManager):
cmd = [self.binary, "system-upgrade", "download"] cmd = [self.binary, "system-upgrade", "download"]
if dry_run: if dry_run:
cmd.append("--assumeno") cmd.append("--assumeno")
elif non_interactive: else:
cmd.append("-y") cmd.append("-y")
if target_release: 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: if dry_run and res.return_code == 1:
combined = res.stdout + res.stderr combined = res.stdout + res.stderr
if "Operation aborted" in combined or "Nothing to do" in combined: if "Operation aborted" in combined or "Nothing to do" in combined:
@@ -373,6 +388,17 @@ class DnfManager(PackageManager):
return self.runner.run(cmd) return self.runner.run(cmd)
def is_reboot_required(self) -> RebootStatus: def is_reboot_required(self) -> RebootStatus:
# Check if dnf / dnf5 system-upgrade downloaded packages are staged
for upgrade_path in [Path("/var/lib/dnf/system-upgrade"), Path("/var/lib/dnf5/offline")]:
if upgrade_path.exists():
try:
if any(upgrade_path.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 # Check needs-restarting -r
if shutil.which("needs-restarting"): if shutil.which("needs-restarting"):
res = self.runner.run(["needs-restarting", "-r"]) res = self.runner.run(["needs-restarting", "-r"])
+7 -7
View File
@@ -55,19 +55,19 @@ class PacmanManager(PackageManager):
) -> CommandResult: ) -> CommandResult:
if packages: if packages:
cmd = ["pacman", "-S"] cmd = ["pacman", "-S"]
if non_interactive:
cmd.append("--noconfirm")
if dry_run: if dry_run:
cmd.append("-p") cmd.append("-p")
else:
cmd.append("--noconfirm")
cmd.extend(packages) cmd.extend(packages)
else: else:
cmd = ["pacman", "-Su"] cmd = ["pacman", "-Su"]
if non_interactive:
cmd.append("--noconfirm")
if dry_run: if dry_run:
cmd.append("-p") cmd.append("-p")
else:
cmd.append("--noconfirm")
return self.runner.run(cmd) return self.runner.run(cmd, stream=not dry_run)
def release_upgrade( def release_upgrade(
self, self,
@@ -79,9 +79,9 @@ class PacmanManager(PackageManager):
cmd = ["pacman", "-Syu"] cmd = ["pacman", "-Syu"]
if dry_run: if dry_run:
cmd.append("-p") cmd.append("-p")
elif non_interactive: else:
cmd.append("--noconfirm") cmd.append("--noconfirm")
return self.runner.run(cmd) return self.runner.run(cmd, stream=not dry_run)
def clean_cache(self) -> CommandResult: def clean_cache(self) -> CommandResult:
return self.runner.run(["pacman", "-Sc", "--noconfirm"]) return self.runner.run(["pacman", "-Sc", "--noconfirm"])
+7 -3
View File
@@ -1,4 +1,4 @@
.TH LINUX-UPDATER 8 "October 2026" "linux-updater 1.0.0" "System Administration Utilities" .TH LINUX-UPDATER 8 "October 2026" "linux-updater 1.3.0" "System Administration Utilities"
.SH NAME .SH NAME
linux-updater \- unified, safe multi-distribution Linux system update utility linux-updater \- unified, safe multi-distribution Linux system update utility
@@ -7,6 +7,7 @@ linux-updater \- unified, safe multi-distribution Linux system update utility
[\fB\-y\fR|\fB\-\-yes\fR] [\fB\-y\fR|\fB\-\-yes\fR]
[\fB\-c\fR \fICONFIG\fR] [\fB\-c\fR \fICONFIG\fR]
[\fB\-\-dry\-run\fR] [\fB\-\-dry\-run\fR]
[\fB\-\-reboot\fR]
[\fB\-\-no\-remediation\fR] [\fB\-\-no\-remediation\fR]
[\fB\-\-skip\-preflight\fR] [\fB\-\-skip\-preflight\fR]
[\fB\-v\fR|\fB\-\-verbose\fR] [\fB\-v\fR|\fB\-\-verbose\fR]
@@ -39,8 +40,8 @@ Runs pre-flight diagnostics, cleans caches if needed, checks for available updat
.B check .B check
Non-destructively inspects pre-flight health diagnostics and lists all pending package upgrades without modifying system state. Non-destructively inspects pre-flight health diagnostics and lists all pending package upgrades without modifying system state.
.TP .TP
.B release\-upgrade \fR[\fB\-t \fITARGET\fR|\fB\-\-target\-release \fITARGET\fR] .B release\-upgrade \fR[\fB\-t \fITARGET\fR|\fB\-\-target\-release \fITARGET\fR|\fB\-\-releasever \fITARGET\fR]
Executes a major OS distribution upgrade (e.g. Debian 12 to 13, Ubuntu 22.04 to 24.04, Fedora 40 to 41, or RHEL/AlmaLinux leapp upgrade). Requires explicit user confirmation unless \fB\-y\fR is passed. Executes a major OS distribution upgrade (e.g. Debian 12 to 13, Ubuntu 22.04 to 24.04, Fedora 43 to 44, or RHEL/AlmaLinux leapp upgrade). On Fedora, the target release version is mandatory via \fB\-t\fR or \fB\-\-releasever\fR. Requires explicit user confirmation unless \fB\-y\fR is passed.
.TP .TP
.B clean \fR[\fB\-\-all\fR] .B clean \fR[\fB\-\-all\fR]
Cleans the local package cache. When \fB\-\-all\fR is given, also removes unused orphaned dependencies. Cleans the local package cache. When \fB\-\-all\fR is given, also removes unused orphaned dependencies.
@@ -59,6 +60,9 @@ Specifies the path to an alternative JSON configuration file (default: \fI/etc/l
.B \-\-dry\-run .B \-\-dry\-run
Simulates update operations without altering package states on disk. Simulates update operations without altering package states on disk.
.TP .TP
.B \-\-reboot
Automatically reboots the system after a major release upgrade or routine update (if a reboot is required). On Fedora release upgrades, automatically executes offline transaction reboot (\fBdnf5 \-y offline reboot\fR). In interactive mode when this option is omitted, the user is prompted to confirm immediate reboot.
.TP
.B \-\-no\-remediation .B \-\-no\-remediation
Disables automated remediation actions (such as clearing package caches or unlinking stale locks). Disables automated remediation actions (such as clearing package caches or unlinking stale locks).
.TP .TP
+15 -7
View File
@@ -67,7 +67,7 @@ class PackageBuilder:
self, self,
source_root: Optional[Path] = None, source_root: Optional[Path] = None,
output_dir: Optional[Path] = None, output_dir: Optional[Path] = None,
version: str = "1.0.0", version: str = "1.3.0",
) -> None: ) -> None:
self.source_root = source_root or Path(__file__).resolve().parent.parent self.source_root = source_root or Path(__file__).resolve().parent.parent
self.output_dir = output_dir or (self.source_root / "dist") self.output_dir = output_dir or (self.source_root / "dist")
@@ -160,16 +160,24 @@ class PackageBuilder:
shutil.copy2(str(control_dir / "control"), str(debian_meta / "control")) shutil.copy2(str(control_dir / "control"), str(debian_meta / "control"))
subprocess.run(["dpkg-deb", "-b", str(pkg_tree), str(deb_output_path)], check=True) subprocess.run(["dpkg-deb", "-b", str(pkg_tree), str(deb_output_path)], check=True)
else: else:
# Pure Python build # Pure Python build with strict GNU_FORMAT (dpkg rejects PAX 'x' headers)
def reset_tarinfo(tarinfo):
tarinfo.uid = 0
tarinfo.gid = 0
tarinfo.uname = "root"
tarinfo.gname = "root"
tarinfo.pax_headers = {}
return tarinfo
ctrl_tar = root / "control.tar.gz" ctrl_tar = root / "control.tar.gz"
data_tar = root / "data.tar.gz" data_tar = root / "data.tar.gz"
with tarfile.open(str(ctrl_tar), "w:gz") as tar: with tarfile.open(str(ctrl_tar), "w:gz", format=tarfile.GNU_FORMAT) as tar:
tar.add(str(control_dir / "control"), arcname="./control") tar.add(str(control_dir / "control"), arcname="./control", filter=reset_tarinfo)
with tarfile.open(str(data_tar), "w:gz") as tar: with tarfile.open(str(data_tar), "w:gz", format=tarfile.GNU_FORMAT) as tar:
for item in data_dir.iterdir(): for item in sorted(data_dir.iterdir()):
tar.add(str(item), arcname=f"./{item.name}") tar.add(str(item), arcname=f"./{item.name}", filter=reset_tarinfo)
create_native_deb(ctrl_tar, data_tar, deb_output_path) create_native_deb(ctrl_tar, data_tar, deb_output_path)
+16 -1
View File
@@ -1,5 +1,5 @@
Name: linux-updater Name: linux-updater
Version: 1.0.0 Version: 1.3.0
Release: 1%{?dist} Release: 1%{?dist}
Summary: Unified, safe multi-distribution Linux system updater Summary: Unified, safe multi-distribution Linux system updater
@@ -46,5 +46,20 @@ fi
%{_mandir}/man8/linux-updater.8* %{_mandir}/man8/linux-updater.8*
%changelog %changelog
* Fri Oct 02 2026 Test Factory <admin@localhost> - 1.3.0-1
- Add Gitea Actions automated CI/CD pipeline for building RPM, DEB, and tarball packages.
- Automated publication to Gitea Package Registry and Gitea Release Assets.
* Fri Oct 02 2026 Test Factory <admin@localhost> - 1.2.0-1
- Fix dnf5 offline reboot and dnf system-upgrade reboot automatic invocation with -y.
- Enhanced cross-distribution unattended update and reboot workflows.
* Fri Oct 02 2026 Test Factory <admin@localhost> - 1.1.0-1
- Real-time download/transaction streaming without stdin hangs.
- Automated and interactive reboot support (--reboot and [y/N] prompt).
- Fedora offline upgrade integration (dnf5 offline / dnf system-upgrade reboot).
- Add --releasever alias for target release version specification.
- Extended pre-flight health diagnostics and test matrix (58 passing tests).
* Fri Oct 02 2026 Test Factory <admin@localhost> - 1.0.0-1 * Fri Oct 02 2026 Test Factory <admin@localhost> - 1.0.0-1
- Initial release with Debian, RHEL, and Arch support. - Initial release with Debian, RHEL, and Arch support.
+230 -1
View File
@@ -122,13 +122,61 @@ class TestCLIIntegration(unittest.TestCase):
mock_statvfs.return_value = mock_stat mock_statvfs.return_value = mock_stat
code = main(["-y", "release-upgrade", "--target-release", "41"]) code = main(["-y", "release-upgrade", "--target-release", "41"])
self.assertEqual(code, 0) self.assertEqual(code, 2)
mock_manager.release_upgrade.assert_called_once_with( mock_manager.release_upgrade.assert_called_once_with(
target_release="41", target_release="41",
dry_run=False, dry_run=False,
non_interactive=True, non_interactive=True,
) )
@patch("linux_updater.cli.check_root_privileges", return_value=True)
@patch("linux_updater.cli.DistroDetector.detect")
@patch("linux_updater.cli.get_manager")
def test_cli_release_upgrade_accepts_releasever_alias(self, mock_get_manager, mock_detect, mock_root):
mock_detect.return_value = DistroInfo(
family=DistroFamily.RHEL,
distro_id="fedora",
version_id="43",
pretty_name="Fedora 43",
)
mock_manager = MagicMock()
mock_manager.get_lock_files.return_value = []
mock_manager.release_upgrade.return_value = CommandResult(0, "success", "", 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 = 10 * 1024 * 1024
mock_stat.f_frsize = 1024
mock_statvfs.return_value = mock_stat
code = main(["-y", "release-upgrade", "--releasever", "44"])
self.assertEqual(code, 2)
mock_manager.release_upgrade.assert_called_once_with(
target_release="44",
dry_run=False,
non_interactive=True,
)
@patch("linux_updater.cli.check_root_privileges", return_value=True)
@patch("linux_updater.cli.DistroDetector.detect")
def test_cli_release_upgrade_fedora_requires_target(self, mock_detect, mock_root):
mock_detect.return_value = DistroInfo(
family=DistroFamily.RHEL,
distro_id="fedora",
version_id="43",
pretty_name="Fedora 43",
)
with patch("os.statvfs") as mock_statvfs:
mock_stat = MagicMock()
mock_stat.f_bavail = 10 * 1024 * 1024
mock_stat.f_frsize = 1024
mock_statvfs.return_value = mock_stat
code = main(["-y", "release-upgrade"])
self.assertEqual(code, 1)
@patch("linux_updater.cli.check_root_privileges", return_value=False) @patch("linux_updater.cli.check_root_privileges", return_value=False)
@patch("linux_updater.cli.DistroDetector.detect") @patch("linux_updater.cli.DistroDetector.detect")
def test_cli_root_required_for_mutating_commands(self, mock_detect, mock_root): def test_cli_root_required_for_mutating_commands(self, mock_detect, mock_root):
@@ -235,6 +283,187 @@ class TestCLIIntegration(unittest.TestCase):
self.assertIn("Linux System Updater", content) self.assertIn("Linux System Updater", content)
self.assertIn("started", content) self.assertIn("started", content)
@patch("linux_updater.cli.check_root_privileges", return_value=True)
@patch("linux_updater.cli.DistroDetector.detect")
@patch("linux_updater.cli.get_manager")
@patch("linux_updater.cli.trigger_system_reboot", return_value=True)
def test_cli_release_upgrade_auto_reboot_triggers_reboot(
self, mock_reboot, mock_get_manager, mock_detect, mock_root
):
mock_detect.return_value = DistroInfo(
family=DistroFamily.RHEL,
distro_id="fedora",
version_id="43",
pretty_name="Fedora 43",
)
mock_manager = MagicMock()
mock_manager.get_lock_files.return_value = []
mock_manager.release_upgrade.return_value = CommandResult(0, "success", "", True)
mock_manager.is_reboot_required.return_value = RebootStatus(required=True)
mock_get_manager.return_value = mock_manager
with patch("os.statvfs") as mock_statvfs:
mock_stat = MagicMock()
mock_stat.f_bavail = 10 * 1024 * 1024
mock_stat.f_frsize = 1024
mock_statvfs.return_value = mock_stat
code = main(["-y", "--reboot", "release-upgrade", "-t", "44"])
self.assertEqual(code, 0)
mock_reboot.assert_called_once_with("fedora", is_release_upgrade=True, runner=unittest.mock.ANY)
@patch("linux_updater.cli.check_root_privileges", return_value=True)
@patch("linux_updater.cli.DistroDetector.detect")
@patch("linux_updater.cli.get_manager")
@patch("linux_updater.cli.trigger_system_reboot", return_value=True)
def test_cli_release_upgrade_interactive_prompt_yes_triggers_reboot(
self, mock_reboot, mock_get_manager, mock_detect, mock_root
):
mock_detect.return_value = DistroInfo(
family=DistroFamily.RHEL,
distro_id="fedora",
version_id="43",
pretty_name="Fedora 43",
)
mock_manager = MagicMock()
mock_manager.get_lock_files.return_value = []
mock_manager.release_upgrade.return_value = CommandResult(0, "success", "", True)
mock_manager.is_reboot_required.return_value = RebootStatus(required=True)
mock_get_manager.return_value = mock_manager
with patch("os.statvfs") as mock_statvfs:
mock_stat = MagicMock()
mock_stat.f_bavail = 10 * 1024 * 1024
mock_stat.f_frsize = 1024
mock_statvfs.return_value = mock_stat
# User answers 'y' to upgrade warning and 'y' to reboot prompt
with patch("linux_updater.cli.prompt_confirmation", side_effect=[True, True]):
code = main(["release-upgrade", "-t", "44"])
self.assertEqual(code, 0)
mock_reboot.assert_called_once_with("fedora", is_release_upgrade=True, runner=unittest.mock.ANY)
@patch("linux_updater.cli.check_root_privileges", return_value=True)
@patch("linux_updater.cli.DistroDetector.detect")
@patch("linux_updater.cli.get_manager")
@patch("linux_updater.cli.trigger_system_reboot")
def test_cli_release_upgrade_interactive_prompt_no_skips_reboot(
self, mock_reboot, mock_get_manager, mock_detect, mock_root
):
mock_detect.return_value = DistroInfo(
family=DistroFamily.RHEL,
distro_id="fedora",
version_id="43",
pretty_name="Fedora 43",
)
mock_manager = MagicMock()
mock_manager.get_lock_files.return_value = []
mock_manager.release_upgrade.return_value = CommandResult(0, "success", "", True)
mock_manager.is_reboot_required.return_value = RebootStatus(required=True)
mock_get_manager.return_value = mock_manager
with patch("os.statvfs") as mock_statvfs:
mock_stat = MagicMock()
mock_stat.f_bavail = 10 * 1024 * 1024
mock_stat.f_frsize = 1024
mock_statvfs.return_value = mock_stat
# User answers 'y' to upgrade warning and 'n' to reboot prompt
with patch("linux_updater.cli.prompt_confirmation", side_effect=[True, False]):
code = main(["release-upgrade", "-t", "44"])
self.assertEqual(code, 2)
mock_reboot.assert_not_called()
@patch("linux_updater.cli.check_root_privileges", return_value=True)
@patch("linux_updater.cli.DistroDetector.detect")
@patch("linux_updater.cli.get_manager")
@patch("linux_updater.cli.trigger_system_reboot", return_value=True)
def test_cli_update_auto_reboot_triggers_reboot(
self, mock_reboot, 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, "success", "", True)
mock_manager.is_reboot_required.return_value = RebootStatus(required=True, reason="kernel upgraded")
mock_get_manager.return_value = mock_manager
with patch("os.statvfs") as mock_statvfs:
mock_stat = MagicMock()
mock_stat.f_bavail = 10 * 1024 * 1024
mock_stat.f_frsize = 1024
mock_statvfs.return_value = mock_stat
code = main(["-y", "--reboot", "update"])
self.assertEqual(code, 0)
mock_reboot.assert_called_once_with("ubuntu", is_release_upgrade=False, runner=unittest.mock.ANY)
@patch("linux_updater.cli.check_root_privileges", return_value=True)
@patch("linux_updater.cli.DistroDetector.detect")
@patch("linux_updater.cli.get_manager")
@patch("linux_updater.cli.trigger_system_reboot", return_value=True)
def test_cli_update_auto_reboot_triggers_even_when_reboot_not_explicitly_required(
self, mock_reboot, 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, "success", "", 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 = 10 * 1024 * 1024
mock_stat.f_frsize = 1024
mock_statvfs.return_value = mock_stat
code = main(["-y", "--reboot", "update"])
self.assertEqual(code, 0)
mock_reboot.assert_called_once_with("ubuntu", is_release_upgrade=False, runner=unittest.mock.ANY)
def test_trigger_system_reboot_fedora_release_upgrade(self):
from linux_updater.cli import trigger_system_reboot
mock_runner = MagicMock()
mock_runner.run.return_value = CommandResult(0, "reboot scheduled", "", True)
with patch("shutil.which", side_effect=lambda cmd: f"/usr/bin/{cmd}"):
res = trigger_system_reboot("fedora", is_release_upgrade=True, runner=mock_runner)
self.assertTrue(res)
# Must try dnf5 offline reboot first if available
mock_runner.run.assert_called_once_with(["/usr/bin/dnf5", "-y", "offline", "reboot"])
def test_trigger_system_reboot_general_systemctl(self):
from linux_updater.cli import trigger_system_reboot
mock_runner = MagicMock()
mock_runner.run.return_value = CommandResult(0, "rebooting", "", True)
with patch("shutil.which", side_effect=lambda cmd: f"/bin/{cmd}"):
res = trigger_system_reboot("ubuntu", is_release_upgrade=False, runner=mock_runner)
self.assertTrue(res)
mock_runner.run.assert_called_once_with(["/bin/systemctl", "reboot"])
def test_trigger_system_reboot_all_fail(self):
from linux_updater.cli import trigger_system_reboot
mock_runner = MagicMock()
mock_runner.run.return_value = CommandResult(1, "", "permission denied", False)
with patch("shutil.which", return_value=None):
res = trigger_system_reboot("arch", is_release_upgrade=False, runner=mock_runner)
self.assertFalse(res)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+17 -1
View File
@@ -2,7 +2,7 @@ import unittest
from pathlib import Path from pathlib import Path
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from linux_updater.models import CommandResult, DistroFamily, RebootStatus from linux_updater.models import CommandResult, DistroFamily, DistroInfo, RebootStatus
from linux_updater.core.runner import CommandRunner from linux_updater.core.runner import CommandRunner
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
@@ -156,6 +156,22 @@ systemd 255.5-1 -> 255.6-1 [extra]
self.assertEqual(called_cmds[1], ["dnf", "install", "-y", "python3-dnf-plugins-core"]) self.assertEqual(called_cmds[1], ["dnf", "install", "-y", "python3-dnf-plugins-core"])
self.assertIn("--releasever=41", called_cmds[3]) self.assertIn("--releasever=41", called_cmds[3])
def test_dnf_fedora_release_upgrade_missing_target_fails_cleanly(self):
fedora_info = DistroInfo(
family=DistroFamily.RHEL,
distro_id="fedora",
version_id="43",
pretty_name="Fedora 43",
)
manager = DnfManager(runner=self.mock_runner, distro_info=fedora_info)
self.mock_runner.run.return_value = CommandResult(0, "Usage: dnf system-upgrade", "", True)
res = manager.release_upgrade(target_release=None)
self.assertFalse(res.success)
self.assertIn("Fedora major release upgrade requires specifying the target release version", res.stderr)
self.assertIn("-t 44", res.stderr)
def test_dnf_almalinux_auto_install_elevate_and_leapp(self): def test_dnf_almalinux_auto_install_elevate_and_leapp(self):
from linux_updater.models import DistroInfo from linux_updater.models import DistroInfo
alma_info = DistroInfo( alma_info = DistroInfo(
+8 -2
View File
@@ -4,15 +4,21 @@ import tempfile
import unittest import unittest
from pathlib import Path from pathlib import Path
from packaging.build_packages import PackageBuilder import importlib.util
_root_dir = Path(__file__).resolve().parent.parent
_pkg_script = _root_dir / "packaging" / "build_packages.py"
_spec = importlib.util.spec_from_file_location("build_packages", str(_pkg_script))
_module = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_module)
PackageBuilder = _module.PackageBuilder
class TestPackaging(unittest.TestCase): class TestPackaging(unittest.TestCase):
def setUp(self): def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory() self.temp_dir = tempfile.TemporaryDirectory()
self.out_dir = Path(self.temp_dir.name) self.out_dir = Path(self.temp_dir.name)
self.root_dir = Path(__file__).resolve().parent.parent self.root_dir = Path(__file__).resolve().parent.parent
self.builder = PackageBuilder(source_root=self.root_dir, output_dir=self.out_dir, version="1.0.0") self.builder = PackageBuilder(source_root=self.root_dir, output_dir=self.out_dir, version="1.3.0")
def tearDown(self): def tearDown(self):
self.temp_dir.cleanup() self.temp_dir.cleanup()