9 Commits
Author SHA1 Message Date
soda64 97c6ac2ab9 docs: document Gitea package registry client config and CI/CD workflow
Build and Publish Release / Build Packages and Publish (push) Successful in 26s
2026-10-03 08:34:44 +02:00
soda64 8bec4ed932 feat: release v2.0.0 with tab completion, package filtering, db health checks, flatpak and logrotate
Build and Publish Release / Build Packages and Publish (push) Successful in 27s
2026-10-03 08:31:00 +02:00
soda64 8d4157b42d feat(ci): automatically link published packages to repository in Gitea
Build and Publish Release / Build Packages and Publish (push) Successful in 15s
2026-10-02 20:12:37 +02:00
soda64 57f49822bb feat(ci): use secrets.PACKAGES_GENERATION for Gitea Package Registry
Build and Publish Release / Build Packages and Publish (push) Successful in 15s
2026-10-02 20:06:16 +02:00
soda64 d5cf44cb57 fix(ci): purge stale release assets before attaching fresh binaries for idempotency
Build and Publish Release / Build Packages and Publish (push) Successful in 15s
2026-10-02 19:58:44 +02:00
soda64 63120e4793 fix(ci): restrict release asset attachments to binary packages only
Build and Publish Release / Build Packages and Publish (push) Successful in 14s
2026-10-02 19:57:43 +02:00
soda64 0bc914ac8a fix(ci): import build_packages via path in tests and enhance release workflow
Build and Publish Release / Build Packages and Publish (push) Successful in 16s
2026-10-02 19:51:40 +02:00
soda64 8921c2da13 feat(ci): add Gitea Actions release workflow and bump version to 1.3.0
Build and Publish Release / Build Packages and Publish (push) Failing after 52s
2026-10-02 19:48:20 +02:00
soda64 ab50abe0c0 chore(release): bump version to 1.2.0, update CLI help examples and documentation 2026-10-02 19:34:36 +02:00
28 changed files with 1351 additions and 80 deletions

No files matched your search

+148
View File
@@ -0,0 +1,148 @@
name: Build and Publish Release
on:
push:
tags:
- 'v*'
workflow_dispatch:
jobs:
release:
name: Build Packages and Publish
runs-on: fedora
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
- name: Verify Build Environment
run: |
echo "=== Runner System Info ==="
uname -a
python3 --version
if ! command -v rpmbuild &>/dev/null; then
echo "Installing rpm-build..."
sudo dnf install -y rpm-build
else
echo "rpmbuild is already available: $(which rpmbuild)"
fi
- name: Run Test Suite
run: |
echo "=== Running Unit Tests ==="
python3 -m unittest discover tests
- name: Build Distribution Packages
run: |
echo "=== Building Packages (.rpm, .deb, .tar.gz) ==="
python3 packaging/build_packages.py
echo "=== Built Artifacts ==="
ls -lh dist/*.tar.gz dist/*.deb 2>/dev/null || true
ls -lh dist/rpm/RPMS/*/*.rpm 2>/dev/null || true
- name: Publish to Gitea Package Registry
env:
PKG_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }}
run: |
echo "=== Publishing to Gitea Package Registry ==="
RPM_FILE=$(find dist/rpm/RPMS -name "*.rpm" 2>/dev/null | head -n 1)
DEB_FILE=$(ls dist/*.deb 2>/dev/null | head -n 1)
if [ -n "$RPM_FILE" ] && [ -f "$RPM_FILE" ]; then
echo "Uploading RPM: $RPM_FILE"
HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" -X PUT \
-u "${{ github.actor }}:${PKG_TOKEN}" \
--upload-file "$RPM_FILE" \
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/rpm/upload")
echo "RPM Registry HTTP status: $HTTP_CODE"
fi
if [ -n "$DEB_FILE" ] && [ -f "$DEB_FILE" ]; then
echo "Uploading DEB: $DEB_FILE"
HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" -X PUT \
-u "${{ github.actor }}:${PKG_TOKEN}" \
--upload-file "$DEB_FILE" \
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/debian/pool/stable/main/upload")
echo "Debian Registry HTTP status: $HTTP_CODE"
fi
# Link packages to this repository in Gitea
REPO_NAME=$(basename "${{ github.repository }}")
echo "Linking RPM package 'linux-updater' to repository ${REPO_NAME}..."
LINK_RPM=$(curl -k -s -w " (HTTP %{http_code})" -X POST \
-H "Authorization: token ${PKG_TOKEN}" \
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/rpm/linux-updater/-/link/${REPO_NAME}")
echo "RPM link result: $LINK_RPM"
echo "Linking Debian package 'linux-updater' to repository ${REPO_NAME}..."
LINK_DEB=$(curl -k -s -w " (HTTP %{http_code})" -X POST \
-H "Authorization: token ${PKG_TOKEN}" \
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/debian/linux-updater/-/link/${REPO_NAME}")
echo "Debian link result: $LINK_DEB"
- name: Attach Artifacts to Gitea Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SERVER_URL: ${{ github.server_url }}
REPO: ${{ github.repository }}
TAG_REF: ${{ github.ref_name }}
run: |
echo "=== Attaching Assets to Release ==="
# Determine tag name (default to package version if workflow_dispatch on branch)
TAG="${TAG_REF}"
if [[ "$TAG" == "main" || "$TAG" == "" ]]; then
VER=$(python3 -c "import linux_updater; print(linux_updater.__version__)")
TAG="v${VER}"
fi
echo "Target Release Tag: $TAG"
# 1. Fetch release ID or create release if missing
REL_JSON=$(curl -k -s -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/tags/${TAG}")
REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$REL_JSON" 2>/dev/null || true)
if [ -z "$REL_ID" ]; then
echo "Release $TAG does not exist yet. Creating release..."
CREATE_DATA=$(python3 -c "import sys, json; print(json.dumps({'tag_name': sys.argv[1], 'name': 'Release ' + sys.argv[1], 'body': 'Automated build and release for ' + sys.argv[1]}))" "$TAG")
CREATE_RESP=$(curl -k -s -X POST \
-H "Authorization: token ${GITHUB_TOKEN}" \
-H "Content-Type: application/json" \
-d "$CREATE_DATA" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases")
REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$CREATE_RESP" 2>/dev/null || true)
echo "Create release response: $CREATE_RESP"
fi
echo "Release ID: $REL_ID"
if [ -n "$REL_ID" ]; then
# Clean up any existing assets for this release (ensures idempotency on re-runs)
EXISTING_ASSETS=$(curl -k -s -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets" || true)
ASSET_IDS=$(python3 -c "import sys, json; print(' '.join(str(a['id']) for a in json.loads(sys.argv[1])))" "$EXISTING_ASSETS" 2>/dev/null || true)
for aid in $ASSET_IDS; do
echo "Removing previous asset ID $aid..."
curl -k -s -X DELETE -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets/${aid}" || true
done
# Target only user-facing binaries (exclude internal rpm SOURCES and SRPMS)
ASSET_FILES=(
$(ls dist/*.tar.gz 2>/dev/null || true)
$(ls dist/*.deb 2>/dev/null || true)
$(ls dist/rpm/RPMS/*/*.rpm 2>/dev/null || true)
)
for f in "${ASSET_FILES[@]}"; do
if [ -f "$f" ]; then
fname=$(basename "$f")
echo "Uploading asset $fname from $f..."
curl -k -s -X POST \
-H "Authorization: token ${GITHUB_TOKEN}" \
-F "attachment=@${f}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets?name=${fname}" || echo "Asset upload note: $?"
fi
done
echo "Artifacts successfully attached to release $TAG!"
else
echo "Could not obtain release ID, skipping asset attachment."
fi
+49 -22
View File
@@ -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.1.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.1.0.tar.gz tar -xzf dist/linux-updater-2.0.0.tar.gz
cd linux-updater-1.1.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`).
--- ---
+72
View File
@@ -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
+76
View File
@@ -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
View File
@@ -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
View File
@@ -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.1.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.1.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.1.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.
+68 -9
View File
@@ -27,7 +27,7 @@ linux-updater health
**Example Output:** **Example Output:**
```text ```text
Linux System Updater v1.1.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.1.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 -1
View File
@@ -1,4 +1,4 @@
"""Linux System Updater - Multi-distribution system updater and health checker.""" """Linux System Updater - Multi-distribution system updater and health checker."""
__version__ = "1.1.0" __version__ = "2.0.0"
__author__ = "Test Factory" __author__ = "Test Factory"
+108 -5
View File
@@ -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
@@ -74,8 +75,10 @@ Examples:
linux-updater check # Check for available updates without applying linux-updater check # Check for available updates without applying
sudo linux-updater update # Update system packages interactively sudo linux-updater update # Update system packages interactively
sudo linux-updater update -y # Non-interactive automated update 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 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 # 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 sudo linux-updater clean --all # Clean package cache and unused dependencies
Subcommand Help: Subcommand Help:
@@ -103,6 +106,7 @@ Subcommand Help:
Examples: Examples:
sudo linux-updater update sudo linux-updater update
sudo linux-updater update -y sudo linux-updater update -y
sudo linux-updater update -y --reboot
sudo linux-updater update --dry-run sudo linux-updater update --dry-run
sudo linux-updater update --packages nginx redis sudo linux-updater update --packages nginx redis
""", """,
@@ -113,9 +117,25 @@ Examples:
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.",
@@ -125,8 +145,21 @@ Examples:
Examples: Examples:
linux-updater check linux-updater check
linux-updater check --json 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
release_parser = subparsers.add_parser( release_parser = subparsers.add_parser(
@@ -142,6 +175,7 @@ Target Release Specification:
Examples: Examples:
sudo linux-updater release-upgrade -t 44 # Fedora: upgrade to version 44 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 --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 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 9 # AlmaLinux / Rocky: upgrade to EL 9
@@ -189,6 +223,33 @@ Examples:
""", """,
) )
# 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
@@ -258,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"
@@ -440,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}")
@@ -459,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}")
@@ -494,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,
) )
@@ -505,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...")
+13 -1
View File
@@ -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:
@@ -15,6 +15,9 @@ class UpdaterConfig:
check_ac_power: bool = True, check_ac_power: bool = True,
clean_after_update: bool = False, clean_after_update: bool = False,
auto_reboot: 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,
@@ -28,6 +31,9 @@ class UpdaterConfig:
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.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
@@ -60,6 +66,9 @@ class UpdaterConfig:
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), 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),
@@ -79,6 +88,9 @@ class UpdaterConfig:
"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, "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,
+163
View File
@@ -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"
+32
View File
@@ -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)
+12 -1
View File
@@ -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()
+47 -8
View File
@@ -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
@@ -27,39 +27,67 @@ class AptManager(PackageManager):
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"])
@@ -127,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))
+16 -2
View File
@@ -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 -1
View File
@@ -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,6 +65,8 @@ 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:
@@ -65,6 +76,13 @@ class DnfManager(PackageManager):
else: 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)
@@ -412,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"])
+37 -4
View File
@@ -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,22 +58,32 @@ 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 dry_run: if dry_run:
cmd.append("-p") cmd.append("-p")
else: else:
cmd.append("--noconfirm") cmd.append("--noconfirm")
cmd.extend(packages) if exclude:
cmd.extend(["--ignore", ",".join(exclude)])
cmd.extend(target_pkgs)
else: else:
cmd = ["pacman", "-Su"] cmd = ["pacman", "-Su"]
if dry_run: if dry_run:
cmd.append("-p") cmd.append("-p")
else: else:
cmd.append("--noconfirm") cmd.append("--noconfirm")
if exclude:
cmd.extend(["--ignore", ",".join(exclude)])
return self.runner.run(cmd, stream=not dry_run) return self.runner.run(cmd, stream=not dry_run)
@@ -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)
+48 -6
View File
@@ -1,4 +1,4 @@
.TH LINUX-UPDATER 8 "October 2026" "linux-updater 1.1.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,20 +24,22 @@ 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|\fB\-\-releasever \fITARGET\fR] .B release\-upgrade \fR[\fB\-t \fITARGET\fR|\fB\-\-target\-release \fITARGET\fR|\fB\-\-releasever \fITARGET\fR]
@@ -47,6 +50,9 @@ Cleans the local package cache. When \fB\-\-all\fR is given, also removes unused
.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),
+39 -1
View File
@@ -67,7 +67,7 @@ class PackageBuilder:
self, self,
source_root: Optional[Path] = None, source_root: Optional[Path] = None,
output_dir: Optional[Path] = None, output_dir: Optional[Path] = None,
version: str = "1.1.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"
@@ -211,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}")
+19
View File
@@ -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."
+8
View File
@@ -0,0 +1,8 @@
/var/log/linux-updater/*.log {
weekly
rotate 4
compress
missingok
notifempty
create 0640 root root
}
+31 -1
View File
@@ -1,5 +1,5 @@
Name: linux-updater Name: linux-updater
Version: 1.1.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,20 +32,50 @@ 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 * Fri Oct 02 2026 Test Factory <admin@localhost> - 1.1.0-1
- Real-time download/transaction streaming without stdin hangs. - Real-time download/transaction streaming without stdin hangs.
- Automated and interactive reboot support (--reboot and [y/N] prompt). - Automated and interactive reboot support (--reboot and [y/N] prompt).
+49
View File
@@ -464,6 +464,55 @@ class TestCLIIntegration(unittest.TestCase):
res = trigger_system_reboot("arch", is_release_upgrade=False, runner=mock_runner) res = trigger_system_reboot("arch", is_release_upgrade=False, runner=mock_runner)
self.assertFalse(res) 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()
+52
View File
@@ -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())
+72
View File
@@ -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)
+10 -2
View File
@@ -4,15 +4,21 @@ import tempfile
import unittest import unittest
from pathlib import Path from pathlib import Path
from packaging.build_packages import PackageBuilder import importlib.util
_root_dir = Path(__file__).resolve().parent.parent
_pkg_script = _root_dir / "packaging" / "build_packages.py"
_spec = importlib.util.spec_from_file_location("build_packages", str(_pkg_script))
_module = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_module)
PackageBuilder = _module.PackageBuilder
class TestPackaging(unittest.TestCase): class TestPackaging(unittest.TestCase):
def setUp(self): def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory() self.temp_dir = tempfile.TemporaryDirectory()
self.out_dir = Path(self.temp_dir.name) self.out_dir = Path(self.temp_dir.name)
self.root_dir = Path(__file__).resolve().parent.parent self.root_dir = Path(__file__).resolve().parent.parent
self.builder = PackageBuilder(source_root=self.root_dir, output_dir=self.out_dir, version="1.1.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()
+11 -6
View File
@@ -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__":