Files

336 lines
11 KiB
Python
Raw Permalink 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
"""VDE 进程外服务模板(Python 3,仅标准库)—— echo 示例服务。
复制本文件作为自定义 vde-service 的起点;保留 CLI、请求/响应字段、退出码,
把 echo 处理逻辑替换为真实算法即可。
契约(与 docs/design/vde-service-protocol.md 一致):
argv: <python> vde_service_echo.py --request <request.json> --response <response.json>
request.protocol 必须为 "vde-service/0.1"
request.request_id 必填非空字符串,响应原样回显
request.operation 固定 "echo"
request.input 可选输入文件路径(按二进制读取)
request.output 必填输出文件路径,必须位于 request.json 所在目录内
request.args.message 可选,无 input 时写入输出的文本
request.args.sleep_ms 可选测试钩子(0..300000),用于验证宿主超时终止
response.outputs[].path 返回文件名(相对 request 目录),使直接进程模式与容器模式
(/vde/work 挂载)下的宿主 outputs 白名单校验都成立。
退出码:0 成功;2 用法错误;3 协议/校验错误;5 输入输出失败。
Windows 注意:CreateProcess 不能直接执行 .py。清单 windows 项指向
vde_service_echo_launch(.exe)(见 launcher/),由它定位 python 与脚本。
POSIX 上 .py 带 shebang 并需可执行位(chmod +x)。
"""
from __future__ import annotations
import json
import os
import sys
import time
PROTOCOL = "vde-service/0.1"
SERVICE_ID = "com.vde.template.echo.python"
OPERATION = "echo"
DEFAULT_MESSAGE = "hello from vde-service template"
MAX_SLEEP_MS = 300000.0
EXIT_OK = 0
EXIT_USAGE = 2
EXIT_PROTOCOL = 3
EXIT_SERVICE_FAILED = 5
def error_response(request_id: str, code: str, message: str) -> dict:
return {
"protocol": PROTOCOL,
"request_id": request_id,
"status": "error",
"service_id": SERVICE_ID,
"code": code,
"message": message,
}
def ok_response(request_id: str, output_name: str, bytes_in: int, bytes_out: int) -> dict:
return {
"protocol": PROTOCOL,
"request_id": request_id,
"status": "ok",
"service_id": SERVICE_ID,
"outputs": [{"path": output_name, "format": "text", "role": "result"}],
"metrics": {"bytes_in": bytes_in, "bytes_out": bytes_out},
"diagnostics": [
"template echo service: replace 'echo' with real processing"
],
}
def finish(response_path: str, payload: dict, exit_code: int, to_stderr: bool) -> int:
text = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
try:
with open(response_path, "wb") as handle:
handle.write(text.encode("utf-8"))
except OSError as exc:
print(
"[vde-template] error: cannot write response '%s': %s"
% (response_path, exc),
file=sys.stderr,
)
return EXIT_PROTOCOL
print(text, file=sys.stderr if to_stderr else sys.stdout)
return exit_code
def usage() -> None:
print(
"vde_service_echo.py (VDE external service template, Python 3)\n"
"Usage: vde_service_echo.py --request <request.json> --response <response.json>\n"
"Exit codes: 0 ok, 2 usage, 3 protocol/validation error, 5 I/O failure."
)
def has_parent_segment(path: str) -> bool:
return any(part == ".." for part in path.replace("\\", "/").split("/"))
def path_within_dir(directory: str, path: str) -> bool:
try:
base = os.path.normcase(os.path.realpath(os.path.abspath(directory)))
target = os.path.normcase(os.path.realpath(os.path.abspath(path)))
if target == base:
return False
return os.path.commonpath([base, target]) == base
except (OSError, ValueError):
return False
def read_text(path: str) -> str:
with open(path, "rb") as handle:
return handle.read().decode("utf-8-sig")
def parse_args(argv: list[str]) -> tuple[str, str] | None:
request_path = ""
response_path = ""
index = 1
while index < len(argv):
arg = argv[index]
if arg in ("--help", "-h"):
usage()
return None
if arg in ("--request", "--response"):
if index + 1 >= len(argv):
print("[vde-template] error: %s needs a value" % arg, file=sys.stderr)
return None
if arg == "--request":
request_path = argv[index + 1]
else:
response_path = argv[index + 1]
index += 2
continue
print("[vde-template] error: unknown option '%s'" % arg, file=sys.stderr)
usage()
return None
if not request_path or not response_path:
usage()
return None
return request_path, response_path
def main(argv: list[str]) -> int:
parsed = parse_args(argv)
if parsed is None:
return EXIT_OK if any(a in ("--help", "-h") for a in argv[1:]) else EXIT_USAGE
request_path, response_path = parsed
try:
raw = read_text(request_path)
except OSError:
return finish(
response_path,
error_response("", "invalid_request", "cannot read request file"),
EXIT_PROTOCOL,
True,
)
try:
request = json.loads(raw)
except (ValueError, UnicodeDecodeError) as exc:
return finish(
response_path,
error_response("", "invalid_request", "invalid JSON: %s" % exc),
EXIT_PROTOCOL,
True,
)
if not isinstance(request, dict):
return finish(
response_path,
error_response("", "invalid_request", "request must be a JSON object"),
EXIT_PROTOCOL,
True,
)
request_id = request.get("request_id")
if not isinstance(request_id, str) or not request_id:
return finish(
response_path,
error_response("", "invalid_request", "request needs non-empty string 'request_id'"),
EXIT_PROTOCOL,
True,
)
if request.get("protocol") != PROTOCOL:
return finish(
response_path,
error_response(
request_id,
"bad_protocol",
"request.protocol must be '%s'" % PROTOCOL,
),
EXIT_PROTOCOL,
True,
)
operation = request.get("operation")
if not isinstance(operation, str) or not operation:
return finish(
response_path,
error_response(request_id, "invalid_request", "request needs non-empty string 'operation'"),
EXIT_PROTOCOL,
True,
)
if operation != OPERATION:
return finish(
response_path,
error_response(
request_id,
"unsupported_operation",
"only '%s' is supported, got '%s'" % (OPERATION, operation),
),
EXIT_PROTOCOL,
True,
)
output = request.get("output")
if not isinstance(output, str) or not output:
return finish(
response_path,
error_response(request_id, "invalid_request", "request needs non-empty string 'output'"),
EXIT_PROTOCOL,
True,
)
message = DEFAULT_MESSAGE
sleep_ms = 0.0
args = request.get("args")
if args is not None:
if not isinstance(args, dict):
return finish(
response_path,
error_response(request_id, "invalid_request", "request.args must be a JSON object"),
EXIT_PROTOCOL,
True,
)
if "message" in args:
if not isinstance(args["message"], str):
return finish(
response_path,
error_response(request_id, "invalid_request", "request.args.message must be a string"),
EXIT_PROTOCOL,
True,
)
message = args["message"]
if "sleep_ms" in args:
value = args["sleep_ms"]
if isinstance(value, bool) or not isinstance(value, (int, float)):
return finish(
response_path,
error_response(request_id, "invalid_request", "request.args.sleep_ms must be a number"),
EXIT_PROTOCOL,
True,
)
sleep_ms = float(value)
if sleep_ms > 0.0:
time.sleep(min(sleep_ms, MAX_SLEEP_MS) / 1000.0)
request_dir = os.path.dirname(os.path.abspath(request_path))
if has_parent_segment(output):
return finish(
response_path,
error_response(request_id, "invalid_output_path", "output path must not contain '..'"),
EXIT_PROTOCOL,
True,
)
output_path = output if os.path.isabs(output) else os.path.join(request_dir, output)
if not path_within_dir(request_dir, output_path):
return finish(
response_path,
error_response(
request_id,
"invalid_output_path",
"output path must stay inside the request directory",
),
EXIT_PROTOCOL,
True,
)
output_name = os.path.basename(os.path.normpath(output_path))
if not output_name or output_name in (".", ".."):
return finish(
response_path,
error_response(request_id, "invalid_output_path", "output path needs a file name"),
EXIT_PROTOCOL,
True,
)
content = message.encode("utf-8")
bytes_in = 0
input_value = request.get("input")
if input_value is not None:
if not isinstance(input_value, str):
return finish(
response_path,
error_response(request_id, "invalid_request", "request.input must be a string path"),
EXIT_PROTOCOL,
True,
)
if input_value:
input_path = (
input_value
if os.path.isabs(input_value)
else os.path.join(request_dir, input_value)
)
try:
with open(input_path, "rb") as handle:
content = handle.read()
except OSError:
return finish(
response_path,
error_response(
request_id, "input_not_found", "cannot read input file '%s'" % input_path
),
EXIT_SERVICE_FAILED,
True,
)
bytes_in = len(content)
try:
with open(output_path, "wb") as handle:
handle.write(content)
except OSError:
return finish(
response_path,
error_response(
request_id, "output_failed", "cannot write output file '%s'" % output_path
),
EXIT_SERVICE_FAILED,
True,
)
return finish(
response_path,
ok_response(request_id, output_name, bytes_in, len(content)),
EXIT_OK,
False,
)
if __name__ == "__main__":
sys.exit(main(sys.argv))