Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97c6ac2ab9 | ||
|
|
8bec4ed932 | ||
|
|
8d4157b42d | ||
|
|
57f49822bb | ||
|
|
d5cf44cb57 | ||
|
|
63120e4793 | ||
|
|
0bc914ac8a | ||
|
|
8921c2da13 | ||
|
|
ab50abe0c0 | ||
|
|
74b0976d2f | ||
|
|
89cee406df | ||
|
|
426e8e5b6e | ||
|
|
61875621ed | ||
|
|
1b109613bf | ||
|
|
b1c0f22ce7 | ||
|
|
5940327b54 | ||
|
|
76c6a2fc5f |
No files matched your search
@@ -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
|
||||||
@@ -14,19 +14,27 @@
|
|||||||
- **Pre-flight Health Diagnostics:**
|
- **Pre-flight Health Diagnostics:**
|
||||||
- **Disk Space:** Enforces safety thresholds on `/boot` (>= 250 MB), `/var` (>= 1024 MB), and `/` (>= 1024 MB).
|
- **Disk Space:** Enforces safety thresholds on `/boot` (>= 250 MB), `/var` (>= 1024 MB), and `/` (>= 1024 MB).
|
||||||
- **Process Locks:** Detects active package manager locks (via PID checking and non-blocking `fcntl.flock` advisory locks).
|
- **Process Locks:** Detects active package manager locks (via PID checking and non-blocking `fcntl.flock` advisory locks).
|
||||||
|
- **Package Database Consistency:** Verifies package manager integrity (`dpkg --audit`, `dnf check`, `pacman` lock integrity) and auto-remediates interrupted transactions (`dpkg --configure -a`, `apt-get install -f`, `dnf clean all`).
|
||||||
- **Memory & OOM Pressure:** Inspects `/proc/meminfo` to warn or halt if available RAM is dangerously low (< 300 MB).
|
- **Memory & OOM Pressure:** Inspects `/proc/meminfo` to warn or halt if available RAM is dangerously low (< 300 MB).
|
||||||
- **AC Power Protection:** Inspects `/sys/class/power_supply` on laptops to prevent updates on battery power.
|
- **AC Power Protection:** Inspects `/sys/class/power_supply` on laptops to prevent updates on battery power.
|
||||||
- **Reboot Detection:** Detects pending reboots from previous kernel/library updates.
|
- **Reboot Detection:** Detects pending reboots from previous kernel/library updates.
|
||||||
- **Safe Automated Remediation:** Safely cleans package cache when `/var` is low and clears stale locks if the holder process is confirmed dead.
|
- **Safe Automated Remediation:** Safely cleans package cache when `/var` is low, clears stale locks if the holder process is dead, and repairs interrupted package transactions.
|
||||||
|
- **Advanced Update Capabilities:**
|
||||||
|
- **Security-only Updates:** `--security` flag restricts updates strictly to CVE/security advisories on RHEL, Fedora, CentOS, Rocky, AlmaLinux, Debian, and Ubuntu.
|
||||||
|
- **Package Filtering:** `--exclude` skips specified packages or glob patterns (e.g., `--exclude "kernel*" "nginx"`).
|
||||||
|
- **Selective Packages:** `--packages` selectively targets specific packages for updates.
|
||||||
|
- **Flatpak Integration:** `--flatpak` triggers Flatpak application updates after OS packages.
|
||||||
|
- **Shell Tab Autocompletion:** Native, zero-latency Bash and Zsh completions with instant flag/subcommand suggestions (`linux-updater completion bash|zsh`).
|
||||||
- **Two Update Tiers:**
|
- **Two Update Tiers:**
|
||||||
- `update`: Routine updates (with optional selective package targeting via `--packages`).
|
- `update`: Routine updates with security filters, exclusions, and Flatpak support.
|
||||||
- `release-upgrade`: Major distribution upgrades (e.g. Debian 12 $\rightarrow$ 13, Ubuntu 22.04 $\rightarrow$ 24.04, Fedora 40 $\rightarrow$ 41, or RHEL/AlmaLinux `leapp` upgrades) with safety warnings.
|
- `release-upgrade`: Major distribution upgrades (e.g. Debian 12 $\rightarrow$ 13, Ubuntu 22.04 $\rightarrow$ 24.04, Fedora 40 $\rightarrow$ 41, or RHEL/AlmaLinux `leapp` upgrades) with safety warnings.
|
||||||
- **Standard Linux FHS Logging:**
|
- **Standard Linux FHS Logging & Logrotate:**
|
||||||
- Logs transactions to `/var/log/linux-updater/linux-updater-<YYYYMMDD>-<HHMMSS>.log`.
|
- Logs transactions to `/var/log/linux-updater/linux-updater-<YYYYMMDD>-<HHMMSS>.log`.
|
||||||
- Atomically maintains `/var/log/linux-updater/latest.log` symlink pointing to the most recent execution.
|
- Atomically maintains `/var/log/linux-updater/latest.log` symlink.
|
||||||
|
- Ships with `/etc/logrotate.d/linux-updater` (weekly rotation, 4 copies, compressed).
|
||||||
- **Automation Ready:**
|
- **Automation Ready:**
|
||||||
- Structured `--json` output for Zabbix, Wazuh, Prometheus node exporters, or custom agents.
|
- Structured `--json` output for Zabbix, Wazuh, Prometheus node exporters, or custom agents.
|
||||||
- Non-interactive mode (`-y` / `--non-interactive`) for cron and systemd timers.
|
- Non-interactive mode (`-y` / `--non-interactive`) for cron, Ansible, and central management.
|
||||||
- Deterministic exit codes.
|
- Deterministic exit codes.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -49,7 +57,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_2.0.0_all.deb
|
||||||
```
|
```
|
||||||
|
|
||||||
### Option 2: Native `.rpm` Package (RHEL / Fedora / AlmaLinux / Rocky)
|
### Option 2: Native `.rpm` Package (RHEL / Fedora / AlmaLinux / Rocky)
|
||||||
@@ -63,8 +71,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-2.0.0.tar.gz
|
||||||
cd linux-updater-1.0.0
|
cd linux-updater-2.0.0
|
||||||
sudo ./install.sh
|
sudo ./install.sh
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -85,20 +93,35 @@ 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. Apply security-only updates non-interactively:
|
||||||
sudo linux-updater -y update --packages openssl nginx
|
sudo linux-updater update -y --security
|
||||||
|
|
||||||
# 8. Simulate major distribution release upgrade:
|
# 8. Exclude specific packages or glob patterns:
|
||||||
sudo linux-updater release-upgrade --dry-run -t 41
|
sudo linux-updater update -y --exclude "kernel*" "nginx"
|
||||||
|
|
||||||
# 9. Clean package cache and remove orphaned packages:
|
# 9. Update system packages and Flatpak apps:
|
||||||
|
sudo linux-updater update -y --flatpak
|
||||||
|
|
||||||
|
# 10. Selectively update specific packages:
|
||||||
|
sudo linux-updater update -y --packages openssl nginx
|
||||||
|
|
||||||
|
# 11. Major distribution release upgrade (interactive confirmation & prompt for reboot):
|
||||||
|
sudo linux-updater release-upgrade -t 44
|
||||||
|
|
||||||
|
# 12. Major release upgrade with alias syntax and automated reboot:
|
||||||
|
sudo linux-updater release-upgrade --releasever 44 --reboot
|
||||||
|
|
||||||
|
# 13. Clean package cache and remove orphaned packages:
|
||||||
sudo linux-updater clean --all
|
sudo linux-updater clean --all
|
||||||
|
|
||||||
|
# 14. Enable Bash or Zsh tab autocompletion:
|
||||||
|
eval "$(linux-updater completion bash)"
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -119,7 +142,11 @@ 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,
|
||||||
|
"exclude_packages": [],
|
||||||
|
"security_only": false,
|
||||||
|
"update_flatpak": false
|
||||||
},
|
},
|
||||||
"logging": {
|
"logging": {
|
||||||
"log_dir": "/var/log/linux-updater",
|
"log_dir": "/var/log/linux-updater",
|
||||||
@@ -137,9 +164,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. |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -163,9 +190,9 @@ All packaging builds and integration tests run inside clean Podman containers:
|
|||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
- [User Guide](docs/user-guide.md): Comprehensive instructions for operators and desktop users.
|
- [User Guide](docs/user-guide.md): Comprehensive instructions for operators and desktop users (selective updates, filtering, security-only, Flatpak, shell completion).
|
||||||
- [Administrator Guide](docs/admin-guide.md): Automation, cron/systemd configuration, monitoring, and logrotate setup.
|
- [Administrator Guide](docs/admin-guide.md): Automation, cron/systemd configuration, monitoring, logrotate setup, and Gitea Package Registry integration (RPM & Debian).
|
||||||
- [Developer Guide](docs/developer-guide.md): Internal architecture, adding new package managers, and test development.
|
- [Developer Guide](docs/developer-guide.md): Internal architecture, adding package managers, test development, packaging, and Gitea Actions CI/CD release workflow.
|
||||||
- [MAN Page (Section 8)](man/linux-updater.8): System administration manual (`man 8 linux-updater`).
|
- [MAN Page (Section 8)](man/linux-updater.8): System administration manual (`man 8 linux-updater`).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# bash completion for linux-updater
|
||||||
|
|
||||||
|
_linux_updater() {
|
||||||
|
local cur prev words cword
|
||||||
|
_init_completion -n : || return
|
||||||
|
|
||||||
|
local commands="update check release-upgrade clean health completion"
|
||||||
|
local common_opts="-c --config -y --yes --non-interactive --dry-run --no-remediation --skip-preflight --json --reboot -h --help"
|
||||||
|
|
||||||
|
# Find the current subcommand (if any)
|
||||||
|
local cmd=""
|
||||||
|
local i
|
||||||
|
for (( i=1; i < cword; i++ )); do
|
||||||
|
case "${words[i]}" in
|
||||||
|
update|check|release-upgrade|clean|health|completion)
|
||||||
|
cmd="${words[i]}"
|
||||||
|
break
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Handle completion for previous option
|
||||||
|
case "$prev" in
|
||||||
|
-c|--config)
|
||||||
|
_filedir json
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
-t|--target-release|--releasever)
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
--packages|--exclude)
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# If no subcommand has been entered yet
|
||||||
|
if [[ -z "$cmd" ]]; then
|
||||||
|
if [[ "$cur" == -* ]]; then
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts -v --version" -- "$cur") )
|
||||||
|
return 0
|
||||||
|
else
|
||||||
|
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Subcommand-specific completions
|
||||||
|
case "$cmd" in
|
||||||
|
update)
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts --packages --exclude --security --flatpak" -- "$cur") )
|
||||||
|
;;
|
||||||
|
check)
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts" -- "$cur") )
|
||||||
|
;;
|
||||||
|
release-upgrade)
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts -t --target-release --releasever" -- "$cur") )
|
||||||
|
;;
|
||||||
|
clean)
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts --all" -- "$cur") )
|
||||||
|
;;
|
||||||
|
health)
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts" -- "$cur") )
|
||||||
|
;;
|
||||||
|
completion)
|
||||||
|
COMPREPLY=( $(compgen -W "bash zsh" -- "$cur") )
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
complete -F _linux_updater linux-updater
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
#compdef linux-updater
|
||||||
|
|
||||||
|
_linux_updater() {
|
||||||
|
local context state state_descr line
|
||||||
|
typeset -A opt_args
|
||||||
|
|
||||||
|
local -a common_args
|
||||||
|
common_args=(
|
||||||
|
'(-c --config)'{-c,--config}'[Path to JSON configuration file]:config file:_files -g "*.json"'
|
||||||
|
'(-y --yes --non-interactive)'{-y,--yes,--non-interactive}'[Run without interactive confirmation prompts]'
|
||||||
|
'--dry-run[Simulate execution without modifying system state]'
|
||||||
|
'--no-remediation[Disable automatic remediation of failed health checks]'
|
||||||
|
'--skip-preflight[Skip pre-flight health checks]'
|
||||||
|
'--json[Output structured JSON results]'
|
||||||
|
'--reboot[Automatically reboot the system after upgrade or if required]'
|
||||||
|
'(-h --help)'{-h,--help}'[Show help message and exit]'
|
||||||
|
)
|
||||||
|
|
||||||
|
_arguments -C \
|
||||||
|
'(-v --version)'{-v,--version}'[Show program version and exit]' \
|
||||||
|
$common_args \
|
||||||
|
'1: :->command' \
|
||||||
|
'*:: :->args'
|
||||||
|
|
||||||
|
case $state in
|
||||||
|
command)
|
||||||
|
local -a commands
|
||||||
|
commands=(
|
||||||
|
'update:Inspect health, auto-remediate safe issues, and apply package updates'
|
||||||
|
'check:Check system health and list available updates without making modifications'
|
||||||
|
'release-upgrade:Perform a major distribution release upgrade with safety checks'
|
||||||
|
'clean:Clean downloaded package cache and remove orphaned packages'
|
||||||
|
'health:Run only the pre-flight health diagnostic checks'
|
||||||
|
'completion:Generate shell autocompletion script (bash or zsh)'
|
||||||
|
)
|
||||||
|
_describe -t commands 'subcommand' commands
|
||||||
|
;;
|
||||||
|
args)
|
||||||
|
case $line[1] in
|
||||||
|
update)
|
||||||
|
_arguments \
|
||||||
|
$common_args \
|
||||||
|
'--packages[Selectively update specified package(s)]:package: ' \
|
||||||
|
'--exclude[Exclude package(s) or glob patterns from update]:exclude: ' \
|
||||||
|
'--security[Apply only security-related updates]' \
|
||||||
|
'--flatpak[Update Flatpak packages if available]'
|
||||||
|
;;
|
||||||
|
check)
|
||||||
|
_arguments \
|
||||||
|
$common_args
|
||||||
|
;;
|
||||||
|
release-upgrade)
|
||||||
|
_arguments \
|
||||||
|
$common_args \
|
||||||
|
'(-t --target-release --releasever)'{-t,--target-release,--releasever}'[Specify target distribution version number/codename]:target release: '
|
||||||
|
;;
|
||||||
|
clean)
|
||||||
|
_arguments \
|
||||||
|
$common_args \
|
||||||
|
'--all[Clean both package cache and autoremove unused dependencies]'
|
||||||
|
;;
|
||||||
|
health)
|
||||||
|
_arguments \
|
||||||
|
$common_args
|
||||||
|
;;
|
||||||
|
completion)
|
||||||
|
local -a shells
|
||||||
|
shells=('bash:Generate Bash completion script' 'zsh:Generate Zsh completion script')
|
||||||
|
_describe -t shells 'shell' shells
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
_linux_updater "$@"
|
||||||
+89
-5
@@ -71,7 +71,11 @@ The default configuration file `/etc/linux-updater.json` governs health check th
|
|||||||
"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,
|
||||||
|
"exclude_packages": [],
|
||||||
|
"security_only": false,
|
||||||
|
"update_flatpak": false
|
||||||
},
|
},
|
||||||
"logging": {
|
"logging": {
|
||||||
"log_dir": "/var/log/linux-updater",
|
"log_dir": "/var/log/linux-updater",
|
||||||
@@ -88,10 +92,14 @@ The default configuration file `/etc/linux-updater.json` governs health check th
|
|||||||
- `min_ram_mb`: Available RAM threshold in `/proc/meminfo`. Protects against OOM killer crashing package scripts. Defaults to 300 MB.
|
- `min_ram_mb`: Available RAM threshold in `/proc/meminfo`. Protects against OOM killer crashing package scripts. Defaults to 300 MB.
|
||||||
|
|
||||||
### Behavior Parameters
|
### Behavior Parameters
|
||||||
- `auto_remediate`: When `true`, automatically clears package cache if `/var` is low and unlinks stale locks if the holder PID is dead.
|
- `auto_remediate`: When `true`, automatically clears package cache if `/var` is low, unlinks stale locks if the holder PID is dead, and repairs interrupted package transactions (`dpkg --configure -a`, `apt-get install -f`, `dnf clean all`).
|
||||||
- `non_interactive`: Default non-interactive state. (Overridden by CLI `-y`).
|
- `non_interactive`: Default non-interactive state. (Overridden by CLI `-y`).
|
||||||
- `check_ac_power`: Inspects `/sys/class/power_supply` and warns/halts if running on battery power.
|
- `check_ac_power`: Inspects `/sys/class/power_supply` and warns/halts if running on battery power.
|
||||||
- `clean_after_update`: If `true`, runs `autoremove` automatically after successful updates.
|
- `clean_after_update`: If `true`, runs `autoremove` automatically after successful updates.
|
||||||
|
- `auto_reboot`: When `true`, automatically triggers reboot if a kernel or core system component was upgraded.
|
||||||
|
- `exclude_packages`: List of package names or glob patterns to skip during update transactions.
|
||||||
|
- `security_only`: When `true`, restricts all update operations strictly to security patches.
|
||||||
|
- `update_flatpak`: When `true`, executes `flatpak update -y` after OS packages update if flatpak is installed.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -136,6 +144,13 @@ linux-updater health --json
|
|||||||
"message": "No pending system reboot detected.",
|
"message": "No pending system reboot detected.",
|
||||||
"can_remediate": false,
|
"can_remediate": false,
|
||||||
"remediation_id": null
|
"remediation_id": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "package_db",
|
||||||
|
"status": "PASS",
|
||||||
|
"message": "Package database is consistent.",
|
||||||
|
"can_remediate": false,
|
||||||
|
"remediation_id": null
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"remediations_performed": []
|
"remediations_performed": []
|
||||||
@@ -174,19 +189,88 @@ esac
|
|||||||
|
|
||||||
## 4. Log Management & Logrotate
|
## 4. Log Management & Logrotate
|
||||||
|
|
||||||
By default, logs are written to `/var/log/linux-updater/` with:
|
By default, logs are written to `/var/log/linux-updater/` conforming to Linux FHS:
|
||||||
- Timestamped files: `linux-updater-YYYYMMDD-HHMMSS.log`
|
- Timestamped files: `linux-updater-YYYYMMDD-HHMMSS.log`
|
||||||
- Symlink to latest run: `/var/log/linux-updater/latest.log`
|
- Symlink to latest run: `/var/log/linux-updater/latest.log`
|
||||||
|
|
||||||
To manage historical logs and compress older runs, configure `/etc/logrotate.d/linux-updater`:
|
The package installation automatically provides `/etc/logrotate.d/linux-updater`:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
/var/log/linux-updater/*.log {
|
/var/log/linux-updater/*.log {
|
||||||
weekly
|
weekly
|
||||||
rotate 12
|
rotate 4
|
||||||
compress
|
compress
|
||||||
missingok
|
missingok
|
||||||
notifempty
|
notifempty
|
||||||
create 0640 root root
|
create 0640 root root
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Shell Tab Autocompletion Deployment
|
||||||
|
|
||||||
|
For administrative workstations and fleet servers, shell completions can be automatically deployed:
|
||||||
|
|
||||||
|
- **System-wide Bash:** `/usr/share/bash-completion/completions/linux-updater`
|
||||||
|
- **System-wide Zsh:** `/usr/share/zsh/site-functions/_linux-updater` (or `/usr/share/zsh/vendor-completions/_linux-updater`)
|
||||||
|
|
||||||
|
Both files are automatically placed when installing via `.deb`, `.rpm`, or `install.sh`. Administrators can also dynamically output and evaluate them:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Bash:
|
||||||
|
linux-updater completion bash > /etc/bash_completion.d/linux-updater
|
||||||
|
|
||||||
|
# Zsh:
|
||||||
|
linux-updater completion zsh > /usr/local/share/zsh/site-functions/_linux-updater
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Gitea Package Registry Integration (Homelab Repositories)
|
||||||
|
|
||||||
|
In enterprise homelab environments with centralized package management, `linux-updater` can be distributed and continuously updated across all fleet hosts via the self-hosted Gitea Package Registry at `https://gitea.wired.synology.me`.
|
||||||
|
|
||||||
|
### A. RHEL / AlmaLinux / Rocky / Fedora Clients (`DNF` / `YUM`)
|
||||||
|
|
||||||
|
Create the repository configuration file `/etc/yum.repos.d/gitea-wired.repo`:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[gitea-wired]
|
||||||
|
name=Wired LAB Gitea RPM Repository
|
||||||
|
baseurl=https://gitea.wired.synology.me/api/packages/soda64/rpm
|
||||||
|
enabled=1
|
||||||
|
gpgcheck=0
|
||||||
|
```
|
||||||
|
|
||||||
|
Verify and install via DNF:
|
||||||
|
```bash
|
||||||
|
sudo dnf clean all
|
||||||
|
sudo dnf makecache
|
||||||
|
sudo dnf install -y linux-updater
|
||||||
|
```
|
||||||
|
|
||||||
|
### B. Debian / Ubuntu Clients (`APT`)
|
||||||
|
|
||||||
|
Import the repository signing key and configure the APT source list `/etc/apt/sources.list.d/gitea-wired.list`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Import Gitea Debian repository key:
|
||||||
|
curl -fsSL https://gitea.wired.synology.me/api/packages/soda64/debian/repository.key | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/gitea-wired.gpg
|
||||||
|
|
||||||
|
# Add repository source entry:
|
||||||
|
echo "deb [signed-by=/etc/apt/trusted.gpg.d/gitea-wired.gpg] https://gitea.wired.synology.me/api/packages/soda64/debian stable main" | sudo tee /etc/apt/sources.list.d/gitea-wired.list
|
||||||
|
|
||||||
|
# Update package cache and install:
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install -y linux-updater
|
||||||
|
```
|
||||||
|
|
||||||
|
### C. Fleet Upgrades via Gitea Package Registry
|
||||||
|
|
||||||
|
Once configured on fleet machines, routine updates executed by `linux-updater` itself or system package managers will automatically pull new releases of `linux-updater` alongside system packages:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Automated routine update includes linux-updater package upgrades:
|
||||||
|
sudo linux-updater update -y
|
||||||
|
```
|
||||||
+45
-5
@@ -16,9 +16,11 @@ linux_updater/
|
|||||||
├── config.py # JSON configuration loader & default thresholds
|
├── config.py # JSON configuration loader & default thresholds
|
||||||
├── models.py # Core data transfer objects (DistroInfo, CheckResult, etc.)
|
├── models.py # Core data transfer objects (DistroInfo, CheckResult, etc.)
|
||||||
├── core/
|
├── core/
|
||||||
|
│ ├── completion.py # Shell autocompletion script generator (Bash & Zsh)
|
||||||
│ ├── detector.py # Distro detection via /etc/os-release parsing
|
│ ├── detector.py # Distro detection via /etc/os-release parsing
|
||||||
│ ├── health.py # Pre-flight health diagnostics & lock checking
|
│ ├── health.py # Pre-flight health diagnostics & package DB checking
|
||||||
│ ├── remediation.py # Automated remediation actions (cache, stale locks)
|
│ ├── lock.py # Concurrency advisory singleton lock
|
||||||
|
│ ├── remediation.py # Automated remediation actions (cache, stale locks, db repair)
|
||||||
│ └── runner.py # Subprocess runner with timestamped file logging
|
│ └── runner.py # Subprocess runner with timestamped file logging
|
||||||
└── managers/
|
└── managers/
|
||||||
├── __init__.py # get_manager() factory
|
├── __init__.py # get_manager() factory
|
||||||
@@ -149,6 +151,44 @@ 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-2.0.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_2.0.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-2.0.0-1.*.noarch.rpm`: Native RPM package.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. CI/CD Pipeline & Automated Release Workflow (Gitea Actions)
|
||||||
|
|
||||||
|
`linux-updater` incorporates an automated CI/CD pipeline defined in `.gitea/workflows/release.yml`.
|
||||||
|
|
||||||
|
### A. Pipeline Architecture & Execution Environment
|
||||||
|
- **Runner Host:** VM `giteaworker` on Synology NAS (`192.168.11.2`), running Fedora with `act_runner` in `hostexecutor` mode.
|
||||||
|
- **Workflow Tag:** `runs-on: fedora`.
|
||||||
|
- **Triggers:**
|
||||||
|
- Pushing any semantic version tag matching `v*` (e.g. `v2.0.0`).
|
||||||
|
- Manual execution via Gitea Web UI or `tea` CLI (`workflow_dispatch`).
|
||||||
|
|
||||||
|
### B. Pipeline Stages
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
A["Push Tag v* / Dispatch"] --> B["Checkout & Verify Environment (rpmbuild, python3)"]
|
||||||
|
B --> C["Run Unit Test Suite (python3 -m unittest discover tests)"]
|
||||||
|
C --> D["Build Distribution Packages (build_packages.py)"]
|
||||||
|
D --> E["Upload to Gitea Package Registry (RPM & Debian)"]
|
||||||
|
D --> F["Attach Artifacts to Gitea Release (API /releases)"]
|
||||||
|
E --> G["Link Packages to Repository (API /packages/.../link)"]
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **Environment Verification:** Verifies Python 3 runtime and ensures `rpmbuild` is installed on the runner.
|
||||||
|
2. **Quality Gate:** Runs full unit test suite (`python3 -m unittest discover tests`). Any test regression immediately aborts the pipeline.
|
||||||
|
3. **Package Compilation:** Invokes `packaging/build_packages.py` to produce native `.deb`, `.rpm`, and `.tar.gz` packages in `dist/`.
|
||||||
|
4. **Publishing to Gitea Package Registry:**
|
||||||
|
- RPM: `PUT /api/packages/soda64/rpm/upload`
|
||||||
|
- Debian: `PUT /api/packages/soda64/debian/pool/stable/main/upload`
|
||||||
|
- Links the uploaded packages to the `linux-updater` repository via `POST /api/v1/packages/soda64/<type>/linux-updater/-/link/linux-updater`.
|
||||||
|
- **Secret Requirement:** The upload requires a personal access token with `package:write` scope stored in repository secrets as `PACKAGES_GENERATION`.
|
||||||
|
5. **Gitea Release & Asset Attachment:**
|
||||||
|
- Queries or creates the Gitea Release corresponding to tag `vX.Y.Z`.
|
||||||
|
- Idempotently purges older assets on re-runs to prevent duplicated attachments.
|
||||||
|
- Uploads binary artifacts (`.tar.gz`, `.deb`, `.rpm`) as downloadable Release Assets for operators.
|
||||||
@@ -15,6 +15,13 @@
|
|||||||
- [x] Slice 7 — safety guardrails: root privilege check on mutating commands & singleton concurrency flock
|
- [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)
|
- [x] Slice 8 — upgrade dependency auto-installation (ELevate/Leapp/dnf-plugins-core) & container test suites (AlmaLinux 9, Arch Linux)
|
||||||
|
|
||||||
|
## v2.0.0 Slices (Enterprise Modernization)
|
||||||
|
- [x] Slice 9 — Shell tab completion: static Bash & Zsh completions, generator command `linux-updater completion [bash|zsh]`, and package deployment
|
||||||
|
- [x] Slice 10 — Package filtering & Security-only updates: `--exclude` (patterns/pins) and `--security` flag across apt, dnf, pacman
|
||||||
|
- [x] Slice 11 — Pre-flight package DB consistency: `check_package_db` health check with automated transaction repair (dpkg --configure -a)
|
||||||
|
- [x] Slice 12 — Flatpak support & Logrotate: optional `--flatpak` post-update trigger and `/etc/logrotate.d/linux-updater` configuration
|
||||||
|
- [x] Slice 13 — Version bump to 2.0.0, documentation update (guides, man page Section 8), and package rebuild (.deb, .rpm, .tar.gz)
|
||||||
|
|
||||||
## 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.
|
||||||
@@ -22,3 +29,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`.
|
||||||
+68
-9
@@ -27,7 +27,7 @@ linux-updater health
|
|||||||
|
|
||||||
**Example Output:**
|
**Example Output:**
|
||||||
```text
|
```text
|
||||||
Linux System Updater v1.0.0
|
Linux System Updater v2.0.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:
|
||||||
@@ -40,6 +40,7 @@ Pre-flight Health Diagnostics:
|
|||||||
[ PASS ] lock_lock No lock active at /var/lib/apt/lists/lock
|
[ PASS ] lock_lock No lock active at /var/lib/apt/lists/lock
|
||||||
[ PASS ] memory_available Available RAM is sufficient: 7850MB
|
[ PASS ] memory_available Available RAM is sufficient: 7850MB
|
||||||
[ PASS ] pending_reboot No pending system reboot detected.
|
[ PASS ] pending_reboot No pending system reboot detected.
|
||||||
|
[ PASS ] package_db Package database is consistent.
|
||||||
-----------------------------------------------------------------
|
-----------------------------------------------------------------
|
||||||
Overall Pre-flight Status: PASSED
|
Overall Pre-flight Status: PASSED
|
||||||
```
|
```
|
||||||
@@ -53,7 +54,7 @@ linux-updater check
|
|||||||
|
|
||||||
**Example Output:**
|
**Example Output:**
|
||||||
```text
|
```text
|
||||||
Linux System Updater v1.0.0
|
Linux System Updater v2.0.0
|
||||||
Detected System: Fedora Linux 40 (Family: rhel)
|
Detected System: Fedora Linux 40 (Family: rhel)
|
||||||
Checking available updates...
|
Checking available updates...
|
||||||
|
|
||||||
@@ -76,8 +77,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:
|
||||||
@@ -86,6 +92,42 @@ If you only want to upgrade specific software (e.g. security patches for OpenSSL
|
|||||||
sudo linux-updater update --packages openssl nginx
|
sudo linux-updater update --packages openssl nginx
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Security-Only Updates (`--security`)
|
||||||
|
To restrict updates solely to security patches and CVE advisories (supported on RHEL, Fedora, CentOS, Rocky, AlmaLinux, Debian, and Ubuntu):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo linux-updater update --security
|
||||||
|
```
|
||||||
|
|
||||||
|
### Excluding Packages (`--exclude`)
|
||||||
|
To exclude specific packages or glob patterns from being upgraded (e.g., pinning kernels, proprietary drivers, or database servers):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo linux-updater update --exclude "kernel*" "nvidia*"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Flatpak Application Updates (`--flatpak`)
|
||||||
|
If you use Flatpak for desktop applications or isolated utilities, pass `--flatpak` to automatically update all Flatpaks after operating system packages have updated:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo linux-updater update --flatpak
|
||||||
|
```
|
||||||
|
|
||||||
|
### Shell Tab Autocompletion (`completion`)
|
||||||
|
`linux-updater` provides zero-latency static tab completion for both Bash and Zsh. Subcommands, flags, and JSON configuration files auto-complete upon pressing `<Tab>`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Enable completion in current Bash shell:
|
||||||
|
eval "$(linux-updater completion bash)"
|
||||||
|
|
||||||
|
# Enable completion in current Zsh shell:
|
||||||
|
eval "$(linux-updater completion zsh)"
|
||||||
|
|
||||||
|
# Permanently install into user profile:
|
||||||
|
linux-updater completion bash >> ~/.bashrc
|
||||||
|
linux-updater completion zsh >> ~/.zshrc
|
||||||
|
```
|
||||||
|
|
||||||
### Simulation / Dry Run (`--dry-run`)
|
### Simulation / Dry Run (`--dry-run`)
|
||||||
To simulate the complete update transaction without changing package states:
|
To simulate the complete update transaction without changing package states:
|
||||||
|
|
||||||
@@ -97,16 +139,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 +168,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,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__ = "2.0.0"
|
||||||
__author__ = "Test Factory"
|
__author__ = "Test Factory"
|
||||||
+323
-24
@@ -2,6 +2,7 @@ import argparse
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
import sys
|
import sys
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
@@ -55,12 +56,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 +100,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",
|
||||||
@@ -84,13 +117,48 @@ def create_parser() -> argparse.ArgumentParser:
|
|||||||
metavar="PACKAGE",
|
metavar="PACKAGE",
|
||||||
help="Selectively update only the specified package(s) instead of the entire system.",
|
help="Selectively update only the specified package(s) instead of the entire system.",
|
||||||
)
|
)
|
||||||
|
update_parser.add_argument(
|
||||||
|
"--exclude",
|
||||||
|
nargs="+",
|
||||||
|
metavar="PATTERN",
|
||||||
|
help="Exclude package(s) or glob patterns (e.g. 'kernel*', 'nginx') from update.",
|
||||||
|
)
|
||||||
|
update_parser.add_argument(
|
||||||
|
"--security",
|
||||||
|
action="store_true",
|
||||||
|
help="Apply only security-related updates (supported on RHEL/Fedora/Debian/Ubuntu).",
|
||||||
|
)
|
||||||
|
update_parser.add_argument(
|
||||||
|
"--flatpak",
|
||||||
|
action="store_true",
|
||||||
|
help="Also update Flatpak packages if flatpak is installed.",
|
||||||
|
)
|
||||||
|
|
||||||
# Subcommand: check
|
# Subcommand: check
|
||||||
subparsers.add_parser(
|
check_parser = subparsers.add_parser(
|
||||||
"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
|
||||||
|
linux-updater check --security
|
||||||
|
linux-updater check --exclude kernel*
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
check_parser.add_argument(
|
||||||
|
"--exclude",
|
||||||
|
nargs="+",
|
||||||
|
metavar="PATTERN",
|
||||||
|
help="Exclude package(s) or glob patterns from check.",
|
||||||
|
)
|
||||||
|
check_parser.add_argument(
|
||||||
|
"--security",
|
||||||
|
action="store_true",
|
||||||
|
help="Check only security-related updates.",
|
||||||
)
|
)
|
||||||
|
|
||||||
# Subcommand: release-upgrade
|
# Subcommand: release-upgrade
|
||||||
@@ -98,12 +166,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 +194,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 +213,41 @@ 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
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Subcommand: completion
|
||||||
|
completion_parser = subparsers.add_parser(
|
||||||
|
"completion",
|
||||||
|
help="Generate shell autocompletion script (bash or zsh).",
|
||||||
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||||
|
description="Generate shell autocompletion script for Bash or Zsh.",
|
||||||
|
epilog="""
|
||||||
|
Installation Examples:
|
||||||
|
# Bash (current session)
|
||||||
|
source <(linux-updater completion bash)
|
||||||
|
|
||||||
|
# Bash (system-wide)
|
||||||
|
sudo linux-updater completion bash > /usr/share/bash-completion/completions/linux-updater
|
||||||
|
|
||||||
|
# Zsh (current session)
|
||||||
|
source <(linux-updater completion zsh)
|
||||||
|
|
||||||
|
# Zsh (system-wide)
|
||||||
|
sudo linux-updater completion zsh > /usr/share/zsh/site-functions/_linux-updater
|
||||||
|
""",
|
||||||
|
)
|
||||||
|
completion_parser.add_argument(
|
||||||
|
"shell",
|
||||||
|
choices=["bash", "zsh"],
|
||||||
|
help="Shell to generate autocompletion script for.",
|
||||||
)
|
)
|
||||||
|
|
||||||
return parser
|
return parser
|
||||||
@@ -143,17 +266,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
|
||||||
@@ -164,6 +319,16 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
parser = create_parser()
|
parser = create_parser()
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
if args.command == "completion":
|
||||||
|
from linux_updater.core.completion import get_bash_completion, get_zsh_completion
|
||||||
|
shell = getattr(args, "shell", "bash")
|
||||||
|
if shell == "zsh":
|
||||||
|
sys.stdout.write(get_zsh_completion())
|
||||||
|
else:
|
||||||
|
sys.stdout.write(get_bash_completion())
|
||||||
|
sys.stdout.flush()
|
||||||
|
return 0
|
||||||
|
|
||||||
if args.command is None:
|
if args.command is None:
|
||||||
args.command = "update"
|
args.command = "update"
|
||||||
|
|
||||||
@@ -247,11 +412,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 +449,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)
|
||||||
@@ -341,16 +511,24 @@ def _run(
|
|||||||
|
|
||||||
# 4. Check Command
|
# 4. Check Command
|
||||||
if args.command == "check":
|
if args.command == "check":
|
||||||
|
exclude = getattr(args, "exclude", None) or config.exclude_packages
|
||||||
|
security_only = getattr(args, "security", False) or config.security_only
|
||||||
if not json_output:
|
if not json_output:
|
||||||
|
if security_only:
|
||||||
|
print("Checking for available security updates...")
|
||||||
|
else:
|
||||||
print("Checking for available package updates...")
|
print("Checking for available package updates...")
|
||||||
updates = manager.check_updates()
|
updates = manager.check_updates(exclude=exclude, security_only=security_only)
|
||||||
if json_output:
|
if json_output:
|
||||||
print(json.dumps({
|
print(json.dumps({
|
||||||
"updates_count": len(updates),
|
"updates_count": len(updates),
|
||||||
|
"security_only": security_only,
|
||||||
|
"exclude": exclude,
|
||||||
"updates": [{"package": u.package, "current_version": u.current_version, "new_version": u.new_version, "repo": u.repo} for u in updates]
|
"updates": [{"package": u.package, "current_version": u.current_version, "new_version": u.new_version, "repo": u.repo} for u in updates]
|
||||||
}, indent=2))
|
}, indent=2))
|
||||||
else:
|
else:
|
||||||
print(f"\nAvailable Updates ({len(updates)}):")
|
label = "Security Updates" if security_only else "Available Updates"
|
||||||
|
print(f"\n{label} ({len(updates)}):")
|
||||||
print("-" * 65)
|
print("-" * 65)
|
||||||
for u in updates:
|
for u in updates:
|
||||||
print(f"• {u.package:<30} {u.current_version} -> {u.new_version}")
|
print(f"• {u.package:<30} {u.current_version} -> {u.new_version}")
|
||||||
@@ -360,22 +538,28 @@ def _run(
|
|||||||
# 5. Update Command
|
# 5. Update Command
|
||||||
if args.command == "update":
|
if args.command == "update":
|
||||||
packages = getattr(args, "packages", None)
|
packages = getattr(args, "packages", None)
|
||||||
|
exclude = getattr(args, "exclude", None) or config.exclude_packages
|
||||||
|
security_only = getattr(args, "security", False) or config.security_only
|
||||||
|
|
||||||
if not json_output:
|
if not json_output:
|
||||||
if packages:
|
if packages:
|
||||||
print(f"Preparing to update specific packages: {', '.join(packages)}")
|
print(f"Preparing to update specific packages: {', '.join(packages)}")
|
||||||
|
elif security_only:
|
||||||
|
print("Checking available security updates...")
|
||||||
else:
|
else:
|
||||||
print("Checking available updates...")
|
print("Checking available updates...")
|
||||||
|
|
||||||
# If not selective, query updates for preview in interactive mode
|
# If not selective, query updates for preview in interactive mode
|
||||||
updates = []
|
updates = []
|
||||||
if not packages and not config.non_interactive:
|
if not packages and not config.non_interactive:
|
||||||
updates = manager.check_updates()
|
updates = manager.check_updates(exclude=exclude, security_only=security_only)
|
||||||
if not updates:
|
if not updates:
|
||||||
if not json_output:
|
if not json_output:
|
||||||
print("System is already up to date. No updates needed.")
|
print("System is already up to date. No updates needed.")
|
||||||
return 0
|
return 0
|
||||||
if not json_output:
|
if not json_output:
|
||||||
print(f"\nAvailable Updates ({len(updates)}):")
|
label = "Available Security Updates" if security_only else "Available Updates"
|
||||||
|
print(f"\n{label} ({len(updates)}):")
|
||||||
print("-" * 65)
|
print("-" * 65)
|
||||||
for u in updates[:20]:
|
for u in updates[:20]:
|
||||||
print(f"• {u.package:<30} {u.current_version} -> {u.new_version}")
|
print(f"• {u.package:<30} {u.current_version} -> {u.new_version}")
|
||||||
@@ -395,6 +579,8 @@ def _run(
|
|||||||
|
|
||||||
res = manager.apply_updates(
|
res = manager.apply_updates(
|
||||||
packages=packages,
|
packages=packages,
|
||||||
|
exclude=exclude,
|
||||||
|
security_only=security_only,
|
||||||
dry_run=dry_run,
|
dry_run=dry_run,
|
||||||
non_interactive=config.non_interactive,
|
non_interactive=config.non_interactive,
|
||||||
)
|
)
|
||||||
@@ -406,6 +592,22 @@ def _run(
|
|||||||
print(json.dumps({"success": False, "result": res.to_dict()}, indent=2))
|
print(json.dumps({"success": False, "result": res.to_dict()}, indent=2))
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
# Flatpak updates if requested
|
||||||
|
flatpak_requested = getattr(args, "flatpak", False) or config.update_flatpak
|
||||||
|
if flatpak_requested:
|
||||||
|
flatpak_bin = shutil.which("flatpak")
|
||||||
|
if flatpak_bin:
|
||||||
|
if dry_run:
|
||||||
|
if not json_output:
|
||||||
|
print("[dry-run] Would execute: flatpak update -y")
|
||||||
|
else:
|
||||||
|
if not json_output:
|
||||||
|
print("\nUpdating Flatpak packages...")
|
||||||
|
runner.run(["flatpak", "update", "-y"])
|
||||||
|
elif getattr(args, "flatpak", False):
|
||||||
|
if not json_output:
|
||||||
|
print("Warning: flatpak binary not found, skipping Flatpak updates.", file=sys.stderr)
|
||||||
|
|
||||||
if config.clean_after_update:
|
if config.clean_after_update:
|
||||||
if not json_output:
|
if not json_output:
|
||||||
print("Cleaning orphan packages...")
|
print("Cleaning orphan packages...")
|
||||||
@@ -414,15 +616,44 @@ 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}).")
|
||||||
|
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 2
|
||||||
|
|
||||||
return 0
|
return 0
|
||||||
@@ -430,6 +661,30 @@ def _run(
|
|||||||
# 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 +696,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 +717,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
|
||||||
|
|||||||
+17
-1
@@ -1,6 +1,6 @@
|
|||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional, Dict, Any
|
from typing import Optional, Dict, Any, List
|
||||||
|
|
||||||
|
|
||||||
class UpdaterConfig:
|
class UpdaterConfig:
|
||||||
@@ -14,6 +14,10 @@ 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,
|
||||||
|
exclude_packages: Optional[List[str]] = None,
|
||||||
|
security_only: bool = False,
|
||||||
|
update_flatpak: 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 +30,10 @@ 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.exclude_packages = exclude_packages or []
|
||||||
|
self.security_only = security_only
|
||||||
|
self.update_flatpak = update_flatpak
|
||||||
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 +65,10 @@ 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),
|
||||||
|
exclude_packages=behavior.get("exclude_packages", []),
|
||||||
|
security_only=behavior.get("security_only", False),
|
||||||
|
update_flatpak=behavior.get("update_flatpak", 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 +87,10 @@ 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,
|
||||||
|
"exclude_packages": self.exclude_packages,
|
||||||
|
"security_only": self.security_only,
|
||||||
|
"update_flatpak": self.update_flatpak,
|
||||||
},
|
},
|
||||||
"logging": {
|
"logging": {
|
||||||
"log_dir": self.log_dir,
|
"log_dir": self.log_dir,
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
"""Shell completion script generator for linux-updater (Bash & Zsh)."""
|
||||||
|
|
||||||
|
BASH_COMPLETION = """# bash completion for linux-updater
|
||||||
|
|
||||||
|
_linux_updater() {
|
||||||
|
local cur prev words cword
|
||||||
|
_init_completion -n : || return
|
||||||
|
|
||||||
|
local commands="update check release-upgrade clean health completion"
|
||||||
|
local common_opts="-c --config -y --yes --non-interactive --dry-run --no-remediation --skip-preflight --json --reboot -h --help"
|
||||||
|
|
||||||
|
# Find the current subcommand (if any)
|
||||||
|
local cmd=""
|
||||||
|
local i
|
||||||
|
for (( i=1; i < cword; i++ )); do
|
||||||
|
case "${words[i]}" in
|
||||||
|
update|check|release-upgrade|clean|health|completion)
|
||||||
|
cmd="${words[i]}"
|
||||||
|
break
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# Handle completion for previous option
|
||||||
|
case "$prev" in
|
||||||
|
-c|--config)
|
||||||
|
_filedir json
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
-t|--target-release|--releasever)
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
--packages|--exclude)
|
||||||
|
return 0
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
# If no subcommand has been entered yet
|
||||||
|
if [[ -z "$cmd" ]]; then
|
||||||
|
if [[ "$cur" == -* ]]; then
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts -v --version" -- "$cur") )
|
||||||
|
return 0
|
||||||
|
else
|
||||||
|
COMPREPLY=( $(compgen -W "$commands" -- "$cur") )
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Subcommand-specific completions
|
||||||
|
case "$cmd" in
|
||||||
|
update)
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts --packages --exclude --security --flatpak" -- "$cur") )
|
||||||
|
;;
|
||||||
|
check)
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts" -- "$cur") )
|
||||||
|
;;
|
||||||
|
release-upgrade)
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts -t --target-release --releasever" -- "$cur") )
|
||||||
|
;;
|
||||||
|
clean)
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts --all" -- "$cur") )
|
||||||
|
;;
|
||||||
|
health)
|
||||||
|
COMPREPLY=( $(compgen -W "$common_opts" -- "$cur") )
|
||||||
|
;;
|
||||||
|
completion)
|
||||||
|
COMPREPLY=( $(compgen -W "bash zsh" -- "$cur") )
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
complete -F _linux_updater linux-updater
|
||||||
|
"""
|
||||||
|
|
||||||
|
ZSH_COMPLETION = r"""#compdef linux-updater
|
||||||
|
|
||||||
|
_linux_updater() {
|
||||||
|
local context state state_descr line
|
||||||
|
typeset -A opt_args
|
||||||
|
|
||||||
|
local -a common_args
|
||||||
|
common_args=(
|
||||||
|
'(-c --config)'{-c,--config}'[Path to JSON configuration file]:config file:_files -g "*.json"'
|
||||||
|
'(-y --yes --non-interactive)'{-y,--yes,--non-interactive}'[Run without interactive confirmation prompts]'
|
||||||
|
'--dry-run[Simulate execution without modifying system state]'
|
||||||
|
'--no-remediation[Disable automatic remediation of failed health checks]'
|
||||||
|
'--skip-preflight[Skip pre-flight health checks]'
|
||||||
|
'--json[Output structured JSON results]'
|
||||||
|
'--reboot[Automatically reboot the system after upgrade or if required]'
|
||||||
|
'(-h --help)'{-h,--help}'[Show help message and exit]'
|
||||||
|
)
|
||||||
|
|
||||||
|
_arguments -C \
|
||||||
|
'(-v --version)'{-v,--version}'[Show program version and exit]' \
|
||||||
|
$common_args \
|
||||||
|
'1: :->command' \
|
||||||
|
'*:: :->args'
|
||||||
|
|
||||||
|
case $state in
|
||||||
|
command)
|
||||||
|
local -a commands
|
||||||
|
commands=(
|
||||||
|
'update:Inspect health, auto-remediate safe issues, and apply package updates'
|
||||||
|
'check:Check system health and list available updates without making modifications'
|
||||||
|
'release-upgrade:Perform a major distribution release upgrade with safety checks'
|
||||||
|
'clean:Clean downloaded package cache and remove orphaned packages'
|
||||||
|
'health:Run only the pre-flight health diagnostic checks'
|
||||||
|
'completion:Generate shell autocompletion script (bash or zsh)'
|
||||||
|
)
|
||||||
|
_describe -t commands 'subcommand' commands
|
||||||
|
;;
|
||||||
|
args)
|
||||||
|
case $line[1] in
|
||||||
|
update)
|
||||||
|
_arguments \
|
||||||
|
$common_args \
|
||||||
|
'--packages[Selectively update specified package(s)]:package: ' \
|
||||||
|
'--exclude[Exclude package(s) or glob patterns from update]:exclude: ' \
|
||||||
|
'--security[Apply only security-related updates]' \
|
||||||
|
'--flatpak[Update Flatpak packages if available]'
|
||||||
|
;;
|
||||||
|
check)
|
||||||
|
_arguments \
|
||||||
|
$common_args
|
||||||
|
;;
|
||||||
|
release-upgrade)
|
||||||
|
_arguments \
|
||||||
|
$common_args \
|
||||||
|
'(-t --target-release --releasever)'{-t,--target-release,--releasever}'[Specify target distribution version number/codename]:target release: '
|
||||||
|
;;
|
||||||
|
clean)
|
||||||
|
_arguments \
|
||||||
|
$common_args \
|
||||||
|
'--all[Clean both package cache and autoremove unused dependencies]'
|
||||||
|
;;
|
||||||
|
health)
|
||||||
|
_arguments \
|
||||||
|
$common_args
|
||||||
|
;;
|
||||||
|
completion)
|
||||||
|
local -a shells
|
||||||
|
shells=('bash:Generate Bash completion script' 'zsh:Generate Zsh completion script')
|
||||||
|
_describe -t shells 'shell' shells
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
_linux_updater "$@"
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def get_bash_completion() -> str:
|
||||||
|
"""Returns the Bash completion script."""
|
||||||
|
return BASH_COMPLETION.strip() + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def get_zsh_completion() -> str:
|
||||||
|
"""Returns the Zsh completion function."""
|
||||||
|
return ZSH_COMPLETION.strip() + "\n"
|
||||||
@@ -340,6 +340,37 @@ class HealthChecker:
|
|||||||
)
|
)
|
||||||
return results
|
return results
|
||||||
|
|
||||||
|
def check_package_db(self) -> List[CheckResult]:
|
||||||
|
results: List[CheckResult] = []
|
||||||
|
try:
|
||||||
|
res = self.manager.verify_db_consistency()
|
||||||
|
if isinstance(res, (tuple, list)) and len(res) == 2:
|
||||||
|
is_ok, msg = res
|
||||||
|
else:
|
||||||
|
is_ok, msg = True, "Package database is consistent."
|
||||||
|
except Exception as e:
|
||||||
|
is_ok, msg = False, f"Package database check failed: {e}"
|
||||||
|
|
||||||
|
if is_ok:
|
||||||
|
results.append(
|
||||||
|
CheckResult(
|
||||||
|
name="package_db",
|
||||||
|
status=CheckStatus.PASS,
|
||||||
|
message=msg,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
results.append(
|
||||||
|
CheckResult(
|
||||||
|
name="package_db",
|
||||||
|
status=CheckStatus.FAIL,
|
||||||
|
message=msg,
|
||||||
|
can_remediate=True,
|
||||||
|
remediation_id="repair_package_db",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return results
|
||||||
|
|
||||||
def run_all_checks(self) -> PreflightReport:
|
def run_all_checks(self) -> PreflightReport:
|
||||||
all_results: List[CheckResult] = []
|
all_results: List[CheckResult] = []
|
||||||
all_results.extend(self.check_disk_space())
|
all_results.extend(self.check_disk_space())
|
||||||
@@ -347,6 +378,7 @@ class HealthChecker:
|
|||||||
all_results.extend(self.check_memory_and_oom())
|
all_results.extend(self.check_memory_and_oom())
|
||||||
all_results.extend(self.check_power())
|
all_results.extend(self.check_power())
|
||||||
all_results.extend(self.check_pending_reboot())
|
all_results.extend(self.check_pending_reboot())
|
||||||
|
all_results.extend(self.check_package_db())
|
||||||
|
|
||||||
has_failure = any(r.status == CheckStatus.FAIL for r in all_results)
|
has_failure = any(r.status == CheckStatus.FAIL for r in all_results)
|
||||||
return PreflightReport(passed=not has_failure, results=all_results)
|
return PreflightReport(passed=not has_failure, results=all_results)
|
||||||
@@ -14,7 +14,7 @@ class RemediationEngine:
|
|||||||
def can_remediate(self, check: CheckResult) -> bool:
|
def can_remediate(self, check: CheckResult) -> bool:
|
||||||
if not check.can_remediate:
|
if not check.can_remediate:
|
||||||
return False
|
return False
|
||||||
return check.remediation_id in {"clean_cache", "remove_stale_lock"}
|
return check.remediation_id in {"clean_cache", "remove_stale_lock", "repair_package_db"}
|
||||||
|
|
||||||
def remediate(self, check: CheckResult) -> bool:
|
def remediate(self, check: CheckResult) -> bool:
|
||||||
if not self.can_remediate(check):
|
if not self.can_remediate(check):
|
||||||
@@ -24,9 +24,20 @@ class RemediationEngine:
|
|||||||
return self.clean_cache()
|
return self.clean_cache()
|
||||||
elif check.remediation_id == "remove_stale_lock":
|
elif check.remediation_id == "remove_stale_lock":
|
||||||
return self.remove_stale_lock(check.message)
|
return self.remove_stale_lock(check.message)
|
||||||
|
elif check.remediation_id == "repair_package_db":
|
||||||
|
return self.repair_package_db()
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def repair_package_db(self) -> bool:
|
||||||
|
try:
|
||||||
|
res = self.manager.repair_db()
|
||||||
|
if hasattr(res, "success"):
|
||||||
|
return bool(res.success)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
def clean_cache(self) -> bool:
|
def clean_cache(self) -> bool:
|
||||||
try:
|
try:
|
||||||
res = self.manager.clean_cache()
|
res = self.manager.clean_cache()
|
||||||
|
|||||||
@@ -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,6 +39,38 @@ class CommandRunner:
|
|||||||
self._log(f"Executing: {' '.join(cmd)}")
|
self._log(f"Executing: {' '.join(cmd)}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
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(
|
proc = subprocess.run(
|
||||||
cmd,
|
cmd,
|
||||||
stdout=subprocess.PIPE,
|
stdout=subprocess.PIPE,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import re
|
import re
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, List, Optional
|
from typing import Dict, 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
|
||||||
@@ -19,58 +19,87 @@ 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:
|
||||||
cmd = ["apt-get", "update"]
|
cmd = ["apt-get", "update"]
|
||||||
return self.runner.run(cmd, env=self._env(True))
|
return self.runner.run(cmd, env=self._env(True))
|
||||||
|
|
||||||
def check_updates(self) -> List[PackageUpdate]:
|
def check_updates(
|
||||||
|
self,
|
||||||
|
exclude: Optional[List[str]] = None,
|
||||||
|
security_only: bool = False,
|
||||||
|
) -> List[PackageUpdate]:
|
||||||
cmd = ["apt-get", "-s", "upgrade"]
|
cmd = ["apt-get", "-s", "upgrade"]
|
||||||
res = self.runner.run(cmd, env=self._env(True))
|
res = self.runner.run(cmd, env=self._env(True))
|
||||||
updates: List[PackageUpdate] = []
|
updates: List[PackageUpdate] = []
|
||||||
|
|
||||||
# Inst libssl3 [3.0.13-0ubuntu3.1] (3.0.13-0ubuntu3.4 Ubuntu:24.04/noble-updates [amd64])
|
import fnmatch
|
||||||
|
|
||||||
pattern = re.compile(r"^Inst\s+(\S+)\s+\[([^\]]+)\]\s+\((\S+)\s+([^)]*)\)")
|
pattern = re.compile(r"^Inst\s+(\S+)\s+\[([^\]]+)\]\s+\((\S+)\s+([^)]*)\)")
|
||||||
pattern_new = re.compile(r"^Inst\s+(\S+)\s+\((\S+)\s+([^)]*)\)")
|
pattern_new = re.compile(r"^Inst\s+(\S+)\s+\((\S+)\s+([^)]*)\)")
|
||||||
|
|
||||||
for line in res.stdout.splitlines():
|
for line in res.stdout.splitlines():
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
|
pkg = None
|
||||||
|
old_ver = "none"
|
||||||
|
new_ver = ""
|
||||||
|
repo = None
|
||||||
|
|
||||||
match = pattern.match(line)
|
match = pattern.match(line)
|
||||||
if match:
|
if match:
|
||||||
pkg, old_ver, new_ver, repo = match.groups()
|
pkg, old_ver, new_ver, repo = match.groups()
|
||||||
updates.append(PackageUpdate(package=pkg, current_version=old_ver, new_version=new_ver, repo=repo))
|
else:
|
||||||
continue
|
|
||||||
match_new = pattern_new.match(line)
|
match_new = pattern_new.match(line)
|
||||||
if match_new:
|
if match_new:
|
||||||
pkg, new_ver, repo = match_new.groups()
|
pkg, new_ver, repo = match_new.groups()
|
||||||
updates.append(PackageUpdate(package=pkg, current_version="none", new_version=new_ver, repo=repo))
|
|
||||||
|
if pkg:
|
||||||
|
if exclude and any(fnmatch.fnmatch(pkg, pat) for pat in exclude):
|
||||||
|
continue
|
||||||
|
if security_only:
|
||||||
|
repo_str = repo.lower() if repo else ""
|
||||||
|
if "security" not in repo_str and "-sec" not in repo_str:
|
||||||
|
continue
|
||||||
|
updates.append(PackageUpdate(package=pkg, current_version=old_ver, new_version=new_ver, repo=repo))
|
||||||
|
|
||||||
return updates
|
return updates
|
||||||
|
|
||||||
def apply_updates(
|
def apply_updates(
|
||||||
self,
|
self,
|
||||||
packages: Optional[List[str]] = None,
|
packages: Optional[List[str]] = None,
|
||||||
|
exclude: Optional[List[str]] = None,
|
||||||
|
security_only: bool = False,
|
||||||
dry_run: bool = False,
|
dry_run: bool = False,
|
||||||
non_interactive: bool = False,
|
non_interactive: bool = False,
|
||||||
) -> CommandResult:
|
) -> CommandResult:
|
||||||
cmd = ["apt-get"]
|
cmd = ["apt-get"]
|
||||||
if packages:
|
if packages:
|
||||||
cmd.extend(["install", "--only-upgrade", "-y"])
|
import fnmatch
|
||||||
cmd.extend(packages)
|
target_pkgs = [p for p in packages if not (exclude and any(fnmatch.fnmatch(p, pat) for pat in exclude))]
|
||||||
|
if not target_pkgs:
|
||||||
|
return CommandResult(0, "All specified packages were excluded.", "", True)
|
||||||
|
cmd.extend(["install", "--only-upgrade", "-y"] + target_pkgs)
|
||||||
|
elif exclude or security_only:
|
||||||
|
filtered = self.check_updates(exclude=exclude, security_only=security_only)
|
||||||
|
if not filtered:
|
||||||
|
return CommandResult(0, "No matching packages to upgrade after applying filters.", "", True)
|
||||||
|
target_pkgs = [u.package for u in filtered]
|
||||||
|
cmd.extend(["install", "--only-upgrade", "-y"] + target_pkgs)
|
||||||
else:
|
else:
|
||||||
cmd.extend(["upgrade", "-y"])
|
cmd.extend(["upgrade", "-y"])
|
||||||
|
|
||||||
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 +113,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"])
|
||||||
@@ -126,3 +155,14 @@ class AptManager(PackageManager):
|
|||||||
Path("/var/lib/dpkg/lock"),
|
Path("/var/lib/dpkg/lock"),
|
||||||
Path("/var/lib/apt/lists/lock"),
|
Path("/var/lib/apt/lists/lock"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
def verify_db_consistency(self) -> "Tuple[bool, str]":
|
||||||
|
audit_res = self.runner.run(["dpkg", "--audit"])
|
||||||
|
if audit_res.return_code != 0 or audit_res.stdout.strip():
|
||||||
|
msg = audit_res.stdout.strip() or audit_res.stderr.strip() or "Unconfigured or broken packages detected"
|
||||||
|
return False, f"dpkg audit found package database issues: {msg[:100]}"
|
||||||
|
return True, "dpkg package database is consistent."
|
||||||
|
|
||||||
|
def repair_db(self) -> CommandResult:
|
||||||
|
self.runner.run(["dpkg", "--configure", "-a"], env=self._env(True))
|
||||||
|
return self.runner.run(["apt-get", "install", "-f", "-y"], env=self._env(True))
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List, Optional
|
from typing import List, Optional, Tuple
|
||||||
from linux_updater.models import PackageUpdate, CommandResult, RebootStatus
|
from linux_updater.models import PackageUpdate, CommandResult, RebootStatus
|
||||||
|
|
||||||
|
|
||||||
@@ -17,7 +17,11 @@ class PackageManager(ABC):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def check_updates(self) -> List[PackageUpdate]:
|
def check_updates(
|
||||||
|
self,
|
||||||
|
exclude: Optional[List[str]] = None,
|
||||||
|
security_only: bool = False,
|
||||||
|
) -> List[PackageUpdate]:
|
||||||
"""Lists available package updates."""
|
"""Lists available package updates."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -25,6 +29,8 @@ class PackageManager(ABC):
|
|||||||
def apply_updates(
|
def apply_updates(
|
||||||
self,
|
self,
|
||||||
packages: Optional[List[str]] = None,
|
packages: Optional[List[str]] = None,
|
||||||
|
exclude: Optional[List[str]] = None,
|
||||||
|
security_only: bool = False,
|
||||||
dry_run: bool = False,
|
dry_run: bool = False,
|
||||||
non_interactive: bool = False,
|
non_interactive: bool = False,
|
||||||
) -> CommandResult:
|
) -> CommandResult:
|
||||||
@@ -60,3 +66,11 @@ class PackageManager(ABC):
|
|||||||
def get_lock_files(self) -> List[Path]:
|
def get_lock_files(self) -> List[Path]:
|
||||||
"""Returns paths of lockfiles used by this manager."""
|
"""Returns paths of lockfiles used by this manager."""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
def verify_db_consistency(self) -> "Tuple[bool, str]":
|
||||||
|
"""Checks whether the package manager database has broken/interrupted transactions."""
|
||||||
|
return True, "Package database is consistent."
|
||||||
|
|
||||||
|
def repair_db(self) -> CommandResult:
|
||||||
|
"""Attempts automated repair of interrupted/broken package transactions."""
|
||||||
|
return CommandResult(0, "No repair needed.", "", True)
|
||||||
@@ -29,8 +29,17 @@ class DnfManager(PackageManager):
|
|||||||
cmd = [self.binary, "makecache"]
|
cmd = [self.binary, "makecache"]
|
||||||
return self.runner.run(cmd)
|
return self.runner.run(cmd)
|
||||||
|
|
||||||
def check_updates(self) -> List[PackageUpdate]:
|
def check_updates(
|
||||||
|
self,
|
||||||
|
exclude: Optional[List[str]] = None,
|
||||||
|
security_only: bool = False,
|
||||||
|
) -> List[PackageUpdate]:
|
||||||
cmd = [self.binary, "check-update"]
|
cmd = [self.binary, "check-update"]
|
||||||
|
if security_only:
|
||||||
|
cmd.append("--security")
|
||||||
|
if exclude:
|
||||||
|
for pat in exclude:
|
||||||
|
cmd.extend(["-x", pat])
|
||||||
res = self.runner.run(cmd)
|
res = self.runner.run(cmd)
|
||||||
|
|
||||||
# DNF returns exit code 100 when updates are found, 0 when clean
|
# DNF returns exit code 100 when updates are found, 0 when clean
|
||||||
@@ -56,19 +65,28 @@ class DnfManager(PackageManager):
|
|||||||
def apply_updates(
|
def apply_updates(
|
||||||
self,
|
self,
|
||||||
packages: Optional[List[str]] = None,
|
packages: Optional[List[str]] = None,
|
||||||
|
exclude: Optional[List[str]] = None,
|
||||||
|
security_only: bool = False,
|
||||||
dry_run: bool = False,
|
dry_run: bool = False,
|
||||||
non_interactive: bool = False,
|
non_interactive: bool = False,
|
||||||
) -> CommandResult:
|
) -> CommandResult:
|
||||||
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 security_only:
|
||||||
|
cmd.append("--security")
|
||||||
|
|
||||||
|
if exclude:
|
||||||
|
for pat in exclude:
|
||||||
|
cmd.extend(["-x", pat])
|
||||||
|
|
||||||
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 +242,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 +311,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 +358,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 +380,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 +406,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"])
|
||||||
@@ -386,3 +430,13 @@ class DnfManager(PackageManager):
|
|||||||
Path("/var/lib/rpm/.rpm.lock"),
|
Path("/var/lib/rpm/.rpm.lock"),
|
||||||
Path("/var/run/dnf.pid"),
|
Path("/var/run/dnf.pid"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
def verify_db_consistency(self) -> Tuple[bool, str]:
|
||||||
|
check_res = self.runner.run([self.binary, "check"])
|
||||||
|
if check_res.return_code != 0:
|
||||||
|
msg = check_res.stderr.strip() or check_res.stdout.strip() or "Transaction database issues found"
|
||||||
|
return False, f"dnf check found package database issues: {msg[:100]}"
|
||||||
|
return True, "RPM database is consistent."
|
||||||
|
|
||||||
|
def repair_db(self) -> CommandResult:
|
||||||
|
return self.runner.run([self.binary, "clean", "all"])
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import os
|
import os
|
||||||
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
|
||||||
@@ -19,24 +19,32 @@ class PacmanManager(PackageManager):
|
|||||||
def refresh_repositories(self) -> CommandResult:
|
def refresh_repositories(self) -> CommandResult:
|
||||||
return self.runner.run(["pacman", "-Sy"])
|
return self.runner.run(["pacman", "-Sy"])
|
||||||
|
|
||||||
def check_updates(self) -> List[PackageUpdate]:
|
def check_updates(
|
||||||
|
self,
|
||||||
|
exclude: Optional[List[str]] = None,
|
||||||
|
security_only: bool = False,
|
||||||
|
) -> List[PackageUpdate]:
|
||||||
# Prefer checkupdates if installed (safe non-root update check)
|
# Prefer checkupdates if installed (safe non-root update check)
|
||||||
cmd = ["checkupdates"] if shutil.which("checkupdates") else ["pacman", "-Qu"]
|
cmd = ["checkupdates"] if shutil.which("checkupdates") else ["pacman", "-Qu"]
|
||||||
res = self.runner.run(cmd)
|
res = self.runner.run(cmd)
|
||||||
|
|
||||||
|
import fnmatch
|
||||||
|
|
||||||
updates: List[PackageUpdate] = []
|
updates: List[PackageUpdate] = []
|
||||||
for line in res.stdout.splitlines():
|
for line in res.stdout.splitlines():
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if not line or "->" not in line:
|
if not line or "->" not in line:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Format: package old_version -> new_version [repo]
|
|
||||||
try:
|
try:
|
||||||
left, right = line.split("->", 1)
|
left, right = line.split("->", 1)
|
||||||
left_parts = left.strip().split()
|
left_parts = left.strip().split()
|
||||||
right_parts = right.strip().split()
|
right_parts = right.strip().split()
|
||||||
|
|
||||||
pkg = left_parts[0]
|
pkg = left_parts[0]
|
||||||
|
if exclude and any(fnmatch.fnmatch(pkg, pat) for pat in exclude):
|
||||||
|
continue
|
||||||
|
|
||||||
old_ver = left_parts[1] if len(left_parts) > 1 else "unknown"
|
old_ver = left_parts[1] if len(left_parts) > 1 else "unknown"
|
||||||
new_ver = right_parts[0] if right_parts else "unknown"
|
new_ver = right_parts[0] if right_parts else "unknown"
|
||||||
repo = right_parts[1].strip("[]") if len(right_parts) > 1 else None
|
repo = right_parts[1].strip("[]") if len(right_parts) > 1 else None
|
||||||
@@ -50,24 +58,34 @@ class PacmanManager(PackageManager):
|
|||||||
def apply_updates(
|
def apply_updates(
|
||||||
self,
|
self,
|
||||||
packages: Optional[List[str]] = None,
|
packages: Optional[List[str]] = None,
|
||||||
|
exclude: Optional[List[str]] = None,
|
||||||
|
security_only: bool = False,
|
||||||
dry_run: bool = False,
|
dry_run: bool = False,
|
||||||
non_interactive: bool = False,
|
non_interactive: bool = False,
|
||||||
) -> CommandResult:
|
) -> CommandResult:
|
||||||
if packages:
|
if packages:
|
||||||
|
import fnmatch
|
||||||
|
target_pkgs = [p for p in packages if not (exclude and any(fnmatch.fnmatch(p, pat) for pat in exclude))]
|
||||||
|
if not target_pkgs:
|
||||||
|
return CommandResult(0, "All specified packages were excluded.", "", True)
|
||||||
cmd = ["pacman", "-S"]
|
cmd = ["pacman", "-S"]
|
||||||
if non_interactive:
|
|
||||||
cmd.append("--noconfirm")
|
|
||||||
if dry_run:
|
if dry_run:
|
||||||
cmd.append("-p")
|
cmd.append("-p")
|
||||||
cmd.extend(packages)
|
else:
|
||||||
|
cmd.append("--noconfirm")
|
||||||
|
if exclude:
|
||||||
|
cmd.extend(["--ignore", ",".join(exclude)])
|
||||||
|
cmd.extend(target_pkgs)
|
||||||
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")
|
||||||
|
if exclude:
|
||||||
|
cmd.extend(["--ignore", ",".join(exclude)])
|
||||||
|
|
||||||
return self.runner.run(cmd)
|
return self.runner.run(cmd, stream=not dry_run)
|
||||||
|
|
||||||
def release_upgrade(
|
def release_upgrade(
|
||||||
self,
|
self,
|
||||||
@@ -79,9 +97,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"])
|
||||||
@@ -112,3 +130,18 @@ class PacmanManager(PackageManager):
|
|||||||
|
|
||||||
def get_lock_files(self) -> List[Path]:
|
def get_lock_files(self) -> List[Path]:
|
||||||
return [Path("/var/lib/pacman/db.lck")]
|
return [Path("/var/lib/pacman/db.lck")]
|
||||||
|
|
||||||
|
def verify_db_consistency(self) -> "Tuple[bool, str]":
|
||||||
|
lock_p = Path("/var/lib/pacman/db.lck")
|
||||||
|
if lock_p.exists():
|
||||||
|
return False, f"Stale pacman database lock: {lock_p}"
|
||||||
|
return True, "Pacman database is consistent."
|
||||||
|
|
||||||
|
def repair_db(self) -> CommandResult:
|
||||||
|
lock_p = Path("/var/lib/pacman/db.lck")
|
||||||
|
if lock_p.exists():
|
||||||
|
try:
|
||||||
|
lock_p.unlink()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return CommandResult(0, "Pacman database checked.", "", True)
|
||||||
+50
-8
@@ -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 2.0.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]
|
||||||
@@ -23,30 +24,35 @@ Free disk space verification on \fB/boot\fR (min 250MB), \fB/var\fR (min 1GB), a
|
|||||||
.IP \(bu 2
|
.IP \(bu 2
|
||||||
Package manager lock detection and advisory locking inspections (\fBfcntl.flock\fR).
|
Package manager lock detection and advisory locking inspections (\fBfcntl.flock\fR).
|
||||||
.IP \(bu 2
|
.IP \(bu 2
|
||||||
|
Package database consistency inspection and safe remediation of interrupted transactions (\fBdpkg \-\-configure \-a\fR, \fBapt\-get install \-f\fR, \fBdnf clean all\fR).
|
||||||
|
.IP \(bu 2
|
||||||
Memory availability and low-RAM/OOM risk detection via \fB/proc/meminfo\fR.
|
Memory availability and low-RAM/OOM risk detection via \fB/proc/meminfo\fR.
|
||||||
.IP \(bu 2
|
.IP \(bu 2
|
||||||
AC power status detection on portable systems via \fB/sys/class/power_supply\fR.
|
AC power status detection on portable systems via \fB/sys/class/power_supply\fR.
|
||||||
.IP \(bu 2
|
.IP \(bu 2
|
||||||
Pending reboot detection from previously installed kernels or libraries.
|
Pending reboot detection from previously installed kernels or libraries.
|
||||||
|
|
||||||
If low disk space on \fB/var\fR is detected, \fBlinux-updater\fR safely purges cached packages. If an abandoned lock file is identified whose holder process is confirmed dead, it removes the stale lock.
|
If low disk space on \fB/var\fR is detected, \fBlinux-updater\fR safely purges cached packages. If an abandoned lock file is identified whose holder process is confirmed dead, it removes the stale lock. If an interrupted package installation transaction is detected, it executes automated repair.
|
||||||
|
|
||||||
.SH COMMANDS
|
.SH COMMANDS
|
||||||
.TP
|
.TP
|
||||||
.B update \fR[\fB\-\-packages \fIPKG...\fR]
|
.B update \fR[\fB\-\-packages \fIPKG...\fR] [\fB\-\-exclude \fIPATTERN...\fR] [\fB\-\-security\fR] [\fB\-\-flatpak\fR]
|
||||||
Runs pre-flight diagnostics, cleans caches if needed, checks for available updates, prompts for user confirmation (unless \fB\-y\fR is provided), applies routine package upgrades, and reports reboot status. When \fB\-\-packages\fR is specified, updates only the named packages.
|
Runs pre-flight diagnostics, auto-remediates safe issues, checks for available updates, prompts for user confirmation (unless \fB\-y\fR is provided), applies routine package upgrades, and reports reboot status. When \fB\-\-packages\fR is specified, updates only the named packages. When \fB\-\-exclude\fR is specified, skips packages matching the names or glob patterns. When \fB\-\-security\fR is specified, installs only security updates. When \fB\-\-flatpak\fR is specified, updates Flatpak applications after OS packages.
|
||||||
.TP
|
.TP
|
||||||
.B check
|
.B check \fR[\fB\-\-exclude \fIPATTERN...\fR] [\fB\-\-security\fR]
|
||||||
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.
|
||||||
.TP
|
.TP
|
||||||
.B health
|
.B health
|
||||||
Runs pre-flight system diagnostics and prints a formatted health report (or JSON with \fB\-\-json\fR) without performing updates.
|
Runs pre-flight system diagnostics and prints a formatted health report (or JSON with \fB\-\-json\fR) without performing updates.
|
||||||
|
.TP
|
||||||
|
.B completion \fR[\fBbash\fR|\fBzsh\fR]
|
||||||
|
Outputs shell tab completion script to stdout for evaluation or installation into shell profiles.
|
||||||
|
|
||||||
.SH OPTIONS
|
.SH OPTIONS
|
||||||
.TP
|
.TP
|
||||||
@@ -59,8 +65,20 @@ 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
|
||||||
|
.BR \-\-exclude " \fIPATTERN...\fR"
|
||||||
|
Exclude package(s) or glob patterns (e.g. 'kernel*', 'nginx') from update operations.
|
||||||
|
.TP
|
||||||
|
.B \-\-security
|
||||||
|
Restrict update operations strictly to security patches and vulnerability advisories. Supported on RHEL, Fedora, CentOS, Rocky, AlmaLinux, Debian, and Ubuntu.
|
||||||
|
.TP
|
||||||
|
.B \-\-flatpak
|
||||||
|
Execute Flatpak application updates (\fBflatpak update \-y\fR) after OS package manager operations complete.
|
||||||
|
.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, unlinking stale locks, or repairing interrupted transactions).
|
||||||
.TP
|
.TP
|
||||||
.B \-\-skip\-preflight
|
.B \-\-skip\-preflight
|
||||||
Bypasses all pre-flight health diagnostics.
|
Bypasses all pre-flight health diagnostics.
|
||||||
@@ -82,11 +100,20 @@ Displays the command-line help summary.
|
|||||||
.I /etc/linux-updater.json
|
.I /etc/linux-updater.json
|
||||||
System configuration file containing disk thresholds, behavior switches, and logging directory settings.
|
System configuration file containing disk thresholds, behavior switches, and logging directory settings.
|
||||||
.TP
|
.TP
|
||||||
|
.I /etc/logrotate.d/linux-updater
|
||||||
|
Logrotate policy rotating updater logs weekly, keeping 4 archives compressed with 0640 permissions.
|
||||||
|
.TP
|
||||||
.I /var/log/linux-updater/
|
.I /var/log/linux-updater/
|
||||||
Standard directory for execution logs conforming to Linux FHS. Each execution creates a timestamped file \fIlinux-updater-YYYYMMDD-HHMMSS.log\fR.
|
Standard directory for execution logs conforming to Linux FHS. Each execution creates a timestamped file \fIlinux-updater-YYYYMMDD-HHMMSS.log\fR.
|
||||||
.TP
|
.TP
|
||||||
.I /var/log/linux-updater/latest.log
|
.I /var/log/linux-updater/latest.log
|
||||||
Atomic symbolic link pointing to the most recent execution log file.
|
Atomic symbolic link pointing to the most recent execution log file.
|
||||||
|
.TP
|
||||||
|
.I /usr/share/bash-completion/completions/linux-updater
|
||||||
|
Static Bash command and argument autocompletion definition.
|
||||||
|
.TP
|
||||||
|
.I /usr/share/zsh/site-functions/_linux-updater
|
||||||
|
Static Zsh command and argument autocompletion definition.
|
||||||
|
|
||||||
.SH EXIT STATUS
|
.SH EXIT STATUS
|
||||||
.TP
|
.TP
|
||||||
@@ -119,6 +146,16 @@ Apply routine updates non-interactively:
|
|||||||
.B linux-updater \-y update
|
.B linux-updater \-y update
|
||||||
.RE
|
.RE
|
||||||
.PP
|
.PP
|
||||||
|
Apply security updates only:
|
||||||
|
.RS
|
||||||
|
.B linux-updater \-y update \-\-security
|
||||||
|
.RE
|
||||||
|
.PP
|
||||||
|
Apply updates excluding kernel packages:
|
||||||
|
.RS
|
||||||
|
.B linux-updater \-y update \-\-exclude "kernel*"
|
||||||
|
.RE
|
||||||
|
.PP
|
||||||
Selectively update only the openssl and nginx packages:
|
Selectively update only the openssl and nginx packages:
|
||||||
.RS
|
.RS
|
||||||
.B linux-updater \-y update \-\-packages openssl nginx
|
.B linux-updater \-y update \-\-packages openssl nginx
|
||||||
@@ -128,6 +165,11 @@ Simulate major distribution upgrade to target version:
|
|||||||
.RS
|
.RS
|
||||||
.B linux-updater release\-upgrade \-\-dry\-run \-t 41
|
.B linux-updater release\-upgrade \-\-dry\-run \-t 41
|
||||||
.RE
|
.RE
|
||||||
|
.PP
|
||||||
|
Install shell completions for Bash:
|
||||||
|
.RS
|
||||||
|
.B eval "$(linux-updater completion bash)"
|
||||||
|
.RE
|
||||||
|
|
||||||
.SH SEE ALSO
|
.SH SEE ALSO
|
||||||
.BR apt-get (8),
|
.BR apt-get (8),
|
||||||
|
|||||||
@@ -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 = "2.0.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")
|
||||||
@@ -105,6 +105,16 @@ class PackageBuilder:
|
|||||||
if (self.source_root / "man").exists():
|
if (self.source_root / "man").exists():
|
||||||
shutil.copytree(str(self.source_root / "man"), str(tmp_root / "man"))
|
shutil.copytree(str(self.source_root / "man"), str(tmp_root / "man"))
|
||||||
|
|
||||||
|
# Copy shell completions
|
||||||
|
if (self.source_root / "completions").exists():
|
||||||
|
shutil.copytree(str(self.source_root / "completions"), str(tmp_root / "completions"))
|
||||||
|
|
||||||
|
# Copy packaging extras (logrotate)
|
||||||
|
if (self.source_root / "packaging" / "logrotate").exists():
|
||||||
|
pkg_dest = tmp_root / "packaging" / "logrotate"
|
||||||
|
pkg_dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copytree(str(self.source_root / "packaging" / "logrotate"), str(pkg_dest))
|
||||||
|
|
||||||
# Archive the tree
|
# Archive the tree
|
||||||
with tarfile.open(str(out_path), "w:gz") as tar:
|
with tarfile.open(str(out_path), "w:gz") as tar:
|
||||||
tar.add(str(tmp_root), arcname=f"linux-updater-{self.version}")
|
tar.add(str(tmp_root), arcname=f"linux-updater-{self.version}")
|
||||||
@@ -151,6 +161,28 @@ class PackageBuilder:
|
|||||||
man_dir.mkdir(parents=True, exist_ok=True)
|
man_dir.mkdir(parents=True, exist_ok=True)
|
||||||
shutil.copy2(str(self.source_root / "man" / "linux-updater.8"), str(man_dir / "linux-updater.8"))
|
shutil.copy2(str(self.source_root / "man" / "linux-updater.8"), str(man_dir / "linux-updater.8"))
|
||||||
|
|
||||||
|
if (self.source_root / "completions" / "bash" / "linux-updater").exists():
|
||||||
|
bash_comp_dir = data_dir / "usr" / "share" / "bash-completion" / "completions"
|
||||||
|
bash_comp_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(
|
||||||
|
str(self.source_root / "completions" / "bash" / "linux-updater"),
|
||||||
|
str(bash_comp_dir / "linux-updater"),
|
||||||
|
)
|
||||||
|
if (self.source_root / "completions" / "zsh" / "_linux-updater").exists():
|
||||||
|
zsh_comp_dir = data_dir / "usr" / "share" / "zsh" / "vendor-completions"
|
||||||
|
zsh_comp_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(
|
||||||
|
str(self.source_root / "completions" / "zsh" / "_linux-updater"),
|
||||||
|
str(zsh_comp_dir / "_linux-updater"),
|
||||||
|
)
|
||||||
|
if (self.source_root / "packaging" / "logrotate" / "linux-updater").exists():
|
||||||
|
logrotate_dir = data_dir / "etc" / "logrotate.d"
|
||||||
|
logrotate_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(
|
||||||
|
str(self.source_root / "packaging" / "logrotate" / "linux-updater"),
|
||||||
|
str(logrotate_dir / "linux-updater"),
|
||||||
|
)
|
||||||
|
|
||||||
# If dpkg-deb is available, use it; otherwise build native .deb
|
# If dpkg-deb is available, use it; otherwise build native .deb
|
||||||
if shutil.which("dpkg-deb"):
|
if shutil.which("dpkg-deb"):
|
||||||
pkg_tree = root / "deb_tree"
|
pkg_tree = root / "deb_tree"
|
||||||
@@ -160,16 +192,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)
|
||||||
|
|
||||||
@@ -203,6 +243,12 @@ class PackageBuilder:
|
|||||||
)
|
)
|
||||||
if (self.source_root / "man").exists():
|
if (self.source_root / "man").exists():
|
||||||
shutil.copytree(str(self.source_root / "man"), str(tmp_root / "man"))
|
shutil.copytree(str(self.source_root / "man"), str(tmp_root / "man"))
|
||||||
|
if (self.source_root / "completions").exists():
|
||||||
|
shutil.copytree(str(self.source_root / "completions"), str(tmp_root / "completions"))
|
||||||
|
if (self.source_root / "packaging" / "logrotate").exists():
|
||||||
|
pkg_dest = tmp_root / "packaging" / "logrotate"
|
||||||
|
pkg_dest.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copytree(str(self.source_root / "packaging" / "logrotate"), str(pkg_dest))
|
||||||
with tarfile.open(str(tarball_path), "w:gz") as tar:
|
with tarfile.open(str(tarball_path), "w:gz") as tar:
|
||||||
tar.add(str(tmp_root), arcname=f"linux-updater-{self.version}")
|
tar.add(str(tmp_root), arcname=f"linux-updater-{self.version}")
|
||||||
|
|
||||||
|
|||||||
@@ -39,4 +39,23 @@ if [ -f "${SCRIPT_DIR}/man/linux-updater.8" ]; then
|
|||||||
install -m 644 "${SCRIPT_DIR}/man/linux-updater.8" "${PREFIX}/share/man/man8/linux-updater.8"
|
install -m 644 "${SCRIPT_DIR}/man/linux-updater.8" "${PREFIX}/share/man/man8/linux-updater.8"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Install shell completions
|
||||||
|
if [ -f "${SCRIPT_DIR}/completions/bash/linux-updater" ]; then
|
||||||
|
mkdir -p "${PREFIX}/share/bash-completion/completions"
|
||||||
|
install -m 644 "${SCRIPT_DIR}/completions/bash/linux-updater" "${PREFIX}/share/bash-completion/completions/linux-updater"
|
||||||
|
fi
|
||||||
|
if [ -f "${SCRIPT_DIR}/completions/zsh/_linux-updater" ]; then
|
||||||
|
mkdir -p "${PREFIX}/share/zsh/site-functions"
|
||||||
|
install -m 644 "${SCRIPT_DIR}/completions/zsh/_linux-updater" "${PREFIX}/share/zsh/site-functions/_linux-updater"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Install logrotate configuration
|
||||||
|
if [ -f "${SCRIPT_DIR}/packaging/logrotate/linux-updater" ]; then
|
||||||
|
mkdir -p "${SYSCONFDIR}/logrotate.d"
|
||||||
|
install -m 644 "${SCRIPT_DIR}/packaging/logrotate/linux-updater" "${SYSCONFDIR}/logrotate.d/linux-updater"
|
||||||
|
elif [ -f "${SCRIPT_DIR}/logrotate/linux-updater" ]; then
|
||||||
|
mkdir -p "${SYSCONFDIR}/logrotate.d"
|
||||||
|
install -m 644 "${SCRIPT_DIR}/logrotate/linux-updater" "${SYSCONFDIR}/logrotate.d/linux-updater"
|
||||||
|
fi
|
||||||
|
|
||||||
echo "Installation complete! Run 'linux-updater --help' to verify."
|
echo "Installation complete! Run 'linux-updater --help' to verify."
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/var/log/linux-updater/*.log {
|
||||||
|
weekly
|
||||||
|
rotate 4
|
||||||
|
compress
|
||||||
|
missingok
|
||||||
|
notifempty
|
||||||
|
create 0640 root root
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
Name: linux-updater
|
Name: linux-updater
|
||||||
Version: 1.0.0
|
Version: 2.0.0
|
||||||
Release: 1%{?dist}
|
Release: 1%{?dist}
|
||||||
Summary: Unified, safe multi-distribution Linux system updater
|
Summary: Unified, safe multi-distribution Linux system updater
|
||||||
|
|
||||||
@@ -32,19 +32,56 @@ mkdir -p $RPM_BUILD_ROOT/var/log/linux-updater
|
|||||||
cp -r linux_updater $RPM_BUILD_ROOT/usr/lib/linux-updater/
|
cp -r linux_updater $RPM_BUILD_ROOT/usr/lib/linux-updater/
|
||||||
install -m 755 bin/linux-updater $RPM_BUILD_ROOT/usr/bin/linux-updater
|
install -m 755 bin/linux-updater $RPM_BUILD_ROOT/usr/bin/linux-updater
|
||||||
install -m 644 linux-updater.json.example $RPM_BUILD_ROOT/etc/linux-updater.json
|
install -m 644 linux-updater.json.example $RPM_BUILD_ROOT/etc/linux-updater.json
|
||||||
|
mkdir -p $RPM_BUILD_ROOT/etc/logrotate.d
|
||||||
|
if [ -f packaging/logrotate/linux-updater ]; then
|
||||||
|
install -m 644 packaging/logrotate/linux-updater $RPM_BUILD_ROOT/etc/logrotate.d/linux-updater
|
||||||
|
fi
|
||||||
mkdir -p $RPM_BUILD_ROOT%{_mandir}/man8
|
mkdir -p $RPM_BUILD_ROOT%{_mandir}/man8
|
||||||
if [ -f man/linux-updater.8 ]; then
|
if [ -f man/linux-updater.8 ]; then
|
||||||
install -m 644 man/linux-updater.8 $RPM_BUILD_ROOT%{_mandir}/man8/linux-updater.8
|
install -m 644 man/linux-updater.8 $RPM_BUILD_ROOT%{_mandir}/man8/linux-updater.8
|
||||||
fi
|
fi
|
||||||
|
mkdir -p $RPM_BUILD_ROOT%{_datadir}/bash-completion/completions
|
||||||
|
mkdir -p $RPM_BUILD_ROOT%{_datadir}/zsh/site-functions
|
||||||
|
if [ -f completions/bash/linux-updater ]; then
|
||||||
|
install -m 644 completions/bash/linux-updater $RPM_BUILD_ROOT%{_datadir}/bash-completion/completions/linux-updater
|
||||||
|
fi
|
||||||
|
if [ -f completions/zsh/_linux-updater ]; then
|
||||||
|
install -m 644 completions/zsh/_linux-updater $RPM_BUILD_ROOT%{_datadir}/zsh/site-functions/_linux-updater
|
||||||
|
fi
|
||||||
|
|
||||||
%files
|
%files
|
||||||
%defattr(-,root,root,-)
|
%defattr(-,root,root,-)
|
||||||
%attr(0755, root, root) /usr/bin/linux-updater
|
%attr(0755, root, root) /usr/bin/linux-updater
|
||||||
/usr/lib/linux-updater
|
/usr/lib/linux-updater
|
||||||
%config(noreplace) /etc/linux-updater.json
|
%config(noreplace) /etc/linux-updater.json
|
||||||
|
%config(noreplace) /etc/logrotate.d/linux-updater
|
||||||
%dir %attr(0750, root, root) /var/log/linux-updater
|
%dir %attr(0750, root, root) /var/log/linux-updater
|
||||||
%{_mandir}/man8/linux-updater.8*
|
%{_mandir}/man8/linux-updater.8*
|
||||||
|
%{_datadir}/bash-completion/completions/linux-updater
|
||||||
|
%{_datadir}/zsh/site-functions/_linux-updater
|
||||||
|
|
||||||
%changelog
|
%changelog
|
||||||
|
* Sat Oct 03 2026 Test Factory <admin@localhost> - 2.0.0-1
|
||||||
|
- Shell tab autocompletion for Bash and Zsh (completion subcommand and packaging integration).
|
||||||
|
- Selective package filtering with --exclude (patterns/globs) and --security updates.
|
||||||
|
- Pre-flight package database consistency inspection (check_package_db) with auto-remediation (repair_package_db).
|
||||||
|
- Optional Flatpak integration (--flatpak and update_flatpak config).
|
||||||
|
- Dedicated logrotate configuration (/etc/logrotate.d/linux-updater).
|
||||||
|
|
||||||
|
* 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.
|
||||||
+279
-1
@@ -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,236 @@ 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)
|
||||||
|
|
||||||
|
@patch("linux_updater.cli.check_root_privileges", return_value=True)
|
||||||
|
@patch("linux_updater.cli.DistroDetector.detect")
|
||||||
|
@patch("linux_updater.cli.get_manager")
|
||||||
|
@patch("shutil.which")
|
||||||
|
def test_cli_update_with_flatpak(self, mock_which, 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.is_reboot_required.return_value = RebootStatus(required=False)
|
||||||
|
mock_manager.apply_updates.return_value = CommandResult(0, "All packages upgraded", "", True)
|
||||||
|
mock_get_manager.return_value = mock_manager
|
||||||
|
|
||||||
|
def fake_which(cmd):
|
||||||
|
if cmd == "flatpak":
|
||||||
|
return "/usr/bin/flatpak"
|
||||||
|
return None
|
||||||
|
mock_which.side_effect = fake_which
|
||||||
|
|
||||||
|
with patch("linux_updater.cli.CommandRunner.run") as mock_runner_run:
|
||||||
|
mock_runner_run.return_value = CommandResult(0, "", "", True)
|
||||||
|
code = main(["-y", "update", "--flatpak"])
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
mock_runner_run.assert_called_with(["flatpak", "update", "-y"])
|
||||||
|
|
||||||
|
@patch("linux_updater.cli.check_root_privileges", return_value=True)
|
||||||
|
@patch("linux_updater.cli.DistroDetector.detect")
|
||||||
|
@patch("linux_updater.cli.get_manager")
|
||||||
|
@patch("shutil.which", return_value=None)
|
||||||
|
def test_cli_update_with_flatpak_missing_binary(self, mock_which, 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.is_reboot_required.return_value = RebootStatus(required=False)
|
||||||
|
mock_manager.apply_updates.return_value = CommandResult(0, "All packages upgraded", "", True)
|
||||||
|
mock_get_manager.return_value = mock_manager
|
||||||
|
|
||||||
|
code = main(["-y", "update", "--flatpak"])
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import io
|
||||||
|
import unittest
|
||||||
|
from contextlib import redirect_stdout
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from linux_updater.cli import create_parser, main
|
||||||
|
from linux_updater.core.completion import get_bash_completion, get_zsh_completion
|
||||||
|
|
||||||
|
|
||||||
|
class TestCompletion(unittest.TestCase):
|
||||||
|
def test_bash_completion_content(self):
|
||||||
|
content = get_bash_completion()
|
||||||
|
self.assertIn("complete -F _linux_updater linux-updater", content)
|
||||||
|
self.assertIn("update check release-upgrade clean health completion", content)
|
||||||
|
self.assertIn("--packages", content)
|
||||||
|
self.assertIn("--exclude", content)
|
||||||
|
self.assertIn("--security", content)
|
||||||
|
self.assertIn("--flatpak", content)
|
||||||
|
|
||||||
|
def test_zsh_completion_content(self):
|
||||||
|
content = get_zsh_completion()
|
||||||
|
self.assertIn("#compdef linux-updater", content)
|
||||||
|
self.assertIn("_linux_updater", content)
|
||||||
|
self.assertIn("update:Inspect health", content)
|
||||||
|
self.assertIn("completion:Generate shell autocompletion script", content)
|
||||||
|
|
||||||
|
def test_cli_completion_bash_runs_without_root_or_lock(self):
|
||||||
|
f = io.StringIO()
|
||||||
|
with redirect_stdout(f):
|
||||||
|
exit_code = main(["completion", "bash"])
|
||||||
|
self.assertEqual(exit_code, 0)
|
||||||
|
output = f.getvalue()
|
||||||
|
self.assertIn("complete -F _linux_updater linux-updater", output)
|
||||||
|
|
||||||
|
def test_cli_completion_zsh_runs_without_root_or_lock(self):
|
||||||
|
f = io.StringIO()
|
||||||
|
with redirect_stdout(f):
|
||||||
|
exit_code = main(["completion", "zsh"])
|
||||||
|
self.assertEqual(exit_code, 0)
|
||||||
|
output = f.getvalue()
|
||||||
|
self.assertIn("#compdef linux-updater", output)
|
||||||
|
|
||||||
|
def test_static_completion_files_exist(self):
|
||||||
|
root_dir = Path(__file__).resolve().parent.parent
|
||||||
|
bash_file = root_dir / "completions" / "bash" / "linux-updater"
|
||||||
|
zsh_file = root_dir / "completions" / "zsh" / "_linux-updater"
|
||||||
|
|
||||||
|
self.assertTrue(bash_file.exists(), f"Missing {bash_file}")
|
||||||
|
self.assertTrue(zsh_file.exists(), f"Missing {zsh_file}")
|
||||||
|
|
||||||
|
self.assertEqual(bash_file.read_text(encoding="utf-8").strip(), get_bash_completion().strip())
|
||||||
|
self.assertEqual(zsh_file.read_text(encoding="utf-8").strip(), get_zsh_completion().strip())
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import unittest
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
from linux_updater.managers.apt import AptManager
|
||||||
|
from linux_updater.managers.dnf import DnfManager
|
||||||
|
from linux_updater.managers.pacman import PacmanManager
|
||||||
|
from linux_updater.models import CommandResult, PackageUpdate
|
||||||
|
|
||||||
|
|
||||||
|
class TestFiltering(unittest.TestCase):
|
||||||
|
def test_apt_exclude_filtering(self):
|
||||||
|
mock_runner = MagicMock()
|
||||||
|
mock_runner.run.return_value = CommandResult(
|
||||||
|
return_code=0,
|
||||||
|
stdout=(
|
||||||
|
"Inst nginx [1.18.0] (1.20.0 Ubuntu:24.04/noble-updates [amd64])\n"
|
||||||
|
"Inst linux-image-generic [5.15.0] (5.15.1 Ubuntu:24.04/noble-updates [amd64])\n"
|
||||||
|
"Inst curl [7.81.0] (7.82.0 Ubuntu:24.04/noble-updates [amd64])\n"
|
||||||
|
),
|
||||||
|
stderr="",
|
||||||
|
success=True,
|
||||||
|
)
|
||||||
|
apt = AptManager(runner=mock_runner)
|
||||||
|
updates = apt.check_updates(exclude=["linux-image-*", "curl"])
|
||||||
|
self.assertEqual(len(updates), 1)
|
||||||
|
self.assertEqual(updates[0].package, "nginx")
|
||||||
|
|
||||||
|
def test_apt_security_only_filtering(self):
|
||||||
|
mock_runner = MagicMock()
|
||||||
|
mock_runner.run.return_value = CommandResult(
|
||||||
|
return_code=0,
|
||||||
|
stdout=(
|
||||||
|
"Inst nginx [1.18.0] (1.20.0 Ubuntu:24.04/noble-updates [amd64])\n"
|
||||||
|
"Inst openssl [3.0.2] (3.0.3 Ubuntu:24.04/noble-security [amd64])\n"
|
||||||
|
),
|
||||||
|
stderr="",
|
||||||
|
success=True,
|
||||||
|
)
|
||||||
|
apt = AptManager(runner=mock_runner)
|
||||||
|
updates = apt.check_updates(security_only=True)
|
||||||
|
self.assertEqual(len(updates), 1)
|
||||||
|
self.assertEqual(updates[0].package, "openssl")
|
||||||
|
|
||||||
|
def test_dnf_exclude_arguments(self):
|
||||||
|
mock_runner = MagicMock()
|
||||||
|
mock_runner.run.return_value = CommandResult(return_code=0, stdout="", stderr="", success=True)
|
||||||
|
dnf = DnfManager(runner=mock_runner, binary="dnf")
|
||||||
|
|
||||||
|
dnf.apply_updates(exclude=["kernel*", "redis*"])
|
||||||
|
cmd = mock_runner.run.call_args[0][0]
|
||||||
|
self.assertIn("-x", cmd)
|
||||||
|
self.assertIn("kernel*", cmd)
|
||||||
|
self.assertIn("redis*", cmd)
|
||||||
|
|
||||||
|
def test_dnf_security_only_arguments(self):
|
||||||
|
mock_runner = MagicMock()
|
||||||
|
mock_runner.run.return_value = CommandResult(return_code=0, stdout="", stderr="", success=True)
|
||||||
|
dnf = DnfManager(runner=mock_runner, binary="dnf")
|
||||||
|
|
||||||
|
dnf.apply_updates(security_only=True)
|
||||||
|
cmd = mock_runner.run.call_args[0][0]
|
||||||
|
self.assertIn("--security", cmd)
|
||||||
|
|
||||||
|
def test_pacman_exclude_arguments(self):
|
||||||
|
mock_runner = MagicMock()
|
||||||
|
mock_runner.run.return_value = CommandResult(return_code=0, stdout="", stderr="", success=True)
|
||||||
|
pacman = PacmanManager(runner=mock_runner)
|
||||||
|
|
||||||
|
pacman.apply_updates(exclude=["linux", "systemd"])
|
||||||
|
cmd = mock_runner.run.call_args[0][0]
|
||||||
|
self.assertIn("--ignore", cmd)
|
||||||
|
self.assertIn("linux,systemd", cmd)
|
||||||
+17
-1
@@ -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(
|
||||||
|
|||||||
+10
-2
@@ -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="2.0.0")
|
||||||
|
|
||||||
def tearDown(self):
|
def tearDown(self):
|
||||||
self.temp_dir.cleanup()
|
self.temp_dir.cleanup()
|
||||||
@@ -29,6 +35,7 @@ class TestPackaging(unittest.TestCase):
|
|||||||
self.assertTrue(any("linux_updater/__init__.py" in n for n in names))
|
self.assertTrue(any("linux_updater/__init__.py" in n for n in names))
|
||||||
self.assertTrue(any("linux-updater.json.example" in n for n in names))
|
self.assertTrue(any("linux-updater.json.example" in n for n in names))
|
||||||
self.assertTrue(any("linux-updater.8" in n for n in names))
|
self.assertTrue(any("linux-updater.8" in n for n in names))
|
||||||
|
self.assertTrue(any("logrotate" in n for n in names))
|
||||||
|
|
||||||
def test_build_deb_creates_package_or_tree(self):
|
def test_build_deb_creates_package_or_tree(self):
|
||||||
deb_path = self.builder.build_deb()
|
deb_path = self.builder.build_deb()
|
||||||
@@ -49,6 +56,7 @@ class TestPackaging(unittest.TestCase):
|
|||||||
self.assertIn("Name: linux-updater", content)
|
self.assertIn("Name: linux-updater", content)
|
||||||
self.assertIn("Requires: python3 >= 3.6", content)
|
self.assertIn("Requires: python3 >= 3.6", content)
|
||||||
self.assertIn("BuildArch: noarch", content)
|
self.assertIn("BuildArch: noarch", content)
|
||||||
|
self.assertIn("/etc/logrotate.d/linux-updater", content)
|
||||||
|
|
||||||
def test_build_all(self):
|
def test_build_all(self):
|
||||||
results = self.builder.build_all()
|
results = self.builder.build_all()
|
||||||
|
|||||||
@@ -51,15 +51,20 @@ class TestRemediationEngine(unittest.TestCase):
|
|||||||
if lock_p.exists():
|
if lock_p.exists():
|
||||||
lock_p.unlink()
|
lock_p.unlink()
|
||||||
|
|
||||||
def test_remediate_refuses_non_remediable(self):
|
def test_remediate_repair_package_db(self):
|
||||||
check = CheckResult(
|
check = CheckResult(
|
||||||
name="disk_boot",
|
name="package_db",
|
||||||
status=CheckStatus.FAIL,
|
status=CheckStatus.FAIL,
|
||||||
message="/boot is full",
|
message="Unconfigured packages detected",
|
||||||
can_remediate=False,
|
can_remediate=True,
|
||||||
|
remediation_id="repair_package_db",
|
||||||
)
|
)
|
||||||
self.assertFalse(self.engine.can_remediate(check))
|
self.assertTrue(self.engine.can_remediate(check))
|
||||||
self.assertFalse(self.engine.remediate(check))
|
self.mock_manager.repair_db.return_value = MagicMock(success=True)
|
||||||
|
success = self.engine.remediate(check)
|
||||||
|
self.assertTrue(success)
|
||||||
|
self.mock_manager.repair_db.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in new issue
Block a user