feat: 增加 Metrix 应用包打包脚本并完善容器镜像
This commit is contained in:
@@ -0,0 +1,128 @@
|
||||
"""把 DecomEval 打成 Metrix 应用包:dist/metrix/decomeval-<版本>.zip。
|
||||
|
||||
包里有 metrix-app.json 和镜像文件 image.tar。版本取 web/package.json 的 version 加 git 短哈希,
|
||||
工作区有未提交的改动时再加 -dirty。需要本机可用的 docker。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SLUG = "decomeval"
|
||||
NAME = "DecomEval"
|
||||
WEB_PORT = 8000
|
||||
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 version() -> str:
|
||||
base = json.loads((ROOT / "web" / "package.json").read_text(encoding="utf-8"))["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) -> dict:
|
||||
return {
|
||||
"schema": 1,
|
||||
"slug": SLUG,
|
||||
"name": NAME,
|
||||
"type": "container",
|
||||
"image": image,
|
||||
"image_file": "image.tar",
|
||||
"services": [
|
||||
{"name": "web", "command": "", "port": WEB_PORT},
|
||||
{"name": "worker", "command": "python -m worker.main"},
|
||||
],
|
||||
"postgres": {"enabled": True, "image": "postgres:16"},
|
||||
"data_dir": DATA_DIR,
|
||||
"env": {
|
||||
"DECOM_DATA_DIR": DATA_DIR,
|
||||
"DECOM_INLINE_WORKER": "0",
|
||||
"DECOM_DB_WAIT_SECONDS": "180",
|
||||
},
|
||||
"access": "public",
|
||||
}
|
||||
|
||||
|
||||
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", "-t", image]
|
||||
for key, value in (
|
||||
("NODE_IMAGE", args.node_image),
|
||||
("PYTHON_IMAGE", args.python_image),
|
||||
("NPM_REGISTRY", args.npm_registry),
|
||||
("PIP_INDEX", args.pip_index),
|
||||
):
|
||||
if value:
|
||||
command += ["--build-arg", f"{key}={value}"]
|
||||
command.append(".")
|
||||
_run(command)
|
||||
|
||||
|
||||
def write_bundle(image: str, target: Path) -> None:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
partial = target.with_name(target.name + ".partial")
|
||||
with tempfile.TemporaryDirectory(prefix="decomeval-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), ensure_ascii=False, indent=2) + "\n")
|
||||
bundle.write(tar, "image.tar")
|
||||
os.replace(partial, target)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="打包 DecomEval 为 Metrix 应用包")
|
||||
parser.add_argument("--skip-build", action="store_true", help="不重新构建,直接打包本机已有的同版本镜像")
|
||||
parser.add_argument("--node-image", default=os.environ.get("DECOM_NODE_IMAGE", ""), help="构建网页用的 Node 镜像")
|
||||
parser.add_argument("--python-image", default=os.environ.get("DECOM_PYTHON_IMAGE", ""), help="运行层用的 Python 镜像")
|
||||
parser.add_argument("--npm-registry", default=os.environ.get("DECOM_NPM_REGISTRY", ""), help="npm 源")
|
||||
parser.add_argument("--pip-index", default=os.environ.get("DECOM_PIP_INDEX", ""), help="pip 源")
|
||||
parser.add_argument("--output", default=str(ROOT / "dist" / "metrix"), help="输出目录")
|
||||
args = parser.parse_args()
|
||||
|
||||
if shutil.which("docker") is None:
|
||||
print("没有找到 docker", 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, target)
|
||||
size = target.stat().st_size
|
||||
print(f"应用包:{target}")
|
||||
print(f"大小:{size / 1024 / 1024:.1f} MB({size} 字节)")
|
||||
print(f"镜像:{image}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user