132 lines
4.5 KiB
Python
132 lines
4.5 KiB
Python
"""Build the InterferenceETL Metrix app bundle: dist/metrix/interference-etl-<version>.zip.
|
|
|
|
The bundle holds metrix-app.json, icon.svg and the image file image.tar. The version is
|
|
etl_app.__version__ plus the git short hash, with -dirty when tracked files have changes.
|
|
Requires a working local docker.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import zipfile
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
SLUG = "interference-etl"
|
|
NAME = "InterferenceETL"
|
|
WEB_PORT = 8080
|
|
DATA_DIR = "/data"
|
|
|
|
|
|
def _git(*args: str) -> str:
|
|
completed = subprocess.run(
|
|
["git", "-c", f"safe.directory={ROOT.as_posix()}", *args],
|
|
cwd=ROOT,
|
|
capture_output=True,
|
|
text=True,
|
|
check=True,
|
|
)
|
|
return completed.stdout.strip()
|
|
|
|
|
|
def base_version() -> str:
|
|
source = (ROOT / "etl_app" / "__init__.py").read_text(encoding="utf-8")
|
|
match = re.search(r'__version__\s*=\s*"([^"]+)"', source)
|
|
if match is None:
|
|
raise SystemExit("etl_app/__init__.py has no __version__")
|
|
return match.group(1)
|
|
|
|
|
|
def version() -> str:
|
|
base = base_version()
|
|
try:
|
|
commit = _git("rev-parse", "--short", "HEAD")
|
|
dirty = bool(_git("status", "--porcelain", "--untracked-files=no"))
|
|
except (OSError, subprocess.CalledProcessError):
|
|
return base
|
|
return f"{base}-{commit}-dirty" if dirty else f"{base}-{commit}"
|
|
|
|
|
|
def manifest(image: str, release: str) -> dict:
|
|
return {
|
|
"schema": 2,
|
|
"slug": SLUG,
|
|
"name": NAME,
|
|
"version": release,
|
|
"description": {
|
|
"zh-CN": "从 SFTP 读取小时干扰指标,汇总后写入数据库,并按日期归档历史结果。",
|
|
"en-US": "Reads hourly interference metrics from SFTP, writes the summary to the database, and archives history by date.",
|
|
},
|
|
"user_auth": "none",
|
|
"admin_auth": "metrix",
|
|
"admin_path": "/admin",
|
|
"icon": "icon.svg",
|
|
"services": [
|
|
{"name": "web", "image": image, "image_file": "image.tar", "command": "", "port": WEB_PORT},
|
|
],
|
|
"data_dir": DATA_DIR,
|
|
"env": {"TZ": "Asia/Shanghai"},
|
|
}
|
|
|
|
|
|
def _run(command: list[str]) -> None:
|
|
print("+ " + " ".join(command), flush=True)
|
|
subprocess.run(command, cwd=ROOT, check=True)
|
|
|
|
|
|
def build_image(image: str, args: argparse.Namespace) -> None:
|
|
command = ["docker", "build", "-f", "deploy/Dockerfile", "-t", image]
|
|
for key, value in (("PYTHON_IMAGE", args.python_image), ("PIP_INDEX", args.pip_index)):
|
|
if value:
|
|
command += ["--build-arg", f"{key}={value}"]
|
|
command.append(".")
|
|
_run(command)
|
|
|
|
|
|
def write_bundle(image: str, release: str, target: Path) -> None:
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
partial = target.with_name(target.name + ".partial")
|
|
with tempfile.TemporaryDirectory(prefix="interference-etl-pack-", dir=target.parent) as work:
|
|
tar = Path(work) / "image.tar"
|
|
_run(["docker", "save", "-o", str(tar), image])
|
|
with zipfile.ZipFile(partial, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as bundle:
|
|
bundle.writestr("metrix-app.json", json.dumps(manifest(image, release), ensure_ascii=False, indent=2) + "\n")
|
|
bundle.write(ROOT / "etl_app" / "static" / "icon.svg", "icon.svg")
|
|
bundle.write(tar, "image.tar")
|
|
os.replace(partial, target)
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description="Build the InterferenceETL Metrix app bundle")
|
|
parser.add_argument("--skip-build", action="store_true", help="package the existing local image of this version")
|
|
parser.add_argument("--python-image", default=os.environ.get("ETL_PYTHON_IMAGE", ""), help="base Python image")
|
|
parser.add_argument("--pip-index", default=os.environ.get("ETL_PIP_INDEX", ""), help="pip index URL")
|
|
parser.add_argument("--output", default=str(ROOT / "dist" / "metrix"), help="output directory")
|
|
args = parser.parse_args()
|
|
|
|
if shutil.which("docker") is None:
|
|
print("docker not found", file=sys.stderr)
|
|
return 1
|
|
current = version()
|
|
image = f"{SLUG}:{current}"
|
|
if not args.skip_build:
|
|
build_image(image, args)
|
|
target = Path(args.output).resolve() / f"{SLUG}-{current}.zip"
|
|
write_bundle(image, current, target)
|
|
size = target.stat().st_size
|
|
print(f"bundle: {target}")
|
|
print(f"size: {size / 1024 / 1024:.1f} MB ({size} bytes)")
|
|
print(f"image: {image}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|