Files
agent-safe-middleware/scripts/pack_image.py
T
chenleixu b82e44ec32 feat: Docker 打包、交付链路与命名脱敏
镜像与构建
- 六阶段 Dockerfile(base/wheels/deps/manifest/core|guard),core 不含 torch
- 构建期自证:gen_manifest --strict 拦未登记模块,core 阶段重算 sha256
- compose 四服务 host 网络(llm.url 强制回环),config.core/local 可挂载覆盖

无 docker 环境的四段链路
- pull_oci_image.py      直拉 OCI 镜像 rootfs(纯标准库,走加速器)
- replay_image_build.sh  按 stage chroot 重放 Dockerfile
- run_image_chroot.sh    等价 docker run(uid 10001 + 入口 + host 网络)
- pack_image.py          封成 docker save 格式包,自带 diff_id 校验

交付
- make_package.sh 生成自包含目录:镜像包 + 溯源清单 + 构建输入 + 脚本 + 源码快照
- 文档:从零复现指南、docker 打包方案、镜像构建限制与替代方案、交付包 README

命名
- Qwen 品牌名统一替换为 large_model / small_model / large_model_guard,
  覆盖 vLLM 服务名、模型目录、配置、脚本、测试与文档
- 模型架构字段(architectures / model_type / tokenizer_class)属上游定义,
  改名会导致加载失败,保留原值;check_local_model.py 的架构判断同理

验证:smoke 6/6;test.py 20 通过 0 失败 1 警告;gen --strict 67 文件 / 22 进镜像
2026-11-27 18:20:16 +00:00

310 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""把 chroot 构建出来的 rootfs 打成 `docker load` 可读的镜像包(不需要 docker/daemon/特权)。
背景:某些目标机本身是无特权容器(无 CAP_SYS_ADMIN、cgroup 只读、seccomp 拦 unshare),
dockerd / podman / buildah / kaniko 都起不来,但 `chroot` 只需要 CAP_SYS_CHROOT——
这一项恰好在默认边界集里,所以能用 chroot 重放 Dockerfile。重放完得到一个完整的
rootfs,本脚本把它封成标准镜像层 + config + manifest,交给任何一台有 docker 的机器
`docker load` 即可。
产物是 docker save 的老格式(manifest.json + <config>.json + <layer>/layer.tar),
兼容性最好;层是未压缩 tar,所以 config 里的 diff_id 与层 blob 的 sha256 相同,
本脚本会把这个关系逐字节校验一遍。
sudo python3 scripts/pack_image.py --rootfs /home/chenleixu/imgroot \\
--tag agent-safe-middleware:core --out dist/asm-core-docker.tar --target core
python3 scripts/pack_image.py --verify-only dist/asm-core-docker.tar
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import platform
import sys
import tarfile
import time
# --------------------------------------------------------------------------- #
# 进镜像时应当排除的东西
# --------------------------------------------------------------------------- #
EXCLUDE_PREFIX = (
"dev/", # 设备节点由 runtime 挂 tmpfs,层里不该有
"proc/",
"sys/",
"tmp/",
"run/",
"service/models/", # 模型永远挂卷,不进镜像
)
EXCLUDE_NAMES = {"__pycache__", ".dockerenv", "resolv.conf", "hostname", "hosts"}
EXCLUDE_SUFFIX = (".pyc", ".pyo")
SKIP_TYPES = {tarfile.FIFOTYPE} # tar 格式本身没有 socket 类型,FIFO 直接跳过
def log(msg: str) -> None:
print(msg, flush=True)
def excluded(rel: str) -> bool:
if rel.startswith(EXCLUDE_PREFIX):
return True
parts = rel.rstrip("/").split("/")
if parts[-1] in EXCLUDE_NAMES:
return True
if any(p in EXCLUDE_NAMES for p in parts[:-1]):
return True
return rel.endswith(EXCLUDE_SUFFIX)
def walk(root: str):
"""确定性遍历:同一 rootfs 两次打包字节一致。目录先于内容,同级按名字排序。"""
def rec(abs_dir: str, rel_dir: str):
rel = (rel_dir + "/") if rel_dir else ""
with os.scandir(abs_dir) as it:
entries = sorted(it, key=lambda e: e.name)
for e in entries:
child_rel = rel + e.name
if excluded(child_rel):
continue
yield e.path, child_rel
if e.is_dir(follow_symlinks=False):
yield from rec(e.path, child_rel)
yield root, "."
yield from rec(root, "")
def pack_layer(root: str, layer_path: str) -> tuple[str, int, int]:
"""打一层未压缩 tar,返回 (sha256, 大小, 条目数)。"""
h = hashlib.sha256()
n = 0
with open(layer_path, "wb") as fh:
with tarfile.open(fileobj=fh, mode="w", format=tarfile.GNU_FORMAT) as tf:
for abs_path, rel in walk(root):
try:
ti = tf.gettarinfo(abs_path, arcname=rel)
except OSError as exc:
log(f" [warn] 跳过 {rel}: {exc}")
continue
if ti is None or ti.type in SKIP_TYPES:
continue
ti.uid, ti.gid = ti.uid & 0xFFFFFFFF, ti.gid & 0xFFFFFFFF
ti.uname = ti.gname = ""
if ti.isfile():
with open(abs_path, "rb") as src:
tf.addfile(ti, src)
else:
tf.addfile(ti)
n += 1
with open(layer_path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest(), os.path.getsize(layer_path), n
# --------------------------------------------------------------------------- #
# 镜像 config:与 Dockerfile 里 core 目标逐项对齐
# --------------------------------------------------------------------------- #
HEALTHCHECK_TEST = [
"CMD", "python", "-c",
"import sys,urllib.request; sys.exit(0 if urllib.request.urlopen("
"'http://127.0.0.1:8080/readyz', timeout=3).status == 200 else 1)",
]
def build_config(diff_id: str, args, layer_bytes: int, entries: int) -> dict:
created = args.created or time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
if args.target == "guard":
env = [
"PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"LANG=C.UTF-8",
"PYTHONDONTWRITEBYTECODE=1", "PYTHONUNBUFFERED=1",
"PIP_NO_CACHE_DIR=1", "PIP_DISABLE_PIP_VERSION_CHECK=1",
"PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple",
"HF_HUB_OFFLINE=1", "HF_HOME=/tmp/hf",
]
start_period = 180
else:
env = [
"PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"LANG=C.UTF-8",
"PYTHONDONTWRITEBYTECODE=1", "PYTHONUNBUFFERED=1",
"PIP_NO_CACHE_DIR=1", "PIP_DISABLE_PIP_VERSION_CHECK=1",
"PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple",
"HF_HUB_OFFLINE=1",
]
start_period = 30
return {
"architecture": args.arch or ("amd64" if platform.machine() in ("x86_64", "AMD64") else "arm64"),
"os": "linux",
"created": created,
"config": {
"Env": env,
"Entrypoint": ["agent-safe-middleware"],
"Cmd": ["--config", "/service/config.yaml"],
"WorkingDir": "/service",
"User": "10001:10001",
"ExposedPorts": {"8080/tcp": {}},
"Labels": {
"org.opencontainers.image.title": "agent-safe-middleware",
"org.opencontainers.image.description":
"Lua-first HTTP/SSE safety middleware (vLLM guard backend)",
"org.opencontainers.image.version": "0.1.0",
"org.opencontainers.image.revision": args.git_rev,
"org.opencontainers.image.created": created,
"ai.asm.target": args.target,
"ai.asm.module.registry": "deploy/docker/modules.json",
"ai.asm.module.manifest": "/service/MANIFEST.json",
"ai.asm.build.method": "chroot-replay + pack_image.py (no docker daemon)",
},
"Healthcheck": {
"Test": HEALTHCHECK_TEST,
"Interval": 15 * 10**9,
"Timeout": 5 * 10**9,
"StartPeriod": start_period * 10**9,
"Retries": 3,
},
},
"rootfs": {"type": "layers", "diff_ids": [f"sha256:{diff_id}"]},
"history": [{
"created": created,
"created_by": "pack_image.py: chroot 重放 Dockerfile 各 stage 后的 rootfs 压成单层",
"comment": f"单层 {layer_bytes/1048576:.1f} MB / {entries} 个条目;"
"层内容 = docker build 的 base+deps+wheel+core 叠加结果",
}],
}
def verify(tar_path: str, expect_tag: str | None = None) -> int:
"""读回镜像包做自证:结构、config、层 sha256 与 diff_id 是否一致。"""
errs = 0
with tarfile.open(tar_path, "r:") as tf:
names = tf.getnames()
log(f" 条目 {len(names)} 个,包体 {os.path.getsize(tar_path)/1048576:.1f} MB")
for need in ("manifest.json", "repositories"):
if need not in names:
log(f" [err] 缺 {need}"); errs += 1
if errs:
return errs
manifest = json.load(tf.extractfile("manifest.json"))
if len(manifest) != 1:
log(f" [err] manifest 条目数 {len(manifest)}"); errs += 1
m = manifest[0]
cfg_name = m["Config"]
if expect_tag and expect_tag not in m.get("RepoTags", []):
log(f" [err] RepoTags={m.get('RepoTags')} 不含 {expect_tag}"); errs += 1
cfg = json.load(tf.extractfile(cfg_name))
c = cfg["config"]
log(f" RepoTags {m.get('RepoTags')}")
log(f" Entrypoint {c.get('Entrypoint')} + Cmd {c.get('Cmd')}")
log(f" User {c.get('User')} WorkDir {c.get('WorkingDir')} "
f"Expose {list(c.get('ExposedPorts', {}))}")
log(f" Labels rev={c.get('Labels', {}).get('org.opencontainers.image.revision')} "
f"target={c.get('Labels', {}).get('ai.asm.target')}")
diff_ids = cfg["rootfs"]["diff_ids"]
if len(diff_ids) != len(m["Layers"]):
log(f" [err] diff_ids {len(diff_ids)} 个 vs 层 {len(m['Layers'])} 个"); errs += 1
for did, lname in zip(diff_ids, m["Layers"]):
h = hashlib.sha256()
n = 0
f = tf.extractfile(lname)
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk); n += len(chunk)
ok = f"sha256:{h.hexdigest()}" == did
log(f" 层 {lname} {n/1048576:.1f} MB sha256 {'一致 ✔' if ok else '不一致 ✘'}")
if not ok:
log(f" diff_id {did}\n 实际 sha256:{h.hexdigest()}"); errs += 1
# 层内自查:关键文件必须在
layer = tf.extractfile(m["Layers"][0])
with tarfile.open(fileobj=layer, mode="r:") as lt:
lnames = set(lt.getnames())
for need in ("service/config.yaml", "service/MANIFEST.json",
"usr/local/bin/agent-safe-middleware"):
hit = need in lnames or ("./" + need) in lnames
log(f" 层内 {'OK ' if hit else 'MISS'} {need}")
if not hit:
errs += 1
log(f" 无 __pycache__:{'是' if not any('__pycache__' in x for x in lnames) else '否 ✘'}")
log(f" 无 torch:{'是' if not any(x.endswith('site-packages/torch/__init__.py') for x in lnames) else '否 ✘'}")
log(f" 结果:{'全部通过 ✔' if errs == 0 else f'{errs} 项失败 ✘'}")
return errs
def main() -> int:
ap = argparse.ArgumentParser(description="把 rootfs 打成 docker load 可读的镜像包")
ap.add_argument("--rootfs", help="chroot 构建产物目录")
ap.add_argument("--tag", default="agent-safe-middleware:core")
ap.add_argument("--out", default="dist/asm-core-docker.tar")
ap.add_argument("--target", default="core", choices=["core", "guard"])
ap.add_argument("--git-rev", default="unknown")
ap.add_argument("--created", default=None, help="ISO8601,留空取当前时间")
ap.add_argument("--arch", default=None)
ap.add_argument("--workdir", default=None, help="临时目录,默认与 --out 同级的 .pack-tmp")
ap.add_argument("--verify-only", nargs="?", const=True, default=False,
help="只校验已存在的包:--verify-only <tar>")
args = ap.parse_args()
if args.verify_only:
p = args.verify_only if isinstance(args.verify_only, str) else args.out
log(f"校验 {p}")
return 1 if verify(p, args.tag) else 0
if not args.rootfs or not os.path.isdir(args.rootfs):
ap.error("--rootfs 必须是已构建好的目录")
for need in ("service/config.yaml", "usr/local/bin/agent-safe-middleware"):
if not os.path.exists(os.path.join(args.rootfs, need)):
ap.error(f"rootfs 里缺 {need},先跑 replay_image_build.sh")
os.makedirs(os.path.dirname(os.path.abspath(args.out)) or ".", exist_ok=True)
tmp = args.workdir or os.path.join(os.path.dirname(os.path.abspath(args.out)), ".pack-tmp")
os.makedirs(tmp, exist_ok=True)
log(f"[1/4] 打层:{args.rootfs} → {tmp}/layer.tar")
layer_path = os.path.join(tmp, "layer.tar")
sha, size, entries = pack_layer(args.rootfs, layer_path)
log(f" {size/1048576:.1f} MB / {entries} 条目 / sha256:{sha[:16]}…")
log("[2/4] 生成 config")
cfg = build_config(sha, args, size, entries)
cfg_bytes = json.dumps(cfg, ensure_ascii=False, separators=(",", ":")).encode()
cfg_sha = hashlib.sha256(cfg_bytes).hexdigest()
cfg_name = f"{cfg_sha}.json"
with open(os.path.join(tmp, cfg_name), "wb") as fh:
fh.write(cfg_bytes)
log(f"[3/4] 组装 {args.out}")
layer_dir = sha[:16]
manifest = [{"Config": cfg_name, "RepoTags": [args.tag], "Layers": [f"{layer_dir}/layer.tar"]}]
repo, tag = (args.tag.rsplit(":", 1) + [""])[:2] if ":" in args.tag else (args.tag, "latest")
repositories = {repo: {tag: layer_dir}}
with tarfile.open(args.out, "w", format=tarfile.GNU_FORMAT) as tf:
def add(name, data: bytes):
ti = tarfile.TarInfo(name)
ti.size, ti.mtime, ti.mode = len(data), 0, 0o644
tf.addfile(ti, __import__("io").BytesIO(data))
add("manifest.json", json.dumps(manifest, separators=(",", ":")).encode())
add(cfg_name, cfg_bytes)
add(f"{layer_dir}/VERSION", b"1.0")
add("repositories", json.dumps(repositories, separators=(",", ":")).encode())
ti = tf.gettarinfo(layer_path, arcname=f"{layer_dir}/layer.tar")
ti.uid = ti.gid = 0
ti.uname = ti.gname = ""
with open(layer_path, "rb") as fh:
tf.addfile(ti, fh)
log("[4/4] 自校验")
errs = verify(args.out, args.tag)
if errs == 0:
os.remove(layer_path)
log(f"\n完成:{args.out}\n 在有 docker 的机器上:docker load -i {os.path.basename(args.out)}")
return 1 if errs else 0
if __name__ == "__main__":
sys.exit(main())