Files
inventory-collector/packaging/build_packages.py
T

347 lines
14 KiB
Python
Executable File

#!/usr/bin/env python3
"""Inventory Collector 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 hashlib
import os
import shutil
import subprocess
import tarfile
import tempfile
import time
from pathlib import Path
from typing import Dict, List, Optional
def get_version(source_root: Path) -> str:
"""Extract __version__ dynamically from inventory_collector/__init__.py."""
init_path = source_root / "inventory_collector" / "__init__.py"
if init_path.exists():
for line in init_path.read_text(encoding="utf-8").splitlines():
if line.startswith("__version__"):
parts = line.split("=")
if len(parts) >= 2:
return parts[1].strip().strip('"').strip("'")
return "1.0.0"
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"!<arch>\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: Optional[str] = None,
) -> 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 or get_version(self.source_root)
def build_tarball(self) -> Path:
"""Builds a standalone inventory-collector-<version>.tar.gz with installer."""
tar_name = f"inventory-collector-{self.version}.tar.gz"
out_path = self.output_dir / tar_name
with tempfile.TemporaryDirectory() as tmp_str:
tmp_root = Path(tmp_str) / f"inventory-collector-{self.version}"
tmp_root.mkdir(parents=True)
# Copy package modules
shutil.copytree(str(self.source_root / "inventory_collector"), str(tmp_root / "inventory_collector"))
# Copy launcher script
bin_dir = tmp_root / "bin"
bin_dir.mkdir()
shutil.copy2(str(self.source_root / "bin" / "inventory-collector"), str(bin_dir / "inventory-collector"))
os.chmod(str(bin_dir / "inventory-collector"), 0o755)
# Copy installer
shutil.copy2(str(self.source_root / "packaging" / "install.sh"), str(tmp_root / "install.sh"))
os.chmod(str(tmp_root / "install.sh"), 0o755)
# Copy packaging directory
shutil.copytree(str(self.source_root / "packaging"), str(tmp_root / "packaging"))
# Copy example config
if (self.source_root / "config.yaml.example").exists():
shutil.copy2(
str(self.source_root / "config.yaml.example"),
str(tmp_root / "config.yaml.example"),
)
# Copy documentation
if (self.source_root / "README.md").exists():
shutil.copy2(str(self.source_root / "README.md"), str(tmp_root / "README.md"))
if (self.source_root / "requirements.txt").exists():
shutil.copy2(str(self.source_root / "requirements.txt"), str(tmp_root / "requirements.txt"))
if (self.source_root / "docs").exists():
shutil.copytree(str(self.source_root / "docs"), str(tmp_root / "docs"))
# Copy man page
if (self.source_root / "man").exists():
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"))
# Archive the tree
with tarfile.open(str(out_path), "w:gz") as tar:
tar.add(str(tmp_root), arcname=f"inventory-collector-{self.version}")
return out_path
def build_deb(self) -> Path:
"""Builds Debian .deb package."""
deb_filename = f"inventory-collector_{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" / "inventory-collector"
etc_dir = data_dir / "etc" / "inventory-collector"
usr_bin.mkdir(parents=True)
usr_lib.mkdir(parents=True)
etc_dir.mkdir(parents=True)
shutil.copy2(str(self.source_root / "bin" / "inventory-collector"), str(usr_bin / "inventory-collector"))
os.chmod(str(usr_bin / "inventory-collector"), 0o755)
shutil.copytree(str(self.source_root / "inventory_collector"), str(usr_lib / "inventory_collector"))
if (self.source_root / "config.yaml.example").exists():
shutil.copy2(
str(self.source_root / "config.yaml.example"),
str(etc_dir / "config.yaml.example"),
)
if (self.source_root / "man" / "inventory-collector.1").exists():
man_dir = data_dir / "usr" / "share" / "man" / "man1"
man_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(str(self.source_root / "man" / "inventory-collector.1"), str(man_dir / "inventory-collector.1"))
if (self.source_root / "completions" / "bash" / "inventory-collector").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" / "inventory-collector"),
str(bash_comp_dir / "inventory-collector"),
)
if (self.source_root / "completions" / "zsh" / "_inventory-collector").exists():
zsh_comp_dir = data_dir / "usr" / "share" / "zsh" / "site-functions"
zsh_comp_dir.mkdir(parents=True, exist_ok=True)
shutil.copy2(
str(self.source_root / "completions" / "zsh" / "_inventory-collector"),
str(zsh_comp_dir / "_inventory-collector"),
)
doc_dir = data_dir / "usr" / "share" / "doc" / "inventory-collector"
doc_dir.mkdir(parents=True, exist_ok=True)
if (self.source_root / "README.md").exists():
shutil.copy2(str(self.source_root / "README.md"), str(doc_dir / "README.md"))
if (self.source_root / "docs" / "user-guide.md").exists():
shutil.copy2(str(self.source_root / "docs" / "user-guide.md"), str(doc_dir / "user-guide.md"))
# 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 with strict GNU_FORMAT (dpkg rejects PAX 'x' headers)
def reset_tarinfo(tarinfo):
tarinfo.uid = 0
tarinfo.gid = 0
tarinfo.uname = "root"
tarinfo.gname = "root"
tarinfo.pax_headers = {}
return tarinfo
ctrl_tar = root / "control.tar.gz"
data_tar = root / "data.tar.gz"
with tarfile.open(str(ctrl_tar), "w:gz", format=tarfile.GNU_FORMAT) as tar:
tar.add(str(control_dir / "control"), arcname="./control", filter=reset_tarinfo)
with tarfile.open(str(data_tar), "w:gz", format=tarfile.GNU_FORMAT) as tar:
for item in sorted(data_dir.iterdir()):
tar.add(str(item), arcname=f"./{item.name}", filter=reset_tarinfo)
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"inventory-collector-{self.version}.tar.gz"
with tempfile.TemporaryDirectory() as tmp_str:
tmp_root = Path(tmp_str) / f"inventory-collector-{self.version}"
tmp_root.mkdir(parents=True)
shutil.copytree(str(self.source_root / "inventory_collector"), str(tmp_root / "inventory_collector"))
bin_dir = tmp_root / "bin"
bin_dir.mkdir()
shutil.copy2(str(self.source_root / "bin" / "inventory-collector"), str(bin_dir / "inventory-collector"))
os.chmod(str(bin_dir / "inventory-collector"), 0o755)
shutil.copytree(str(self.source_root / "packaging"), str(tmp_root / "packaging"))
if (self.source_root / "config.yaml.example").exists():
shutil.copy2(
str(self.source_root / "config.yaml.example"),
str(tmp_root / "config.yaml.example"),
)
if (self.source_root / "man").exists():
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 / "README.md").exists():
shutil.copy2(str(self.source_root / "README.md"), str(tmp_root / "README.md"))
if (self.source_root / "docs").exists():
shutil.copytree(str(self.source_root / "docs"), str(tmp_root / "docs"))
with tarfile.open(str(tarball_path), "w:gz") as tar:
tar.add(str(tmp_root), arcname=f"inventory-collector-{self.version}")
# 2. Copy spec file
spec_source = self.source_root / "packaging" / "rpm" / "inventory-collector.spec"
target_spec = specs_dir / "inventory-collector.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 and copy to dist/
rpms = list(rpms_dir.glob("**/*.rpm"))
if rpms:
for rpm in rpms:
shutil.copy2(str(rpm), str(self.output_dir / rpm.name))
return rpms[0]
except Exception as e:
print(f"[WARN] rpmbuild encountered error: {e}")
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 sha256_file(filepath: Path) -> str:
h = hashlib.sha256()
with open(filepath, "rb") as f:
while chunk := f.read(65536):
h.update(chunk)
return h.hexdigest()
def main() -> int:
builder = PackageBuilder()
print(f"Building inventory-collector v{builder.version} distribution packages...")
results = builder.build_all()
print("\n=== Package Build Results ===")
for name, path in results.items():
if path.exists() and path.is_file():
size = path.stat().st_size
digest = sha256_file(path)
print(f"[{name.upper():<7}] {path.name:<45} ({size:>7} bytes) SHA256: {digest[:16]}...")
else:
print(f"[{name.upper():<7}] {path}")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())