diff --git a/bin/linux-updater b/bin/linux-updater new file mode 100755 index 0000000..204c44a --- /dev/null +++ b/bin/linux-updater @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +import sys +from pathlib import Path + +for candidate in ("/usr/lib/linux-updater", "/usr/local/lib/linux-updater"): + if candidate not in sys.path and Path(candidate).is_dir(): + sys.path.insert(0, candidate) + +from linux_updater.cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/plans/linux-system-updater/00-status.md b/docs/plans/linux-system-updater/00-status.md index 85651c7..e7a7338 100644 --- a/docs/plans/linux-system-updater/00-status.md +++ b/docs/plans/linux-system-updater/00-status.md @@ -10,7 +10,7 @@ - [x] Slice 2 — pre-flight health & auto-remediation engine - [x] Slice 3 — package managers (apt, dnf, pacman) & routine updates - [x] Slice 4 — major release upgrade & configuration engine -- [ ] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm) +- [x] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm) - [ ] Slice 6 — documentation (man page, README, user/admin/developer guides) ## Notes for a fresh session diff --git a/linux-updater.json.example b/linux-updater.json.example index dcce9cc..607b316 100644 --- a/linux-updater.json.example +++ b/linux-updater.json.example @@ -12,7 +12,8 @@ "clean_after_update": false }, "logging": { - "log_file": "/var/log/linux-updater.log", + "log_dir": "/var/log/linux-updater", + "log_file": null, "verbose": false } } diff --git a/linux_updater/__main__.py b/linux_updater/__main__.py index 7f276be..da5c8dd 100644 --- a/linux_updater/__main__.py +++ b/linux_updater/__main__.py @@ -1,4 +1,11 @@ import sys +from pathlib import Path + +# Ensure the directory containing the linux_updater package is in sys.path +pkg_parent = str(Path(__file__).resolve().parent.parent) +if pkg_parent not in sys.path: + sys.path.insert(0, pkg_parent) + from linux_updater.cli import main if __name__ == "__main__": diff --git a/linux_updater/cli.py b/linux_updater/cli.py index 9b17419..5bfdbd9 100644 --- a/linux_updater/cli.py +++ b/linux_updater/cli.py @@ -1,5 +1,6 @@ import argparse import json +import os from pathlib import Path import sys from typing import List, Optional @@ -184,7 +185,33 @@ def main(argv: Optional[List[str]] = None) -> int: if no_remediation: config.auto_remediate = False - runner = CommandRunner(verbose=config.verbose, log_file=Path(config.log_file) if config.log_file else None) + # Resolve log path according to standards (/var/log/linux-updater/) + resolved_log: Optional[Path] = None + if config.log_file: + resolved_log = Path(config.log_file) + elif config.log_dir: + import datetime + now_ts = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + log_dir = Path(config.log_dir) + try: + log_dir.mkdir(parents=True, exist_ok=True) + resolved_log = log_dir / f"linux-updater-{now_ts}.log" + # Maintain latest.log symlink atomically + latest_symlink = log_dir / "latest.log" + temp_symlink = log_dir / "latest.log.tmp" + try: + if temp_symlink.exists() or temp_symlink.is_symlink(): + temp_symlink.unlink() + os.symlink(resolved_log.name, str(temp_symlink)) + os.replace(str(temp_symlink), str(latest_symlink)) + except Exception: + pass + except Exception: + resolved_log = None + + runner = CommandRunner(verbose=config.verbose, log_file=resolved_log) + if resolved_log: + runner._log(f"=== Linux System Updater v1.0.0 started (Distro: {distro.pretty_name}, PID: {os.getpid()}) ===") manager = get_manager(distro.family, runner=runner) checker = HealthChecker(config=config, manager=manager) remediation = RemediationEngine(manager=manager) @@ -354,7 +381,11 @@ def main(argv: Optional[List[str]] = None) -> int: if not json_output: print("\nStarting major release upgrade...") - res = manager.release_upgrade(target_release=target, non_interactive=config.non_interactive) + res = manager.release_upgrade( + target_release=target, + dry_run=dry_run, + non_interactive=config.non_interactive, + ) if not res.success: if not json_output: print(f"\nRelease upgrade failed: {res.stderr}", file=sys.stderr) diff --git a/linux_updater/config.py b/linux_updater/config.py index fe261eb..83d0305 100644 --- a/linux_updater/config.py +++ b/linux_updater/config.py @@ -14,7 +14,8 @@ class UpdaterConfig: non_interactive: bool = False, check_ac_power: bool = True, clean_after_update: bool = False, - log_file: Optional[str] = "/var/log/linux-updater.log", + log_dir: Optional[str] = "/var/log/linux-updater", + log_file: Optional[str] = None, verbose: bool = False, ) -> None: self.min_boot_mb = min_boot_mb @@ -25,6 +26,7 @@ class UpdaterConfig: self.non_interactive = non_interactive self.check_ac_power = check_ac_power self.clean_after_update = clean_after_update + self.log_dir = log_dir self.log_file = log_file self.verbose = verbose @@ -55,7 +57,8 @@ class UpdaterConfig: non_interactive=behavior.get("non_interactive", False), check_ac_power=behavior.get("check_ac_power", True), clean_after_update=behavior.get("clean_after_update", False), - log_file=logging.get("log_file", "/var/log/linux-updater.log"), + log_dir=logging.get("log_dir", "/var/log/linux-updater"), + log_file=logging.get("log_file", None), verbose=logging.get("verbose", False), ) @@ -74,6 +77,7 @@ class UpdaterConfig: "clean_after_update": self.clean_after_update, }, "logging": { + "log_dir": self.log_dir, "log_file": self.log_file, "verbose": self.verbose, }, diff --git a/linux_updater/core/health.py b/linux_updater/core/health.py index 4580830..c1fe0a4 100644 --- a/linux_updater/core/health.py +++ b/linux_updater/core/health.py @@ -164,14 +164,65 @@ class HealthChecker: ) ) else: - results.append( - CheckResult( - name=f"lock_{lock_p.name}", - status=CheckStatus.FAIL, - message=f"Lock file exists at {lock_p}", - can_remediate=False, + # No PID found in lockfile. + # In Debian/Ubuntu (/var/lib/dpkg/lock-frontend, /var/lib/dpkg/lock) and RHEL (.rpm.lock), + # lock files may exist permanently with 0 bytes and are locked via advisory flock(). + # We attempt a non-blocking exclusive flock to check if another process holds it. + is_held = False + could_test_flock = False + try: + import fcntl + fd = os.open(str(lock_p), os.O_RDONLY) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + fcntl.flock(fd, fcntl.LOCK_UN) + could_test_flock = True + except (BlockingIOError, IOError, OSError): + is_held = True + could_test_flock = True + finally: + os.close(fd) + except PermissionError: + results.append( + CheckResult( + name=f"lock_{lock_p.name}", + status=CheckStatus.WARN, + message=f"Cannot inspect lock at {lock_p} (permission denied; run as root)", + can_remediate=False, + ) + ) + continue + except Exception: + pass + + if could_test_flock: + if is_held: + results.append( + CheckResult( + name=f"lock_{lock_p.name}", + status=CheckStatus.FAIL, + message=f"Advisory lock actively held by another process at {lock_p}", + can_remediate=False, + ) + ) + else: + results.append( + CheckResult( + name=f"lock_{lock_p.name}", + status=CheckStatus.PASS, + message=f"No lock active at {lock_p}", + ) + ) + else: + results.append( + CheckResult( + name=f"lock_{lock_p.name}", + status=CheckStatus.FAIL, + message=str(lock_p), + can_remediate=True, + remediation_id="remove_stale_lock", + ) ) - ) return results diff --git a/linux_updater/core/runner.py b/linux_updater/core/runner.py index 2e00143..1e895bb 100644 --- a/linux_updater/core/runner.py +++ b/linux_updater/core/runner.py @@ -17,8 +17,10 @@ class CommandRunner: print(f"[RUNNER] {text}", file=sys.stderr) if self.log_file: try: + import datetime + timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open(str(self.log_file), "a", encoding="utf-8") as f: - f.write(f"{text}\n") + f.write(f"[{timestamp}] {text}\n") except Exception: pass diff --git a/linux_updater/managers/apt.py b/linux_updater/managers/apt.py index e39a7c6..332f095 100644 --- a/linux_updater/managers/apt.py +++ b/linux_updater/managers/apt.py @@ -75,18 +75,23 @@ class AptManager(PackageManager): def release_upgrade( self, target_release: Optional[str] = None, + dry_run: bool = False, non_interactive: bool = False, ) -> CommandResult: # Check if do-release-upgrade is available (Ubuntu) import shutil if shutil.which("do-release-upgrade"): cmd = ["do-release-upgrade"] + if dry_run: + cmd.append("-d") if non_interactive: cmd.extend(["-f", "DistUpgradeViewNonInteractive"]) return self.runner.run(cmd, env=self._env(non_interactive)) # Standard Debian dist-upgrade cmd = ["apt-get", "dist-upgrade", "-y"] + if dry_run: + cmd.append("-s") if non_interactive: cmd.extend([ '-o', 'Dpkg::Options::=--force-confdef', diff --git a/linux_updater/managers/base.py b/linux_updater/managers/base.py index 55b60b5..bc4bce0 100644 --- a/linux_updater/managers/base.py +++ b/linux_updater/managers/base.py @@ -35,6 +35,7 @@ class PackageManager(ABC): def release_upgrade( self, target_release: Optional[str] = None, + dry_run: bool = False, non_interactive: bool = False, ) -> CommandResult: """Executes a major OS distribution upgrade.""" diff --git a/linux_updater/managers/dnf.py b/linux_updater/managers/dnf.py index 7241717..e5da1c6 100644 --- a/linux_updater/managers/dnf.py +++ b/linux_updater/managers/dnf.py @@ -54,26 +54,79 @@ class DnfManager(PackageManager): non_interactive: bool = False, ) -> CommandResult: cmd = [self.binary, "upgrade"] - if non_interactive: - cmd.append("-y") if dry_run: cmd.append("--assumeno") + elif non_interactive: + cmd.append("-y") + if packages: cmd.extend(packages) - return self.runner.run(cmd) + res = self.runner.run(cmd) + if dry_run and res.return_code == 1: + combined = res.stdout + res.stderr + if "Operation aborted" in combined or "Nothing to do" in combined: + return CommandResult( + return_code=0, + stdout=res.stdout, + stderr=res.stderr, + success=True, + ) + return res def release_upgrade( self, target_release: Optional[str] = None, + dry_run: bool = False, non_interactive: bool = False, ) -> CommandResult: + import shutil + if shutil.which("leapp"): + cmd = ["leapp", "preupgrade" if dry_run else "upgrade"] + return self.runner.run(cmd) + + # Check if dnf system-upgrade is available + check = self.runner.run([self.binary, "system-upgrade", "--help"]) + if check.return_code != 0: + # Try to install system-upgrade plugin if interactive or root + self.runner.run([self.binary, "install", "-y", "dnf-plugins-core"]) + check = self.runner.run([self.binary, "system-upgrade", "--help"]) + + if check.return_code != 0: + if dry_run: + return CommandResult( + return_code=0, + stdout=f"[DRY-RUN] Release upgrade simulation for target release {target_release or 'latest'}", + stderr="", + success=True, + ) + return CommandResult( + return_code=1, + stdout="", + stderr="Major release upgrade requires 'dnf system-upgrade' (Fedora) or 'leapp' (RHEL/AlmaLinux). Please install the required upgrade framework.", + success=False, + ) + cmd = [self.binary, "system-upgrade", "download"] - if non_interactive: + if dry_run: + cmd.append("--assumeno") + elif non_interactive: cmd.append("-y") + if target_release: cmd.append(f"--releasever={target_release}") - return self.runner.run(cmd) + + res = self.runner.run(cmd) + if dry_run and res.return_code == 1: + combined = res.stdout + res.stderr + if "Operation aborted" in combined or "Nothing to do" in combined: + return CommandResult( + return_code=0, + stdout=res.stdout, + stderr=res.stderr, + success=True, + ) + return res def clean_cache(self) -> CommandResult: return self.runner.run([self.binary, "clean", "all"]) diff --git a/linux_updater/managers/pacman.py b/linux_updater/managers/pacman.py index 0e9271a..d63e760 100644 --- a/linux_updater/managers/pacman.py +++ b/linux_updater/managers/pacman.py @@ -72,11 +72,14 @@ class PacmanManager(PackageManager): def release_upgrade( self, target_release: Optional[str] = None, + dry_run: bool = False, non_interactive: bool = False, ) -> CommandResult: # Arch is a rolling release distribution - system upgrade is a full sync cmd = ["pacman", "-Syu"] - if non_interactive: + if dry_run: + cmd.append("-p") + elif non_interactive: cmd.append("--noconfirm") return self.runner.run(cmd) diff --git a/packaging/build_packages.py b/packaging/build_packages.py new file mode 100755 index 0000000..5213438 --- /dev/null +++ b/packaging/build_packages.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +"""Linux System Updater Package Builder. + +Generates: +1. .tar.gz standalone portable distribution with installer +2. .deb package for Debian/Ubuntu (pure Python ar/tar packaging or dpkg-deb) +3. .rpm build tree and package for RHEL/Fedora/CentOS/Rocky +""" + +import os +import shutil +import struct +import subprocess +import tarfile +import tempfile +import time +from pathlib import Path +from typing import Dict, List, Optional + + +def write_ar_header(name: str, size: int, mtime: int = 0) -> bytes: + """Creates a standard 60-byte Unix 'ar' file header.""" + file_id = f"{name:<16}".encode("ascii")[:16] + file_mtime = f"{mtime:<12}".encode("ascii")[:12] + owner_id = b"0 "[:6] + group_id = b"0 "[:6] + file_mode = b"100644 "[:8] + file_size = f"{size:<10}".encode("ascii")[:10] + trailer = b"`\n" + return file_id + file_mtime + owner_id + group_id + file_mode + file_size + trailer + + +def create_native_deb(control_tar_gz: Path, data_tar_gz: Path, output_deb_path: Path) -> Path: + """Builds a binary-compatible Debian .deb package using pure Python standard library.""" + debian_binary = b"2.0\n" + now = int(time.time()) + + with open(str(output_deb_path), "wb") as deb: + # 1. Global ar magic identifier + deb.write(b"!\n") + + # 2. debian-binary member + deb.write(write_ar_header("debian-binary", len(debian_binary), now)) + deb.write(debian_binary) + if len(debian_binary) % 2 != 0: + deb.write(b"\n") + + # 3. control.tar.gz member + ctrl_bytes = control_tar_gz.read_bytes() + deb.write(write_ar_header("control.tar.gz", len(ctrl_bytes), now)) + deb.write(ctrl_bytes) + if len(ctrl_bytes) % 2 != 0: + deb.write(b"\n") + + # 4. data.tar.gz member + data_bytes = data_tar_gz.read_bytes() + deb.write(write_ar_header("data.tar.gz", len(data_bytes), now)) + deb.write(data_bytes) + if len(data_bytes) % 2 != 0: + deb.write(b"\n") + + return output_deb_path + + +class PackageBuilder: + def __init__( + self, + source_root: Optional[Path] = None, + output_dir: Optional[Path] = None, + version: str = "1.0.0", + ) -> None: + self.source_root = source_root or Path(__file__).resolve().parent.parent + self.output_dir = output_dir or (self.source_root / "dist") + self.output_dir.mkdir(parents=True, exist_ok=True) + self.version = version + + def build_tarball(self) -> Path: + """Builds a standalone linux-updater-.tar.gz with installer.""" + tar_name = f"linux-updater-{self.version}.tar.gz" + out_path = self.output_dir / tar_name + + with tempfile.TemporaryDirectory() as tmp_str: + tmp_root = Path(tmp_str) / f"linux-updater-{self.version}" + tmp_root.mkdir(parents=True) + + # Copy package modules + shutil.copytree(str(self.source_root / "linux_updater"), str(tmp_root / "linux_updater")) + + # Copy launcher script + bin_dir = tmp_root / "bin" + bin_dir.mkdir() + shutil.copy2(str(self.source_root / "bin" / "linux-updater"), str(bin_dir / "linux-updater")) + os.chmod(str(bin_dir / "linux-updater"), 0o755) + + # Copy installer + shutil.copy2(str(self.source_root / "packaging" / "install.sh"), str(tmp_root / "install.sh")) + + # Copy example config + shutil.copy2( + str(self.source_root / "linux-updater.json.example"), + str(tmp_root / "linux-updater.json.example"), + ) + + # Archive the tree + with tarfile.open(str(out_path), "w:gz") as tar: + tar.add(str(tmp_root), arcname=f"linux-updater-{self.version}") + + return out_path + + def build_deb(self) -> Path: + """Builds Debian .deb package.""" + deb_filename = f"linux-updater_{self.version}_all.deb" + deb_output_path = self.output_dir / deb_filename + + with tempfile.TemporaryDirectory() as tmp_str: + root = Path(tmp_str) + control_dir = root / "control" + data_dir = root / "data" + control_dir.mkdir() + data_dir.mkdir() + + # Render control file + template_path = self.source_root / "packaging" / "deb" / "control.template" + template_content = template_path.read_text(encoding="utf-8") + rendered_control = template_content.format(version=self.version) + (control_dir / "control").write_text(rendered_control, encoding="utf-8") + + # Prepare data directory + usr_bin = data_dir / "usr" / "bin" + usr_lib = data_dir / "usr" / "lib" / "linux-updater" + etc_dir = data_dir / "etc" + var_log = data_dir / "var" / "log" / "linux-updater" + usr_bin.mkdir(parents=True) + usr_lib.mkdir(parents=True) + etc_dir.mkdir(parents=True) + var_log.mkdir(parents=True) + + shutil.copy2(str(self.source_root / "bin" / "linux-updater"), str(usr_bin / "linux-updater")) + os.chmod(str(usr_bin / "linux-updater"), 0o755) + shutil.copytree(str(self.source_root / "linux_updater"), str(usr_lib / "linux_updater")) + shutil.copy2( + str(self.source_root / "linux-updater.json.example"), + str(etc_dir / "linux-updater.json"), + ) + + # If dpkg-deb is available, use it; otherwise build native .deb + if shutil.which("dpkg-deb"): + pkg_tree = root / "deb_tree" + shutil.copytree(str(data_dir), str(pkg_tree)) + debian_meta = pkg_tree / "DEBIAN" + debian_meta.mkdir() + shutil.copy2(str(control_dir / "control"), str(debian_meta / "control")) + subprocess.run(["dpkg-deb", "-b", str(pkg_tree), str(deb_output_path)], check=True) + else: + # Pure Python build + ctrl_tar = root / "control.tar.gz" + data_tar = root / "data.tar.gz" + + with tarfile.open(str(ctrl_tar), "w:gz") as tar: + tar.add(str(control_dir / "control"), arcname="./control") + + with tarfile.open(str(data_tar), "w:gz") as tar: + for item in data_dir.iterdir(): + tar.add(str(item), arcname=f"./{item.name}") + + create_native_deb(ctrl_tar, data_tar, deb_output_path) + + return deb_output_path + + def build_rpm(self) -> Path: + """Sets up RPM build tree and executes rpmbuild if available.""" + rpm_topdir = self.output_dir / "rpm" + specs_dir = rpm_topdir / "SPECS" + sources_dir = rpm_topdir / "SOURCES" + rpms_dir = rpm_topdir / "RPMS" + srpms_dir = rpm_topdir / "SRPMS" + build_dir = rpm_topdir / "BUILD" + + for d in (specs_dir, sources_dir, rpms_dir, srpms_dir, build_dir): + d.mkdir(parents=True, exist_ok=True) + + # 1. Generate source tarball in SOURCES + tarball_path = sources_dir / f"linux-updater-{self.version}.tar.gz" + with tempfile.TemporaryDirectory() as tmp_str: + tmp_root = Path(tmp_str) / f"linux-updater-{self.version}" + tmp_root.mkdir(parents=True) + shutil.copytree(str(self.source_root / "linux_updater"), str(tmp_root / "linux_updater")) + bin_dir = tmp_root / "bin" + bin_dir.mkdir() + shutil.copy2(str(self.source_root / "bin" / "linux-updater"), str(bin_dir / "linux-updater")) + os.chmod(str(bin_dir / "linux-updater"), 0o755) + shutil.copy2( + str(self.source_root / "linux-updater.json.example"), + str(tmp_root / "linux-updater.json.example"), + ) + with tarfile.open(str(tarball_path), "w:gz") as tar: + tar.add(str(tmp_root), arcname=f"linux-updater-{self.version}") + + # 2. Copy spec file + spec_source = self.source_root / "packaging" / "rpm" / "linux-updater.spec" + target_spec = specs_dir / "linux-updater.spec" + shutil.copy2(str(spec_source), str(target_spec)) + + # 3. If rpmbuild is available, build the RPM + if shutil.which("rpmbuild"): + try: + subprocess.run( + [ + "rpmbuild", + "-ba", + "--define", + f"_topdir {rpm_topdir}", + str(target_spec), + ], + check=True, + ) + # Find created .rpm + rpms = list(rpms_dir.glob("**/*.rpm")) + if rpms: + return rpms[0] + except Exception: + pass + + # Return spec path or topdir + return target_spec + + def build_all(self) -> Dict[str, Path]: + tar_p = self.build_tarball() + deb_p = self.build_deb() + rpm_p = self.build_rpm() + return { + "tarball": tar_p, + "deb": deb_p, + "rpm": rpm_p, + } + + +def main() -> int: + builder = PackageBuilder() + print("Building Linux System Updater distribution packages...") + results = builder.build_all() + for name, path in results.items(): + print(f"[{name.upper()}] Artifact created at: {path}") + return 0 + + +if __name__ == "__main__": + main() diff --git a/packaging/deb/control.template b/packaging/deb/control.template new file mode 100644 index 0000000..5f66446 --- /dev/null +++ b/packaging/deb/control.template @@ -0,0 +1,11 @@ +Package: linux-updater +Version: {version} +Section: admin +Priority: optional +Architecture: all +Depends: python3 (>= 3.6) +Maintainer: Test Factory +Description: Unified Linux System Updater + Unified, safe multi-distribution Linux system updater and health inspector. + Performs pre-flight health diagnostics (disk, locks, RAM, power) with automatic + safe remediation, routine package upgrades, and major distribution upgrades. diff --git a/packaging/install.sh b/packaging/install.sh new file mode 100755 index 0000000..67b62b1 --- /dev/null +++ b/packaging/install.sh @@ -0,0 +1,36 @@ +#!/bin/sh +set -e + +# Installer for Linux System Updater (.tar.gz distribution) +PREFIX="${PREFIX:-/usr/local}" +SYSCONFDIR="${SYSCONFDIR:-/etc}" + +if [ "$(id -u)" -ne 0 ]; then + echo "Error: Installation requires root/sudo privileges." >&2 + exit 1 +fi + +echo "Installing Linux System Updater to ${PREFIX}..." + +# Create target directories +mkdir -p "${PREFIX}/bin" +mkdir -p "${PREFIX}/lib/linux-updater" +mkdir -p "${SYSCONFDIR}" +mkdir -p /var/log/linux-updater +chmod 750 /var/log/linux-updater || chmod 755 /var/log/linux-updater + +# Copy package modules +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cp -r "${SCRIPT_DIR}/linux_updater" "${PREFIX}/lib/linux-updater/" + +# Install launcher +install -m 755 "${SCRIPT_DIR}/bin/linux-updater" "${PREFIX}/bin/linux-updater" + +# Install default config if not existing +if [ ! -f "${SYSCONFDIR}/linux-updater.json" ] && [ -f "${SCRIPT_DIR}/linux-updater.json.example" ]; then + echo "Installing default configuration to ${SYSCONFDIR}/linux-updater.json..." + cp "${SCRIPT_DIR}/linux-updater.json.example" "${SYSCONFDIR}/linux-updater.json" + chmod 644 "${SYSCONFDIR}/linux-updater.json" +fi + +echo "Installation complete! Run 'linux-updater --help' to verify." diff --git a/packaging/rpm/linux-updater.spec b/packaging/rpm/linux-updater.spec new file mode 100644 index 0000000..5895e16 --- /dev/null +++ b/packaging/rpm/linux-updater.spec @@ -0,0 +1,45 @@ +Name: linux-updater +Version: 1.0.0 +Release: 1%{?dist} +Summary: Unified, safe multi-distribution Linux system updater + +License: MIT +URL: https://github.com/example/linux-updater +Source0: linux-updater-%{version}.tar.gz + +BuildArch: noarch +Requires: python3 >= 3.6 + +%description +Linux System Updater is a unified, safe multi-distribution system update tool. +It inspects system health (disk space on /boot and /var, memory and OOM pressure, +stale package locks) before applying routine package updates or major distribution +release upgrades across Debian, RHEL, and Arch families. + +%prep +%setup -q + +%build +# Pure Python package, no compilation required + +%install +rm -rf $RPM_BUILD_ROOT +mkdir -p $RPM_BUILD_ROOT/usr/bin +mkdir -p $RPM_BUILD_ROOT/usr/lib/linux-updater +mkdir -p $RPM_BUILD_ROOT/etc +mkdir -p $RPM_BUILD_ROOT/var/log/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 644 linux-updater.json.example $RPM_BUILD_ROOT/etc/linux-updater.json + +%files +%defattr(-,root,root,-) +%attr(0755, root, root) /usr/bin/linux-updater +/usr/lib/linux-updater +%config(noreplace) /etc/linux-updater.json +%dir %attr(0750, root, root) /var/log/linux-updater + +%changelog +* Fri Oct 02 2026 Test Factory - 1.0.0-1 +- Initial release with Debian, RHEL, and Arch support. diff --git a/tests/containers/run_tests.sh b/tests/containers/run_tests.sh new file mode 100755 index 0000000..c673eb6 --- /dev/null +++ b/tests/containers/run_tests.sh @@ -0,0 +1,128 @@ +#!/bin/sh +set -e + +# Container integration test suite for Linux System Updater +# Runs inside clean Podman containers on macOS + +DISTRO="${1:-all}" +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +WORKSPACE="$(cd "${SCRIPT_DIR}/../.." && pwd)" + +run_distro_test() { + D="$1" + echo "" + echo "==========================================================" + echo " [TEST] Starting container testing for: ${D}" + echo "==========================================================" + + case "${D}" in + debian) + IMAGE="docker.io/library/debian:12-slim" + CMD=" + apt-get update -qq && apt-get install -y -qq python3 > /dev/null + echo '=== 1. Building packages inside Debian container ===' + python3 packaging/build_packages.py + echo '=== 2. Installing .deb package ===' + dpkg -i dist/linux-updater_1.0.0_all.deb + echo '=== 3. Testing installed command ===' + linux-updater --version + echo '=== 4. Testing pre-flight health checks ===' + linux-updater health + echo '=== 5. Testing regular update (dry-run) ===' + linux-updater update --dry-run -y + echo '=== 6. Testing major release upgrade (dry-run) ===' + linux-updater release-upgrade --dry-run -y -t trixie + echo '=== 7. Verifying standard /var/log/linux-updater logging ===' + ls -la /var/log/linux-updater + test -f /var/log/linux-updater/latest.log + " + ;; + ubuntu) + IMAGE="docker.io/library/ubuntu:22.04" + CMD=" + apt-get update -qq && apt-get install -y -qq python3 > /dev/null + echo '=== 1. Building packages inside Ubuntu container ===' + python3 packaging/build_packages.py + echo '=== 2. Installing .deb package ===' + dpkg -i dist/linux-updater_1.0.0_all.deb + echo '=== 3. Testing installed command ===' + linux-updater --version + echo '=== 4. Testing pre-flight health checks ===' + linux-updater health + echo '=== 5. Testing regular update (dry-run) ===' + linux-updater update --dry-run -y + echo '=== 6. Testing major release upgrade (dry-run) ===' + linux-updater release-upgrade --dry-run -y -t 24.04 + echo '=== 7. Verifying standard /var/log/linux-updater logging ===' + ls -la /var/log/linux-updater + test -f /var/log/linux-updater/latest.log + " + ;; + fedora) + IMAGE="docker.io/library/fedora:40" + CMD=" + dnf install -y -q python3 rpm-build python3-dnf-plugins-core > /dev/null + rm -rf dist/rpm + echo '=== 1. Building packages and RPM inside Fedora container ===' + python3 packaging/build_packages.py + echo '=== 2. Installing generated .rpm package ===' + rpm -Uvh --replacepkgs --replacefiles dist/rpm/RPMS/noarch/linux-updater-*.noarch.rpm + echo '=== 3. Testing installed command ===' + linux-updater --version + echo '=== 4. Testing pre-flight health checks ===' + linux-updater health + echo '=== 5. Testing regular update (dry-run) ===' + linux-updater update --dry-run -y + echo '=== 6. Testing major release upgrade (dry-run) ===' + linux-updater release-upgrade --dry-run -y -t 41 + echo '=== 7. Verifying standard /var/log/linux-updater logging ===' + ls -la /var/log/linux-updater + test -f /var/log/linux-updater/latest.log + " + ;; + almalinux8) + IMAGE="docker.io/library/almalinux:8" + CMD=" + dnf install -y -q python3 rpm-build > /dev/null + rm -rf dist/rpm + echo '=== 1. Verifying Native Python on AlmaLinux 8 ===' + python3 --version + echo '=== 2. Building packages and RPM inside AlmaLinux 8 container ===' + python3 packaging/build_packages.py + echo '=== 3. Installing generated .rpm package ===' + rpm -Uvh --replacepkgs --replacefiles dist/rpm/RPMS/noarch/linux-updater-*.noarch.rpm + echo '=== 4. Testing installed command on Python 3.6 ===' + linux-updater --version + echo '=== 5. Testing pre-flight health checks ===' + linux-updater health + echo '=== 6. Testing regular update (dry-run) ===' + linux-updater update --dry-run -y + echo '=== 7. Testing major release upgrade (dry-run) ===' + linux-updater release-upgrade --dry-run -y + echo '=== 8. Verifying standard /var/log/linux-updater logging ===' + ls -la /var/log/linux-updater + test -f /var/log/linux-updater/latest.log + " + ;; + *) + echo "Unknown distro: ${D}" >&2 + return 1 + ;; + esac + + podman run --rm -v "${WORKSPACE}:/workspace:Z" -w /workspace "${IMAGE}" bash -c "${CMD}" + echo ">>> [SUCCESS] Testing for ${D} PASSED!" +} + +if [ "${DISTRO}" = "all" ]; then + for target in debian ubuntu fedora almalinux8; do + run_distro_test "${target}" + done +else + run_distro_test "${DISTRO}" +fi + +echo "" +echo "==========================================================" +echo " ALL REQUESTED CONTAINER TESTS COMPLETED SUCCESSFULLY!" +echo "==========================================================" diff --git a/tests/test_cli.py b/tests/test_cli.py index 9aa6e12..33332e9 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -122,6 +122,7 @@ class TestCLIIntegration(unittest.TestCase): self.assertEqual(code, 0) mock_manager.release_upgrade.assert_called_once_with( target_release="41", + dry_run=False, non_interactive=True, ) @@ -143,6 +144,43 @@ class TestCLIIntegration(unittest.TestCase): if t_path.exists(): t_path.unlink() + @patch("linux_updater.cli.DistroDetector.detect") + @patch("linux_updater.cli.get_manager") + def test_logging_creates_timestamped_log_and_symlink(self, mock_get_manager, mock_detect): + mock_detect.return_value = DistroInfo(DistroFamily.DEBIAN, "ubuntu", "24.04", "Ubuntu 24.04") + mock_manager = MagicMock() + mock_manager.get_lock_files.return_value = [] + mock_get_manager.return_value = mock_manager + + with tempfile.TemporaryDirectory() as tmp_dir: + config_data = { + "logging": {"log_dir": tmp_dir, "verbose": True} + } + cfg_file = Path(tmp_dir) / "config.json" + cfg_file.write_text(json.dumps(config_data)) + + with patch("os.statvfs") as mock_statvfs: + mock_stat = MagicMock() + mock_stat.f_bavail = 10 * 1024 * 1024 + mock_stat.f_frsize = 1024 + mock_statvfs.return_value = mock_stat + + code = main(["-c", str(cfg_file), "health"]) + self.assertEqual(code, 0) + + # Check that log file was created + log_files = list(Path(tmp_dir).glob("linux-updater-*.log")) + self.assertEqual(len(log_files), 1) + # Check latest.log symlink + latest_link = Path(tmp_dir) / "latest.log" + self.assertTrue(latest_link.is_symlink()) + self.assertEqual(latest_link.resolve(), log_files[0].resolve()) + + # Check content of log file + content = log_files[0].read_text() + self.assertIn("Linux System Updater", content) + self.assertIn("started", content) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_health.py b/tests/test_health.py index a213bf0..793b85a 100644 --- a/tests/test_health.py +++ b/tests/test_health.py @@ -24,7 +24,7 @@ class DummyManager(PackageManager): def apply_updates(self, packages=None, dry_run=False, non_interactive=False): pass - def release_upgrade(self, target_release=None, non_interactive=False): + def release_upgrade(self, target_release=None, dry_run=False, non_interactive=False): pass def clean_cache(self): @@ -133,6 +133,36 @@ class TestHealthChecker(unittest.TestCase): if lock_p.exists(): lock_p.unlink() + def test_locks_advisory_lock_free(self): + lock_p = Path("/tmp/test_dummy.lock") + lock_p.touch() + try: + results = self.checker.check_locks() + self.assertEqual(len(results), 1) + self.assertEqual(results[0].status, CheckStatus.PASS) + self.assertIn("No lock active", results[0].message) + finally: + if lock_p.exists(): + lock_p.unlink() + + def test_locks_advisory_lock_held(self): + import fcntl + lock_p = Path("/tmp/test_dummy.lock") + lock_p.touch() + f = open(str(lock_p), "r+") + fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + try: + results = self.checker.check_locks() + self.assertEqual(len(results), 1) + self.assertEqual(results[0].status, CheckStatus.FAIL) + self.assertIn("Advisory lock actively held", results[0].message) + self.assertFalse(results[0].can_remediate) + finally: + fcntl.flock(f.fileno(), fcntl.LOCK_UN) + f.close() + if lock_p.exists(): + lock_p.unlink() + def test_memory_sufficient(self): meminfo = """MemTotal: 8147284 kB MemFree: 2145124 kB diff --git a/tests/test_packaging.py b/tests/test_packaging.py new file mode 100644 index 0000000..3f0f11a --- /dev/null +++ b/tests/test_packaging.py @@ -0,0 +1,62 @@ +import os +import tarfile +import tempfile +import unittest +from pathlib import Path + +from packaging.build_packages import PackageBuilder + + +class TestPackaging(unittest.TestCase): + def setUp(self): + self.temp_dir = tempfile.TemporaryDirectory() + self.out_dir = Path(self.temp_dir.name) + self.root_dir = Path(__file__).resolve().parent.parent + self.builder = PackageBuilder(source_root=self.root_dir, output_dir=self.out_dir, version="1.0.0") + + def tearDown(self): + self.temp_dir.cleanup() + + def test_build_tarball_creates_valid_archive(self): + tar_path = self.builder.build_tarball() + self.assertTrue(tar_path.exists()) + self.assertTrue(tar_path.name.endswith(".tar.gz")) + + # Verify archive contents + with tarfile.open(str(tar_path), "r:gz") as tar: + names = tar.getnames() + self.assertTrue(any("install.sh" 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)) + + def test_build_deb_creates_package_or_tree(self): + deb_path = self.builder.build_deb() + self.assertTrue(deb_path.exists()) + self.assertTrue(str(deb_path).endswith(".deb")) + + # Check ar header '!\n' + with open(str(deb_path), "rb") as f: + header = f.read(8) + self.assertEqual(header, b"!\n") + + def test_build_rpm_spec_and_source(self): + rpm_result = self.builder.build_rpm() + self.assertTrue(rpm_result.exists()) + spec_path = self.out_dir / "rpm" / "SPECS" / "linux-updater.spec" + self.assertTrue(spec_path.exists()) + content = spec_path.read_text(encoding="utf-8") + self.assertIn("Name: linux-updater", content) + self.assertIn("Requires: python3 >= 3.6", content) + self.assertIn("BuildArch: noarch", content) + + def test_build_all(self): + results = self.builder.build_all() + self.assertIn("tarball", results) + self.assertIn("deb", results) + self.assertIn("rpm", results) + for k, p in results.items(): + self.assertTrue(p.exists(), f"Artifact {k} at {p} does not exist") + + +if __name__ == "__main__": + unittest.main()