feat: implement slice 1 tracer bullet (cli entrypoint, distro detector, and test suite)
This commit is contained in:
commit
63c6cc846b
16 files changed
+1317
No files matched your search
@@ -0,0 +1,4 @@
|
||||
"""Linux System Updater - Multi-distribution system updater and health checker."""
|
||||
|
||||
__version__ = "1.0.0"
|
||||
__author__ = "Test Factory"
|
||||
@@ -0,0 +1,5 @@
|
||||
import sys
|
||||
from linux_updater.cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,135 @@
|
||||
import argparse
|
||||
import sys
|
||||
from typing import List, Optional
|
||||
|
||||
from linux_updater import __version__
|
||||
from linux_updater.core.detector import DistroDetector
|
||||
from linux_updater.models import DistroFamily
|
||||
|
||||
|
||||
def create_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="linux-updater",
|
||||
description="Unified, safe multi-distribution Linux system updater and health inspector.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
parser.add_argument(
|
||||
"-v", "--version",
|
||||
action="version",
|
||||
version=f"%(prog)s {__version__}",
|
||||
help="Show program's version number and exit.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-c", "--config",
|
||||
type=str,
|
||||
default="/etc/linux-updater.json",
|
||||
help="Path to JSON configuration file.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-y", "--yes", "--non-interactive",
|
||||
dest="non_interactive",
|
||||
action="store_true",
|
||||
help="Run without interactive confirmation prompts (ideal for cron and automation).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Simulate execution without modifying system state.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-remediation",
|
||||
action="store_true",
|
||||
help="Disable automatic remediation of failed pre-flight health checks.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--skip-preflight",
|
||||
action="store_true",
|
||||
help="Skip pre-flight health checks (not recommended).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--json",
|
||||
action="store_true",
|
||||
help="Output structured JSON results.",
|
||||
)
|
||||
|
||||
subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
|
||||
|
||||
# Subcommand: update
|
||||
update_parser = subparsers.add_parser(
|
||||
"update",
|
||||
help="Inspect health, auto-remediate safe issues, and apply package updates.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
update_parser.add_argument(
|
||||
"--packages",
|
||||
nargs="+",
|
||||
metavar="PACKAGE",
|
||||
help="Selectively update only the specified package(s) instead of the entire system.",
|
||||
)
|
||||
|
||||
# Subcommand: check
|
||||
subparsers.add_parser(
|
||||
"check",
|
||||
help="Check system health and list available updates without making modifications.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
|
||||
# Subcommand: release-upgrade
|
||||
release_parser = subparsers.add_parser(
|
||||
"release-upgrade",
|
||||
help="Perform a major distribution release upgrade with additional safety guardrails.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
release_parser.add_argument(
|
||||
"-t", "--target-release",
|
||||
type=str,
|
||||
help="Specify the target distribution version number/codename (e.g. 24.04, 41).",
|
||||
)
|
||||
|
||||
# Subcommand: clean
|
||||
clean_parser = subparsers.add_parser(
|
||||
"clean",
|
||||
help="Clean downloaded package cache and remove orphaned packages.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
clean_parser.add_argument(
|
||||
"--all",
|
||||
action="store_true",
|
||||
help="Clean both package cache and autoremove unused dependencies.",
|
||||
)
|
||||
|
||||
# Subcommand: health
|
||||
subparsers.add_parser(
|
||||
"health",
|
||||
help="Run only the pre-flight health diagnostic checks.",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: Optional[List[str]] = None) -> int:
|
||||
parser = create_parser()
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
# If no subcommand provided, default to update or show help if no args given
|
||||
if args.command is None:
|
||||
args.command = "update"
|
||||
|
||||
detector = DistroDetector()
|
||||
distro = detector.detect()
|
||||
|
||||
if not args.json:
|
||||
print(f"Linux System Updater v{__version__}")
|
||||
print(f"Detected System: {distro.pretty_name} (Family: {distro.family.value})")
|
||||
|
||||
if distro.family == DistroFamily.UNKNOWN:
|
||||
if not args.json:
|
||||
print(f"Error: Unsupported or unrecognized Linux distribution: {distro.distro_id}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
# Core subsystem
|
||||
@@ -0,0 +1,86 @@
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional
|
||||
from linux_updater.models import DistroFamily, DistroInfo
|
||||
|
||||
|
||||
class DistroDetector:
|
||||
def __init__(self, os_release_path: Optional[Path] = None) -> None:
|
||||
if os_release_path is not None:
|
||||
self.os_release_path = os_release_path
|
||||
else:
|
||||
default_p = Path("/etc/os-release")
|
||||
fallback_p = Path("/usr/lib/os-release")
|
||||
self.os_release_path = default_p if default_p.exists() else fallback_p
|
||||
|
||||
def _parse_os_release(self) -> Dict[str, str]:
|
||||
data: Dict[str, str] = {}
|
||||
if not self.os_release_path.exists():
|
||||
return data
|
||||
|
||||
try:
|
||||
with open(str(self.os_release_path), "r", encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, val = line.split("=", 1)
|
||||
key = key.strip()
|
||||
val = val.strip()
|
||||
# Strip surrounding quotes if present
|
||||
if len(val) >= 2 and (
|
||||
(val.startswith('"') and val.endswith('"'))
|
||||
or (val.startswith("'") and val.endswith("'"))
|
||||
):
|
||||
val = val[1:-1]
|
||||
data[key] = val
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
return data
|
||||
|
||||
def detect(self) -> DistroInfo:
|
||||
data = self._parse_os_release()
|
||||
if not data:
|
||||
return DistroInfo(
|
||||
family=DistroFamily.UNKNOWN,
|
||||
distro_id="unknown",
|
||||
version_id="unknown",
|
||||
pretty_name="Unknown Linux System",
|
||||
)
|
||||
|
||||
distro_id = data.get("ID", "").lower().strip()
|
||||
id_like = data.get("ID_LIKE", "").lower().strip().split()
|
||||
version_id = data.get("VERSION_ID", data.get("BUILD_ID", "rolling")).strip()
|
||||
pretty_name = data.get("PRETTY_NAME", data.get("NAME", distro_id)).strip()
|
||||
|
||||
family = self._resolve_family(distro_id, id_like)
|
||||
|
||||
return DistroInfo(
|
||||
family=family,
|
||||
distro_id=distro_id,
|
||||
version_id=version_id,
|
||||
pretty_name=pretty_name,
|
||||
)
|
||||
|
||||
def _resolve_family(self, distro_id: str, id_like: list) -> DistroFamily:
|
||||
debian_ids = {"debian", "ubuntu", "linuxmint", "pop", "elementary", "kali", "raspbian"}
|
||||
rhel_ids = {"rhel", "fedora", "centos", "rocky", "almalinux", "ol", "amzn"}
|
||||
arch_ids = {"arch", "manjaro", "endeavouros", "garuda", "artix"}
|
||||
|
||||
if distro_id in debian_ids:
|
||||
return DistroFamily.DEBIAN
|
||||
if distro_id in rhel_ids:
|
||||
return DistroFamily.RHEL
|
||||
if distro_id in arch_ids:
|
||||
return DistroFamily.ARCH
|
||||
|
||||
# Check ID_LIKE
|
||||
for like in id_like:
|
||||
if like in debian_ids:
|
||||
return DistroFamily.DEBIAN
|
||||
if like in rhel_ids:
|
||||
return DistroFamily.RHEL
|
||||
if like in arch_ids:
|
||||
return DistroFamily.ARCH
|
||||
|
||||
return DistroFamily.UNKNOWN
|
||||
@@ -0,0 +1 @@
|
||||
# Package managers subsystem
|
||||
@@ -0,0 +1,61 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
from linux_updater.models import PackageUpdate, CommandResult, RebootStatus
|
||||
|
||||
|
||||
class PackageManager(ABC):
|
||||
@property
|
||||
@abstractmethod
|
||||
def name(self) -> str:
|
||||
"""Returns the identifier of the package manager (e.g. 'apt', 'dnf', 'pacman')."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def refresh_repositories(self) -> CommandResult:
|
||||
"""Synchronizes repository metadata."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def check_updates(self) -> List[PackageUpdate]:
|
||||
"""Lists available package updates."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def apply_updates(
|
||||
self,
|
||||
packages: Optional[List[str]] = None,
|
||||
dry_run: bool = False,
|
||||
non_interactive: bool = False,
|
||||
) -> CommandResult:
|
||||
"""Applies package updates."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def release_upgrade(
|
||||
self,
|
||||
target_release: Optional[str] = None,
|
||||
non_interactive: bool = False,
|
||||
) -> CommandResult:
|
||||
"""Executes a major OS distribution upgrade."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def clean_cache(self) -> CommandResult:
|
||||
"""Cleans downloaded package cache."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def autoremove(self) -> CommandResult:
|
||||
"""Removes unneeded dependency packages."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def is_reboot_required(self) -> RebootStatus:
|
||||
"""Detects whether a system reboot is required."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_lock_files(self) -> List[Path]:
|
||||
"""Returns paths of lockfiles used by this manager."""
|
||||
pass
|
||||
@@ -0,0 +1,120 @@
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Dict, Any, NamedTuple
|
||||
|
||||
|
||||
class DistroFamily(str, Enum):
|
||||
DEBIAN = "debian"
|
||||
RHEL = "rhel"
|
||||
ARCH = "arch"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
class CheckStatus(str, Enum):
|
||||
PASS = "PASS"
|
||||
WARN = "WARN"
|
||||
FAIL = "FAIL"
|
||||
|
||||
|
||||
class DistroInfo(NamedTuple):
|
||||
family: DistroFamily
|
||||
distro_id: str
|
||||
version_id: str
|
||||
pretty_name: str
|
||||
|
||||
|
||||
class CheckResult:
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
status: CheckStatus,
|
||||
message: str,
|
||||
can_remediate: bool = False,
|
||||
remediation_id: Optional[str] = None,
|
||||
) -> None:
|
||||
self.name = name
|
||||
self.status = status
|
||||
self.message = message
|
||||
self.can_remediate = can_remediate
|
||||
self.remediation_id = remediation_id
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"name": self.name,
|
||||
"status": self.status.value,
|
||||
"message": self.message,
|
||||
"can_remediate": self.can_remediate,
|
||||
"remediation_id": self.remediation_id,
|
||||
}
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"CheckResult(name={self.name!r}, status={self.status!r}, message={self.message!r})"
|
||||
|
||||
|
||||
class PreflightReport:
|
||||
def __init__(
|
||||
self,
|
||||
passed: bool,
|
||||
results: List[CheckResult],
|
||||
remediations_performed: Optional[List[str]] = None,
|
||||
) -> None:
|
||||
self.passed = passed
|
||||
self.results = results
|
||||
self.remediations_performed = remediations_performed or []
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"passed": self.passed,
|
||||
"results": [r.to_dict() for r in self.results],
|
||||
"remediations_performed": self.remediations_performed,
|
||||
}
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"PreflightReport(passed={self.passed!r}, results_count={len(self.results)})"
|
||||
|
||||
|
||||
class PackageUpdate(NamedTuple):
|
||||
package: str
|
||||
current_version: str
|
||||
new_version: str
|
||||
repo: Optional[str] = None
|
||||
|
||||
|
||||
class CommandResult:
|
||||
def __init__(
|
||||
self,
|
||||
return_code: int,
|
||||
stdout: str,
|
||||
stderr: str,
|
||||
success: bool,
|
||||
) -> None:
|
||||
self.return_code = return_code
|
||||
self.stdout = stdout
|
||||
self.stderr = stderr
|
||||
self.success = success
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"return_code": self.return_code,
|
||||
"stdout": self.stdout,
|
||||
"stderr": self.stderr,
|
||||
"success": self.success,
|
||||
}
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"CommandResult(return_code={self.return_code}, success={self.success})"
|
||||
|
||||
|
||||
class RebootStatus:
|
||||
def __init__(self, required: bool, reason: str = "") -> None:
|
||||
self.required = required
|
||||
self.reason = reason
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"required": self.required,
|
||||
"reason": self.reason,
|
||||
}
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"RebootStatus(required={self.required!r}, reason={self.reason!r})"
|
||||
Reference in new issue
Block a user