镜像与构建 - 六阶段 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 进镜像
245 lines
9.2 KiB
Python
245 lines
9.2 KiB
Python
import ipaddress
|
|
from pathlib import Path
|
|
from typing import Literal
|
|
from urllib.parse import urlsplit
|
|
|
|
import yaml
|
|
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
|
|
|
|
|
def normalize_domain(value: str) -> str:
|
|
value = value.rstrip(".").lower()
|
|
try:
|
|
value = value.encode("idna").decode("ascii")
|
|
except UnicodeError:
|
|
raise ValueError("invalid domain") from None
|
|
labels = value.split(".")
|
|
if len(value) > 253 or any(
|
|
not label
|
|
or len(label) > 63
|
|
or label.startswith("-")
|
|
or label.endswith("-")
|
|
or not all(c.isascii() and (c.isalnum() or c == "-") for c in label)
|
|
for label in labels
|
|
):
|
|
raise ValueError("invalid domain")
|
|
try:
|
|
ipaddress.ip_address(value)
|
|
except ValueError:
|
|
return value
|
|
raise ValueError("IP literals are not domains")
|
|
|
|
|
|
class Model(BaseModel):
|
|
model_config = ConfigDict(extra="forbid", frozen=True)
|
|
|
|
|
|
class NetworkRule(Model):
|
|
domain: str
|
|
scheme: str = "https"
|
|
ports: list[int] = Field(default_factory=lambda: [443], min_length=1)
|
|
cidrs: list[str] = Field(default_factory=list)
|
|
|
|
@field_validator("domain")
|
|
@classmethod
|
|
def domain_valid(cls, value: str) -> str:
|
|
wildcard = value.startswith("*.")
|
|
return ("*." if wildcard else "") + normalize_domain(value[2:] if wildcard else value)
|
|
|
|
@field_validator("scheme")
|
|
@classmethod
|
|
def scheme_valid(cls, value: str) -> str:
|
|
if value not in {"https", "http"}:
|
|
raise ValueError("only http/https are supported")
|
|
return value
|
|
|
|
@field_validator("ports")
|
|
@classmethod
|
|
def ports_valid(cls, value: list[int]) -> list[int]:
|
|
if any(not 1 <= port <= 65535 for port in value):
|
|
raise ValueError("invalid port")
|
|
return value
|
|
|
|
@field_validator("cidrs")
|
|
@classmethod
|
|
def cidrs_valid(cls, value: list[str]) -> list[str]:
|
|
for item in value:
|
|
ipaddress.ip_network(item, strict=True)
|
|
return value
|
|
|
|
def matches(self, hostname: str, scheme: str, port: int) -> bool:
|
|
domain = self.domain
|
|
domain_match = (
|
|
hostname.endswith(domain[1:]) if domain.startswith("*.") else hostname == domain
|
|
)
|
|
return domain_match and scheme == self.scheme and port in self.ports
|
|
|
|
|
|
class NetworkPolicy(Model):
|
|
allow: list[NetworkRule] = Field(default_factory=list)
|
|
timeout_seconds: float = Field(default=3, gt=0, le=60)
|
|
max_response_bytes: int = Field(default=1024 * 1024, gt=0)
|
|
|
|
|
|
class LLMLoadConfig(Model):
|
|
device: str = "cpu" # vLLM backend 下无意义,保留以兼容旧配置
|
|
dtype: Literal["auto", "float16", "bfloat16", "float32"] = "auto"
|
|
revision: str | None = None
|
|
enable_thinking: bool | None = None # None = 不传该 kwarg
|
|
|
|
|
|
class LLMLimits(Model):
|
|
max_input_tokens: int = Field(default=4096, gt=0, le=32768)
|
|
max_new_tokens: int = Field(default=32, gt=0, le=512)
|
|
timeout_seconds: float = Field(default=3, gt=0, le=60)
|
|
max_concurrency: int = Field(default=1, gt=0, le=32)
|
|
queue_size: int = Field(default=8, gt=0, le=1024)
|
|
|
|
|
|
class LLMConfig(Model):
|
|
id: str = Field(pattern=r"^[a-zA-Z0-9_.-]{1,128}$")
|
|
type: Literal["guard"]
|
|
backend: Literal["transformers", "vllm"] = "transformers"
|
|
file: Path | None = None # transformers 必填
|
|
url: str | None = None # vllm 必填,必须是本机回环
|
|
served_model: str | None = None # vllm 必填,须与 /v1/models 一致
|
|
startup_timeout_seconds: float = Field(default=60, gt=0, le=600)
|
|
enabled: bool = True
|
|
load: LLMLoadConfig = Field(default_factory=LLMLoadConfig)
|
|
limits: LLMLimits = Field(default_factory=LLMLimits)
|
|
|
|
@model_validator(mode="after")
|
|
def _check_backend(self):
|
|
if self.backend == "transformers":
|
|
if self.file is None:
|
|
raise ValueError("llm.backend=transformers 需要 file")
|
|
return self
|
|
if not self.url or not self.served_model:
|
|
raise ValueError("llm.backend=vllm 需要 url 与 served_model")
|
|
host = (urlsplit(self.url).hostname or "").lower()
|
|
if host not in {"127.0.0.1", "::1", "localhost"}:
|
|
raise ValueError("llm.url 必须指向本机回环地址")
|
|
return self
|
|
|
|
|
|
class PluginLLMAccess(Model):
|
|
allow: list[str] = Field(default_factory=list)
|
|
|
|
|
|
class PluginMatch(Model):
|
|
paths: list[str] = Field(min_length=1)
|
|
|
|
@field_validator("paths")
|
|
@classmethod
|
|
def paths_valid(cls, value: list[str]) -> list[str]:
|
|
if len(value) != len(set(value)):
|
|
raise ValueError("plugin match.paths contains a duplicate path")
|
|
for path in value:
|
|
if not path.startswith("/"):
|
|
raise ValueError("plugin match.paths entries must be absolute paths")
|
|
if any(ord(char) < 0x20 or ord(char) == 0x7F for char in path):
|
|
raise ValueError("plugin match.paths entries must not contain control characters")
|
|
if any(char in path for char in "*?#"):
|
|
raise ValueError("plugin match.paths entries must be exact paths without wildcards")
|
|
return value
|
|
|
|
def matches(self, path: str) -> bool:
|
|
return path in self.paths
|
|
|
|
|
|
class PluginConfig(Model):
|
|
id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$")
|
|
file: Path
|
|
enabled: bool = True
|
|
match: PluginMatch | None = None
|
|
config: dict = Field(default_factory=dict)
|
|
network: NetworkPolicy = Field(default_factory=NetworkPolicy)
|
|
llm: PluginLLMAccess = Field(default_factory=PluginLLMAccess)
|
|
|
|
@model_validator(mode="after")
|
|
def reject_legacy_path_match(self):
|
|
if "paths" in self.config:
|
|
raise ValueError(f"plugin {self.id}: config.paths is unsupported; use match.paths")
|
|
return self
|
|
|
|
|
|
class Limits(Model):
|
|
max_sessions: int = Field(default=4, gt=0)
|
|
hook_timeout_seconds: float = Field(default=5, gt=0)
|
|
lua_memory_bytes: int = Field(default=32 * 1024 * 1024, gt=0)
|
|
max_request_bytes: int = Field(default=2 * 1024 * 1024, gt=0)
|
|
max_response_bytes: int = Field(default=2 * 1024 * 1024, gt=0)
|
|
max_sse_frame_bytes: int = Field(default=256 * 1024, gt=0)
|
|
max_plugin_buffer_bytes: int = Field(default=1024 * 1024, gt=0)
|
|
max_host_calls_per_hook: int = Field(default=64, gt=0)
|
|
max_attachment_files: int = Field(default=8, gt=0)
|
|
max_attachment_fields: int = Field(default=128, gt=0)
|
|
max_attachment_text_bytes: int = Field(default=1024 * 1024, gt=0)
|
|
max_attachment_unpacked_bytes: int = Field(default=32 * 1024 * 1024, gt=0)
|
|
max_attachment_zip_entries: int = Field(default=2048, gt=0)
|
|
attachment_timeout_seconds: float = Field(default=10, gt=0)
|
|
max_attachment_reads: int = Field(default=64, gt=0)
|
|
upstream_timeout_seconds: float = Field(default=120, gt=0)
|
|
|
|
|
|
class Settings(Model):
|
|
upstream: str
|
|
listen_host: str = "0.0.0.0"
|
|
listen_port: int = Field(default=8080, ge=1, le=65535)
|
|
limits: Limits = Field(default_factory=Limits)
|
|
llm: list[LLMConfig] = Field(default_factory=list)
|
|
plugins: list[PluginConfig] = Field(default_factory=list)
|
|
|
|
@field_validator("upstream")
|
|
@classmethod
|
|
def upstream_valid(cls, value: str) -> str:
|
|
url = urlsplit(value)
|
|
if url.scheme not in {"http", "https"} or not url.hostname or url.username is not None:
|
|
raise ValueError("invalid fixed upstream URL")
|
|
if url.query or url.fragment:
|
|
raise ValueError("upstream cannot contain query or fragment")
|
|
_ = url.port
|
|
return value.rstrip("/")
|
|
|
|
@model_validator(mode="after")
|
|
def plugins_valid(self):
|
|
ids = [p.id for p in self.plugins]
|
|
if len(ids) != len(set(ids)):
|
|
raise ValueError("duplicate plugin IDs")
|
|
model_ids = [model.id for model in self.llm]
|
|
if len(model_ids) != len(set(model_ids)):
|
|
raise ValueError("duplicate llm IDs")
|
|
models = {model.id: model for model in self.llm}
|
|
for plugin in self.plugins:
|
|
for model_id in plugin.llm.allow:
|
|
model = models.get(model_id)
|
|
if model is None:
|
|
raise ValueError(f"unknown llm model: {model_id}")
|
|
if not model.enabled:
|
|
raise ValueError(f"disabled llm model: {model_id}")
|
|
return self
|
|
|
|
|
|
def load_settings(path: str | Path) -> Settings:
|
|
path = Path(path).resolve()
|
|
with path.open(encoding="utf-8") as file:
|
|
raw = yaml.safe_load(file)
|
|
settings = Settings.model_validate(raw)
|
|
plugins = []
|
|
for plugin in settings.plugins:
|
|
file = (path.parent / plugin.file).resolve()
|
|
if not file.is_file():
|
|
raise ValueError(f"plugin file not found: {plugin.id}")
|
|
plugins.append(plugin.model_copy(update={"file": file}))
|
|
models = []
|
|
for model in settings.llm:
|
|
if model.file is None:
|
|
# backend=vllm 的条目只有 url/served_model,没有权重目录
|
|
models.append(model)
|
|
continue
|
|
file = model.file.resolve()
|
|
if not file.exists():
|
|
raise ValueError(f"llm model path not found: {model.id}")
|
|
models.append(model.model_copy(update={"file": file}))
|
|
return settings.model_copy(update={"plugins": plugins, "llm": models})
|