87 lines
4.0 KiB
Python
87 lines
4.0 KiB
Python
"""Build a standalone assistant deployment archive without requiring local Docker."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
from datetime import datetime
|
|
import hashlib
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
import tarfile
|
|
|
|
from dotenv import dotenv_values
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
CONFIG_PREFIXES = ("WORK_ASSISTANT_", "DIRECT_LLM_", "OPENCLAW_", "HERMES_")
|
|
|
|
|
|
def runtime_config(root: Path) -> bytes:
|
|
# Export only the bridge/model settings, not business DB credentials or the
|
|
# unrelated full-platform API keys. Preserve the current shared secret.
|
|
values = dotenv_values(root / ".env", encoding="utf-8")
|
|
secret = values.get("WORK_ASSISTANT_SHARED_SECRET") or ""
|
|
if len(secret.strip()) < 32:
|
|
raise ValueError("请先在项目 .env 配置有效的 WORK_ASSISTANT_SHARED_SECRET(至少 32 字符)。")
|
|
selected = {key: value for key, value in values.items()
|
|
if key == "MODEL_PROVIDER" or key.startswith(CONFIG_PREFIXES)}
|
|
selected.pop("WORK_ASSISTANT_STATE_URL", None) # Container path is in compose.yml.
|
|
lines = ["# Initial assistant configuration. The deploy script preserves assistant.env."]
|
|
for key, value in sorted(selected.items()):
|
|
if value is not None:
|
|
# Mount this dotenv file directly: Compose does not interpolate its
|
|
# secrets. JSON quoting matches python-dotenv double-quoted strings.
|
|
lines.append(f"{key}={json.dumps(value, ensure_ascii=False)}")
|
|
return ("\n".join(lines) + "\n").encode("utf-8")
|
|
|
|
|
|
def add_bytes(archive: tarfile.TarFile, name: str, data: bytes, mode: int = 0o644) -> None:
|
|
item = tarfile.TarInfo(name)
|
|
item.size = len(data)
|
|
item.mode = mode
|
|
archive.addfile(item, io.BytesIO(data))
|
|
|
|
|
|
def build_package(root: Path, output: Path, version: str) -> Path:
|
|
config = runtime_config(root)
|
|
deployment = root / "deploy" / "assistant"
|
|
source = io.BytesIO()
|
|
with tarfile.open(fileobj=source, mode="w:gz") as archive:
|
|
for path in sorted((root / "app").rglob("*")):
|
|
if "__pycache__" in path.parts or path.suffix not in {".py", ".json"}:
|
|
continue
|
|
if path.is_symlink() or not path.is_file():
|
|
raise ValueError(f"无法打包源文件:{path.relative_to(root)}")
|
|
add_bytes(archive, path.relative_to(root).as_posix(), path.read_bytes())
|
|
add_bytes(archive, "requirements.txt", (root / "requirements.txt").read_bytes())
|
|
add_bytes(archive, "Dockerfile", (deployment / "Dockerfile").read_bytes())
|
|
output.mkdir(parents=True, exist_ok=True)
|
|
target = output / f"company-ai-assistant-{version}.tar.gz"
|
|
# Exclusive creation prevents accidentally replacing an existing release.
|
|
with target.open("xb") as handle:
|
|
with tarfile.open(fileobj=handle, mode="w:gz") as archive:
|
|
for name in ("compose.yml", "deploy.sh", "README.txt"):
|
|
data = (deployment / name).read_bytes().replace(b"\r\n", b"\n")
|
|
add_bytes(archive, name, data, 0o755 if name == "deploy.sh" else 0o644)
|
|
add_bytes(archive, "VERSION", (version + "\n").encode("ascii"))
|
|
add_bytes(archive, "assistant.env.initial", config, 0o600)
|
|
add_bytes(archive, "image-source.tar.gz", source.getvalue())
|
|
checksum = hashlib.sha256(target.read_bytes()).hexdigest()
|
|
target.with_name(target.name + ".sha256").write_text(
|
|
f"{checksum} {target.name}\n", encoding="ascii")
|
|
return target
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--output", type=Path, default=ROOT / "dist")
|
|
args = parser.parse_args()
|
|
package = build_package(ROOT, args.output.resolve(), datetime.now().strftime("%Y%m%d-%H%M%S"))
|
|
print(f"部署包已生成:{package}")
|
|
print(f"大小:{package.stat().st_size / 1024 / 1024:.2f} MiB;旁边附有 SHA-256 校验文件。")
|
|
print("上传并解压后执行 bash deploy.sh;更新时仍执行同一命令。")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|