ohos-devloop-pc 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ohos_devloop_pc/DeviceTest.hap +0 -0
- ohos_devloop_pc/__init__.py +58 -0
- ohos_devloop_pc/_version.py +24 -0
- ohos_devloop_pc/dayu600_flash_setup.py +165 -0
- ohos_devloop_pc/dayu600_skip_setup.py +314 -0
- ohos_devloop_pc/device_locks.py +332 -0
- ohos_devloop_pc/mount_ws.py +203 -0
- ohos_devloop_pc/pc_cli.py +102 -0
- ohos_devloop_pc/pc_ops.py +1387 -0
- ohos_devloop_pc/pc_service.py +1340 -0
- ohos_devloop_pc/rkflash.py +509 -0
- ohos_devloop_pc-0.4.0.dist-info/METADATA +65 -0
- ohos_devloop_pc-0.4.0.dist-info/RECORD +16 -0
- ohos_devloop_pc-0.4.0.dist-info/WHEEL +5 -0
- ohos_devloop_pc-0.4.0.dist-info/entry_points.txt +2 -0
- ohos_devloop_pc-0.4.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1387 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""PC 操作服务操作注册表(devloop-pc)——HTTP 服务与 stdio MCP 适配器共享的操作面。
|
|
4
|
+
|
|
5
|
+
背景(部署形态 B,2026-11-23):主 Agent 宿主迁到编译服务器后,设备与镜像仍是 Windows
|
|
6
|
+
侧物理资源;本模块把「下载/解包镜像」与「操作开发板」收敛成带鉴权的 PC 操作服务
|
|
7
|
+
(HTTP/JSON),服务器侧经 stdio MCP 适配器(pc_mcp.py)调用。
|
|
8
|
+
|
|
9
|
+
用法(本模块属独立发行版 ohos-devloop-pc):
|
|
10
|
+
ohos-devloop-pc serve # 起 HTTP 服务(只 bind 127.0.0.1)
|
|
11
|
+
ohos-devloop-pc ops --json # 打印 MCP tool manifest
|
|
12
|
+
python pc/ohos_devloop_pc/pc_ops.py # 脚本直跑形态(等价)
|
|
13
|
+
ohos-devloop server agent install # 部署服务器主 Agent(消费静态 tools.json)
|
|
14
|
+
|
|
15
|
+
设计约定:
|
|
16
|
+
- 本模块是纯注册表:Op 声明 + handler 实现,不碰网络、不读 token(import 期零副作用)。
|
|
17
|
+
- OpError 消息直接可执行(含修复命令/期望 vs 实际/路径),由 pc_service 映射为 400。
|
|
18
|
+
- 参数只做类型/范围/存在性校验,不接受额外键(T-261123-03:显式 op allowlist)。
|
|
19
|
+
- 信任边界:整体等价于「持有 token 即拥有 PC 开发权限」,token 是安全边界
|
|
20
|
+
(threat_model T-261123-03;RUNBOOK「部署形态 B」节)。
|
|
21
|
+
- 坑位:hdc 退出码不可信——board 侧一律以产物/输出判定(铁律 3),md5 校验双值入错。
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import base64
|
|
26
|
+
import hashlib
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import re
|
|
30
|
+
import shlex
|
|
31
|
+
import shutil
|
|
32
|
+
import subprocess
|
|
33
|
+
import sys
|
|
34
|
+
import tarfile
|
|
35
|
+
import tempfile
|
|
36
|
+
import time
|
|
37
|
+
import uuid
|
|
38
|
+
from dataclasses import dataclass
|
|
39
|
+
from datetime import datetime
|
|
40
|
+
from pathlib import Path, PurePosixPath
|
|
41
|
+
|
|
42
|
+
import yaml
|
|
43
|
+
|
|
44
|
+
# PC 发行版引导(ohos-devloop-pc):本目录与 pc/ 入 sys.path,再经 ohos_devloop_pc 注入
|
|
45
|
+
# 服务器 scripts 兄弟目录——脚本直跑与包导入两种形态都能解析扁平兄弟模块(见 pc/README.md)。
|
|
46
|
+
import sys
|
|
47
|
+
from pathlib import Path
|
|
48
|
+
|
|
49
|
+
_PC_DIR = Path(__file__).resolve().parent
|
|
50
|
+
for _cand in (str(_PC_DIR), str(_PC_DIR.parent)):
|
|
51
|
+
if _cand not in sys.path:
|
|
52
|
+
sys.path.insert(0, _cand)
|
|
53
|
+
import ohos_devloop_pc # noqa: E402,F401
|
|
54
|
+
|
|
55
|
+
import apply
|
|
56
|
+
from ohos_devloop_pc import device_locks # 包导入:避免与 pc/ 目录扁平导入产生双模块实例
|
|
57
|
+
import flash
|
|
58
|
+
import ui_probe
|
|
59
|
+
import wsroot
|
|
60
|
+
|
|
61
|
+
TOOL_NAME_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
62
|
+
TID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") # 任务 ID 白名单(统一调度标识语义)
|
|
63
|
+
RUN_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
|
|
64
|
+
DEVICE_NAME_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
|
|
65
|
+
|
|
66
|
+
# 契约版本单源(MAJOR.MINOR,H2 已确认):PC 服务对外报告的 HTTP 操作面与 MCP 工具面版本。
|
|
67
|
+
# 消费面——/healthz 载荷、/v1/ops 与 tools manifest 顶层、MCP initialize 的 serverInfo.version、
|
|
68
|
+
# pc_mcp 启动握手(同 MAJOR 且 MINOR ≥ 要求即兼容,小版本升级不打断会话)。
|
|
69
|
+
# 13-02:新增 device.lock/device.unlock/device.locks 三个 op → MINOR+1(1.0 → 1.1);
|
|
70
|
+
# pc_mcp 的 REQUIRED_* 保持 1.0(旧 kit 仍可接 1.1 服务)。
|
|
71
|
+
# 26-11-25:新增 flash.rkflash_plan/flash.rkflash_run/flash.rkflash_verify 三个 op → MINOR+1(1.1 → 1.2)。
|
|
72
|
+
# 26-11-26:新增 file.push(PC→服务器工作区写入,0.4 控制面迁服务器 D6)→ MINOR+1(1.2 → 1.3)。
|
|
73
|
+
# 26-11-26:新增 flash.pull_images(自建镜像服务器→PC 拉取)→ MINOR+1(1.3 → 1.4);
|
|
74
|
+
# board.push/board.preflight 增 expect_version(自建镜像刷板后基线动态化,形状向后兼容)。
|
|
75
|
+
# 26-11-27(双发行版合并):E2E 轮修复并入 PC 发行版——rkflash 三 op 的 config/tool/hdc 缺省化
|
|
76
|
+
# (inventory local 解析,Agent 不再需要 PC 路径);board 基线诊断标注来源(expect_version
|
|
77
|
+
# 缺省回退 PC inventory,E2E-19);新增 flash.ls(images 目录只读清单)与 job.wait(长轮询
|
|
78
|
+
# 终态,E2E-18)→ 两侧各自 1.4 合并后 MINOR+1(1.4 → 1.5)。
|
|
79
|
+
HTTP_API_VERSION = "1.5"
|
|
80
|
+
MCP_TOOLS_VERSION = "1.5"
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class OpError(Exception):
|
|
84
|
+
"""可预期的操作失败:消息直接可执行(含修复指引/双值对照),由服务映射为 400。"""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True)
|
|
88
|
+
class Op:
|
|
89
|
+
"""一条 PC 操作:HTTP op 名(board.shell)+ JSON Schema 参数 + handler。
|
|
90
|
+
|
|
91
|
+
handler 签名 (params: dict, svc: dict | None) -> dict;svc 由服务注入
|
|
92
|
+
(token_configured 等只读上下文,绝不回传 token 值)。
|
|
93
|
+
"""
|
|
94
|
+
name: str
|
|
95
|
+
title: str
|
|
96
|
+
description: str
|
|
97
|
+
params: dict # JSON Schema properties(name → schema)
|
|
98
|
+
required: tuple[str, ...]
|
|
99
|
+
handler: object
|
|
100
|
+
async_job: bool = False
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _inv() -> dict:
|
|
104
|
+
"""读 inventory(唯一事实来源):工作区优先、包缺省兜底(wsroot 语义)。"""
|
|
105
|
+
return yaml.safe_load(wsroot.inventory_path().read_text(encoding="utf-8")) or {}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _pick(mapping: dict, name: str, kind: str) -> tuple[str, dict]:
|
|
109
|
+
"""校验条目名在 inventory 内;空名取首条;否则 OpError 并列出可用名(坐标不可注入)。"""
|
|
110
|
+
if not name:
|
|
111
|
+
first = next(iter(mapping), "")
|
|
112
|
+
if not first:
|
|
113
|
+
raise OpError(f"inventory 无 {kind} 条目——先在工作区 config/inventory.yaml 配置")
|
|
114
|
+
return first, mapping[first]
|
|
115
|
+
entry = mapping.get(name)
|
|
116
|
+
if entry is None:
|
|
117
|
+
avail = "、".join(sorted(mapping)) or "无"
|
|
118
|
+
raise OpError(f"inventory.{kind} 无条目 {name!r}(可用: {avail})")
|
|
119
|
+
return name, entry
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _board(name: str = "") -> apply.Board:
|
|
123
|
+
inv = _inv()
|
|
124
|
+
bname, cfg = _pick(inv.get("boards") or {}, name, "boards")
|
|
125
|
+
return apply.Board(bname, cfg, inv.get("local") or {})
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _server(name: str = "") -> apply.Server:
|
|
129
|
+
inv = _inv()
|
|
130
|
+
sname, cfg = _pick(inv.get("servers") or {}, name, "servers")
|
|
131
|
+
return apply.Server(sname, cfg)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _ws() -> Path:
|
|
135
|
+
"""工作区根(写侧单一出口):安装态无工作区时把 WorkspaceRequiredError 包成可执行 OpError。"""
|
|
136
|
+
try:
|
|
137
|
+
return wsroot.require_ws()
|
|
138
|
+
except wsroot.WorkspaceRequiredError as e:
|
|
139
|
+
raise OpError(str(e)) from e
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _pc_data() -> Path:
|
|
143
|
+
"""服务运行数据根(inbox/evidence 等,人工按需清理;RUNBOOK 有清理口径)。"""
|
|
144
|
+
return Path.home() / ".ohos-devloop" / "pc_service"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _script_path(rel: str) -> Path:
|
|
148
|
+
return wsroot.PKG / "scripts" / rel
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _run_script(rel: str, args: list[str], timeout: int | None = None,
|
|
152
|
+
cwd: str | Path | None = None, env: dict | None = None) -> tuple[int, str, str]:
|
|
153
|
+
"""起包内脚本子进程(list 参数,禁 shell 字符串);rc!=0 抛带输出尾部的 OpError。"""
|
|
154
|
+
rc, out, err = apply.sh([sys.executable, str(_script_path(rel)), *args],
|
|
155
|
+
timeout=timeout, cwd=cwd, env=env)
|
|
156
|
+
if rc != 0:
|
|
157
|
+
raise OpError(f"{rel} 退出码 {rc}: {(out + err).strip()[-400:]}")
|
|
158
|
+
return rc, out, err
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _run_script_soft(rel: str, args: list[str], timeout: int | None = None,
|
|
162
|
+
cwd: str | Path | None = None, env: dict | None = None) -> tuple[int, str, str]:
|
|
163
|
+
"""非抛错模式:rc 与合并输出原样回传(诊断类 op 与异步 job 用)。"""
|
|
164
|
+
return apply.sh([sys.executable, str(_script_path(rel)), *args],
|
|
165
|
+
timeout=timeout, cwd=cwd, env=env)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
# --------------------------------------------------------------------------- 路径守卫
|
|
169
|
+
|
|
170
|
+
def _under(path: str, root: str) -> bool:
|
|
171
|
+
"""resolve 后 containment 判定(`..` 逃逸归一)。Windows 下 POSIX 绝对路径 resolve 为
|
|
172
|
+
当前盘绝对路径,root 同转换后比较——盘符前缀一致,包含关系不变。"""
|
|
173
|
+
try:
|
|
174
|
+
p = str(Path(path).resolve())
|
|
175
|
+
r = str(Path(root).resolve())
|
|
176
|
+
return p == r or os.path.commonpath([p, r]) == r
|
|
177
|
+
except (OSError, ValueError):
|
|
178
|
+
return False
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _glob_prefix(glob_: str) -> str:
|
|
182
|
+
"""inventory ohos_root_glob 的固定前缀(`*` 之前),rstrip('/')。"""
|
|
183
|
+
return str(glob_ or "").split("*", 1)[0].rstrip("/")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _server_path_allowed(p: str, glob_: str) -> bool:
|
|
187
|
+
"""server_path 必须落在 inventory ohos_root_glob 前缀下(T-261123-04)。
|
|
188
|
+
规范化(resolve 吞 `..`)后判定:
|
|
189
|
+
- 通配符粘在名字中段(glob `..._default_*/code`,`*` 前不是 `/`)→ 名字前缀匹配;
|
|
190
|
+
此时快照名以固定前缀开头,resolve 后逃逸出前缀区的路径不可能再命中;
|
|
191
|
+
- `*` 起于目录边界(glob `/srv/ws/*`)→ 要求「前缀 + 分隔符」开头,挡同前缀兄弟目录。
|
|
192
|
+
glob 无 `*` 或前缀为空时退化为「绝对路径」——单快照部署没有通配可推导。"""
|
|
193
|
+
if not p.startswith("/"):
|
|
194
|
+
return False
|
|
195
|
+
g = str(glob_ or "")
|
|
196
|
+
idx = g.find("*")
|
|
197
|
+
prefix = _glob_prefix(g)
|
|
198
|
+
if not prefix:
|
|
199
|
+
return True
|
|
200
|
+
root = str(Path(prefix).resolve())
|
|
201
|
+
norm = str(Path(p).resolve())
|
|
202
|
+
if norm == root:
|
|
203
|
+
return True
|
|
204
|
+
mid_segment = idx > 0 and g[idx - 1] != "/"
|
|
205
|
+
if mid_segment:
|
|
206
|
+
return norm.startswith(root)
|
|
207
|
+
return norm.startswith(root + os.sep)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _server_path_allowed_any(p: str, s: apply.Server) -> bool:
|
|
211
|
+
"""服务器路径守卫(0.4):允许落在 大仓快照(ohos_root_glob)或控制面工作区(workspace_root)。
|
|
212
|
+
|
|
213
|
+
0.4 起构建/签名产物在服务器 workspace_root 下(runs/、projects/),不再只在大仓 out/。
|
|
214
|
+
"""
|
|
215
|
+
glob_ = str(s.cfg.get("ohos_root_glob") or "")
|
|
216
|
+
if glob_ and _server_path_allowed(p, glob_):
|
|
217
|
+
return True
|
|
218
|
+
root = str(s.cfg.get("workspace_root") or "").strip()
|
|
219
|
+
return bool(root) and not root.startswith("<") and _server_path_allowed(p, root.rstrip("/") + "/*")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _device_path_allowed(p: str, device_root: str = "/system") -> bool:
|
|
223
|
+
"""device_path 必须绝对 POSIX、无 `..`,且以 device_root 或 /data/local/tmp/ 开头。"""
|
|
224
|
+
if not p.startswith("/"):
|
|
225
|
+
return False
|
|
226
|
+
if ".." in PurePosixPath(p).parts:
|
|
227
|
+
return False
|
|
228
|
+
root = device_root.rstrip("/")
|
|
229
|
+
return p == root or p.startswith(root + "/") or p.startswith("/data/local/tmp/")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _param_str(v) -> str:
|
|
233
|
+
"""apply --params 值序列化:yaml.safe_dump flow 形态 + 去掉顶层标量的文档结束标记('...'),
|
|
234
|
+
单参数 k=v 形态;apply.py 的 parse_params 用 yaml.safe_load 反解。"""
|
|
235
|
+
s = yaml.safe_dump(v, default_flow_style=True)
|
|
236
|
+
return re.sub(r"\n\.\.\.\s*$", "", s).strip()
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
# --------------------------------------------------------------------------- handlers(trace 面)
|
|
240
|
+
|
|
241
|
+
def _h_pc_info(params: dict, svc: dict | None = None) -> dict:
|
|
242
|
+
"""服务/版本/工作区/条目与就绪状态;绝不回 token 值(只回布尔)。
|
|
243
|
+
|
|
244
|
+
version 是工具包版本(apply.tool_version(),pipx 安装态),http_api_version /
|
|
245
|
+
mcp_tools_version 是接口契约版本(HTTP_API_VERSION / MCP_TOOLS_VERSION 常量)——
|
|
246
|
+
两者不是一回事:工具包可带新契约版本跑旧接口,或反之(版本握手判兼容)。
|
|
247
|
+
"""
|
|
248
|
+
inv = _inv()
|
|
249
|
+
local = inv.get("local") or {}
|
|
250
|
+
hdc = str(local.get("hdc") or "").strip()
|
|
251
|
+
if hdc.startswith("<"): # 占位串不算已配置(PUB-01 口径)
|
|
252
|
+
hdc = ""
|
|
253
|
+
ws = wsroot.ws_root()
|
|
254
|
+
return {
|
|
255
|
+
"service": "ohos-devloop-pc",
|
|
256
|
+
"version": apply.tool_version(),
|
|
257
|
+
"http_api_version": HTTP_API_VERSION,
|
|
258
|
+
"mcp_tools_version": MCP_TOOLS_VERSION,
|
|
259
|
+
"workspace": str(ws) if ws else None,
|
|
260
|
+
"hdc": hdc or None,
|
|
261
|
+
"servers": sorted(inv.get("servers") or {}),
|
|
262
|
+
"boards": sorted(inv.get("boards") or {}),
|
|
263
|
+
"token_configured": bool(svc and svc.get("token_configured")),
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _h_board_list(params: dict, svc: dict | None = None) -> dict:
|
|
268
|
+
return {"targets": _board(str(params.get("board", ""))).targets()}
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _h_board_shell(params: dict, svc: dict | None = None) -> dict:
|
|
272
|
+
b = _board(str(params.get("board", "")))
|
|
273
|
+
timeout_s = int(params.get("timeout_s", 30))
|
|
274
|
+
return {"output": b.shell(str(params["command"]), timeout=timeout_s)}
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _h_board_param(params: dict, svc: dict | None = None) -> dict:
|
|
278
|
+
b = _board(str(params.get("board", "")))
|
|
279
|
+
return {"value": b.param(str(params["key"]))}
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _h_flash_list(params: dict, svc: dict | None = None) -> dict:
|
|
283
|
+
"""非抛错模式:rc 与合并输出原样回传(供诊断,未配置目录时不吞错误)。"""
|
|
284
|
+
rc, out, err = _run_script_soft("flash.py", ["list"], timeout=120)
|
|
285
|
+
return {"rc": rc, "output": (out + ("\n" + err if err.strip() else "")).strip()}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _h_flash_ls(params: dict, svc: dict | None = None) -> dict:
|
|
289
|
+
"""images 目录只读清单(E2E-20 诊断面):根 = inventory local.images_dir。
|
|
290
|
+
|
|
291
|
+
Agent 无法 `ls D 盘`,此 op 只暴露 images 目录(与 rkflash config 缺省同根),
|
|
292
|
+
支持一层子目录;越界路径直接 400(白名单根 = images_dir)。
|
|
293
|
+
"""
|
|
294
|
+
imgs = _local_default("images_dir", "固件解压目录 images_dir")
|
|
295
|
+
root = Path(imgs).resolve()
|
|
296
|
+
sub = str(params.get("path") or "").strip().lstrip("/\\")
|
|
297
|
+
target = (root / sub if sub else root).resolve()
|
|
298
|
+
if target != root and root not in target.parents:
|
|
299
|
+
raise OpError(f"path 必须位于 images 目录内: {sub!r}")
|
|
300
|
+
try:
|
|
301
|
+
entries = []
|
|
302
|
+
for ch in sorted(target.iterdir(), key=lambda x: x.name.lower()):
|
|
303
|
+
if ch.is_dir():
|
|
304
|
+
entries.append({"name": ch.name, "type": "dir", "size": None})
|
|
305
|
+
elif ch.is_file():
|
|
306
|
+
entries.append({"name": ch.name, "type": "file",
|
|
307
|
+
"size": ch.stat().st_size})
|
|
308
|
+
except FileNotFoundError:
|
|
309
|
+
raise OpError(f"images 目录不存在: {target}")
|
|
310
|
+
return {"root": str(root), "path": "" if sub else None, "entries": entries}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _expected_baseline(b: apply.Board, params: dict) -> tuple[str, str]:
|
|
314
|
+
"""期望基线 + 来源标注(E2E-19 基线单一来源,与自建镜像动态基线合并口径)。
|
|
315
|
+
|
|
316
|
+
调用方 expect_version(服务器侧 apply/Agent 取自 board_baselines.yaml / 镜像版本)优先;
|
|
317
|
+
否则回退 PC 本地 inventory boards.<名>.software_version(旧路径兜底),报错标注来源。
|
|
318
|
+
"""
|
|
319
|
+
exp = str(params.get("expect_version") or "").strip()
|
|
320
|
+
if exp:
|
|
321
|
+
return exp, "调用方 expect_version(自建镜像刷板后的动态基线)"
|
|
322
|
+
cfg = str(b.cfg.get("software_version") or "").strip()
|
|
323
|
+
if cfg and not cfg.startswith("<"):
|
|
324
|
+
return cfg, "PC 本地 inventory boards.<名>.software_version(旧路径兜底)"
|
|
325
|
+
return "", ""
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
# --------------------------------------------------------------------------- handlers(全量面)
|
|
329
|
+
|
|
330
|
+
def _h_board_preflight(params: dict, svc: dict | None = None) -> dict:
|
|
331
|
+
"""复刻 apply.step_preflight:设备在线 + 基线版本 + 校时 + 熄屏 24h + 存量 faultlog 盘点。"""
|
|
332
|
+
b = _board(str(params.get("board", "")))
|
|
333
|
+
tgts = b.targets()
|
|
334
|
+
if not tgts:
|
|
335
|
+
raise OpError("hdc 未发现设备(hdc list targets 为空)")
|
|
336
|
+
ver = b.param("const.product.software.version")
|
|
337
|
+
expect, src = _expected_baseline(b, params) # expect_version 优先,缺省回退 inventory 并标注来源
|
|
338
|
+
if expect and expect not in ver:
|
|
339
|
+
raise OpError(f"基线不匹配: 板上 {ver!r} 不含期望 {expect!r}(来源: {src},禁止混基线推送)")
|
|
340
|
+
b.shell(f"date -s @{int(time.time())}") # 板上无 RTC:重启后必校时
|
|
341
|
+
b.shell("power-shell timeout -o 86400000") # 熄屏 30s 打断长取证:调 24h(重启后失效)
|
|
342
|
+
faults = b.shell("ls /data/log/faultlog/faultlogger 2>/dev/null | tail -5", timeout=20)
|
|
343
|
+
return {"device": tgts[:2], "version": ver, "timesync": "done",
|
|
344
|
+
"screen_timeout": "24h", "pre_faults": faults.strip()[:300]}
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _h_board_push(params: dict, svc: dict | None = None) -> dict:
|
|
348
|
+
"""推板:保留完整保护链(RUNBOOK 铁律)——基线预检 → scp 拉取 → 板端备份 → remount →
|
|
349
|
+
send → md5 双值比对 → chmod → sync;任一步失败即中止(T-261123-04 路径守卫先行)。"""
|
|
350
|
+
server_path = str(params["server_path"])
|
|
351
|
+
device_path = str(params["device_path"])
|
|
352
|
+
b = _board(str(params.get("board", "")))
|
|
353
|
+
s = _server(str(params.get("server", "")))
|
|
354
|
+
if not _server_path_allowed_any(server_path, s):
|
|
355
|
+
raise OpError(f"server_path 不在服务器大仓或工作区前缀下: {server_path}")
|
|
356
|
+
if not _device_path_allowed(device_path, str(b.cfg.get("device_root", "/system"))):
|
|
357
|
+
raise OpError(f"device_path 非法(须以 device_root 或 /data/local/tmp/ 开头且无 ..): {device_path}")
|
|
358
|
+
|
|
359
|
+
# ① 基线预检(禁止混基线,RUNBOOK 铁律 2):expect_version(自建镜像动态基线)压过 inventory;
|
|
360
|
+
# E2E-19:期望来源在报错里标注,漂移可诊断
|
|
361
|
+
ver = b.param("const.product.software.version")
|
|
362
|
+
expect, src = _expected_baseline(b, params)
|
|
363
|
+
if expect and expect not in ver:
|
|
364
|
+
raise OpError(f"基线不匹配: 板上 {ver!r} 不含期望 {expect!r}"
|
|
365
|
+
f"(来源: {src},禁止混基线推送)")
|
|
366
|
+
|
|
367
|
+
# ② 从服务器 scp 拉取到 inbox(uuid 隔离,避免并发写同一路径)
|
|
368
|
+
inbox = _pc_data() / "inbox" / uuid.uuid4().hex
|
|
369
|
+
local = inbox / Path(server_path).name
|
|
370
|
+
s.scp_get(server_path, local)
|
|
371
|
+
|
|
372
|
+
# ③ 设备端存在性检查/备份(任何一项备份失败都不允许写入)
|
|
373
|
+
backed_up, backup_path = False, ""
|
|
374
|
+
backup_local = inbox / "backup" / Path(device_path).name
|
|
375
|
+
if b.recv(device_path, backup_local):
|
|
376
|
+
backed_up = True
|
|
377
|
+
backup_dir = str(b.cfg.get("backup_dir") or "").strip()
|
|
378
|
+
if backup_dir and not backup_dir.startswith("<"): # 占位符不算配置(PUB-01 口径)
|
|
379
|
+
dst = Path(backup_dir) / expect / datetime.now().strftime("%Y%m%d") / Path(device_path).name
|
|
380
|
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
|
381
|
+
shutil.copy2(backup_local, dst)
|
|
382
|
+
backup_path = str(dst)
|
|
383
|
+
|
|
384
|
+
# ④ remount → send → md5 双值比对(hdc 退出码不可信,铁律 3)→ chmod 644 → sync
|
|
385
|
+
b.remount_rw()
|
|
386
|
+
b.send(local, device_path)
|
|
387
|
+
local_md5 = hashlib.md5(local.read_bytes()).hexdigest()
|
|
388
|
+
dev_md5 = b.md5(device_path)
|
|
389
|
+
if local_md5 != dev_md5:
|
|
390
|
+
raise OpError(f"md5 不一致(hdc 退出码不可信的典型场景): local={local_md5} device={dev_md5}")
|
|
391
|
+
b.shell(f"chmod 644 {shlex.quote(device_path)}")
|
|
392
|
+
b.shell("sync")
|
|
393
|
+
return {"md5": dev_md5, "backed_up": backed_up, "backup_path": backup_path or None,
|
|
394
|
+
"device_version": ver}
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _h_board_install(params: dict, svc: dict | None = None) -> dict:
|
|
398
|
+
"""装 hap:校时 → uninstall(脏代码缓存坑)→ install → bm dump 含 applicationinfo 才算成功。"""
|
|
399
|
+
server_path = str(params["server_path"])
|
|
400
|
+
bundle = str(params["bundle"])
|
|
401
|
+
b = _board(str(params.get("board", "")))
|
|
402
|
+
s = _server(str(params.get("server", "")))
|
|
403
|
+
if not server_path.lower().endswith(".hap"):
|
|
404
|
+
raise OpError(f"server_path 必须是 .hap 文件: {server_path}")
|
|
405
|
+
if not _server_path_allowed_any(server_path, s):
|
|
406
|
+
raise OpError(f"server_path 不在服务器大仓或工作区前缀下: {server_path}")
|
|
407
|
+
# 0.4:hap 在服务器侧构建/签名 → 拉到 PC inbox 再装(hdc 只认本地文件)
|
|
408
|
+
inbox = _pc_data() / "inbox" / uuid.uuid4().hex
|
|
409
|
+
hap = inbox / Path(server_path).name
|
|
410
|
+
s.scp_get(server_path, hap)
|
|
411
|
+
if not hap.is_file() or hap.stat().st_size == 0:
|
|
412
|
+
raise OpError(f"hap 拉取失败或为空: {server_path}")
|
|
413
|
+
b.shell(f"date -s @{int(time.time())}") # 板上无 RTC:时钟漂移会让 profile validity 判定失败
|
|
414
|
+
b.raw("shell", f"bm uninstall -n {bundle}") # install 前必 uninstall(未安装时卸载失败无害)
|
|
415
|
+
time.sleep(2)
|
|
416
|
+
_, out, err = b.raw("install", str(hap), timeout=120)
|
|
417
|
+
dump = b.shell(f"bm dump -n {bundle}", timeout=30)
|
|
418
|
+
if "applicationinfo" not in dump.lower():
|
|
419
|
+
raise OpError(f"bm dump 未见 applicationInfo(安装失败): {(out + err)[:300]}")
|
|
420
|
+
return {"bundle": bundle, "bm_dump_head": dump[:300]}
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _h_board_screenshot(params: dict, svc: dict | None = None) -> dict:
|
|
424
|
+
"""snapshot_display 截图 → recv(落盘为准)→ rm;回 path/sha256/size/base64(>4MiB 置空)。"""
|
|
425
|
+
b = _board(str(params.get("board", "")))
|
|
426
|
+
ev = _pc_data() / "evidence" / datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
427
|
+
ev.mkdir(parents=True, exist_ok=True)
|
|
428
|
+
dev = f"/data/local/tmp/pc_shot_{uuid.uuid4().hex}.jpeg"
|
|
429
|
+
b.shell(f"snapshot_display -f {dev}", timeout=30)
|
|
430
|
+
local = ev / f"shot_{uuid.uuid4().hex}.jpeg"
|
|
431
|
+
if not b.recv(dev, local):
|
|
432
|
+
raise OpError(f"截图拉取失败(snapshot_display 退出码不可信): {dev}")
|
|
433
|
+
b.shell(f"rm -f {dev}")
|
|
434
|
+
raw = local.read_bytes()
|
|
435
|
+
sha256 = hashlib.sha256(raw).hexdigest()
|
|
436
|
+
if len(raw) > 4 * 1024 * 1024:
|
|
437
|
+
return {"path": str(local), "sha256": sha256, "size": len(raw), "base64": None,
|
|
438
|
+
"hint": "原始文件 >4MiB,base64 省略(用 path 取原图)"}
|
|
439
|
+
return {"path": str(local), "sha256": sha256, "size": len(raw),
|
|
440
|
+
"base64": base64.b64encode(raw).decode("ascii")}
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _h_board_hilog(params: dict, svc: dict | None = None) -> dict:
|
|
444
|
+
"""hilog -x 尾部:原始输出截断保留尾部 2MiB 并回 truncated 标记。"""
|
|
445
|
+
b = _board(str(params.get("board", "")))
|
|
446
|
+
lines = int(params.get("lines", 200))
|
|
447
|
+
out = b.shell("hilog -x", timeout=60)
|
|
448
|
+
raw = out.encode("utf-8", errors="replace")
|
|
449
|
+
truncated = len(raw) > 2 * 1024 * 1024
|
|
450
|
+
tail = raw[-2 * 1024 * 1024:].decode("utf-8", errors="replace")
|
|
451
|
+
return {"lines": lines, "truncated": truncated,
|
|
452
|
+
"tail": "\n".join(tail.splitlines()[-lines:])}
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def _h_flash_fetch(params: dict, svc: dict | None = None) -> dict:
|
|
456
|
+
device = str(params.get("device", "dayu200"))
|
|
457
|
+
if not DEVICE_NAME_RE.match(device):
|
|
458
|
+
raise OpError(f"device 名非法(仅 ^[A-Za-z0-9._-]{{1,64}}$): {device!r}")
|
|
459
|
+
rc, out, err = _run_script_soft("flash.py", ["fetch", device], timeout=1800)
|
|
460
|
+
return {"rc": rc, "output_tail": (out + err).strip()[-2000:]}
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _h_flash_extract(params: dict, svc: dict | None = None) -> dict:
|
|
464
|
+
archive = str(params.get("archive", "") or "")
|
|
465
|
+
if archive:
|
|
466
|
+
p = Path(archive)
|
|
467
|
+
if not p.is_absolute():
|
|
468
|
+
raise OpError(f"archive 必须是绝对路径: {archive}")
|
|
469
|
+
if not p.is_file():
|
|
470
|
+
raise OpError(f"固件包不存在: {archive}")
|
|
471
|
+
if not (str(p).endswith(".tar.gz") or str(p).endswith(".tgz")):
|
|
472
|
+
raise OpError(f"archive 必须是 .tar.gz/.tgz: {archive}")
|
|
473
|
+
args = ["extract", archive]
|
|
474
|
+
else:
|
|
475
|
+
args = ["extract"] # 缺省自动选 download/ 下最新
|
|
476
|
+
rc, out, err = _run_script_soft("flash.py", args, timeout=1800)
|
|
477
|
+
return {"rc": rc, "output_tail": (out + err).strip()[-2000:]}
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def _h_flash_sync_repo(params: dict, svc: dict | None = None) -> dict:
|
|
481
|
+
root = str(params.get("root", "") or "")
|
|
482
|
+
task_id = str(params.get("task_id", "") or "")
|
|
483
|
+
if task_id and not TID_RE.match(task_id):
|
|
484
|
+
raise OpError(f"task_id 非法(TID 白名单): {task_id!r}")
|
|
485
|
+
args = ["sync-repo"] + ([root] if root else []) + ([task_id] if task_id else [])
|
|
486
|
+
s = _server(str(params.get("server", "")))
|
|
487
|
+
rc, out = _remote_cli(s, ["flash", *args], 3600)
|
|
488
|
+
return {"rc": rc, "output_tail": out[-2000:]}
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _h_pool_status(params: dict, svc: dict | None = None) -> dict:
|
|
492
|
+
s = _server(str(params.get("server", "")))
|
|
493
|
+
rc, out = _remote_cli(s, ["flash", "pool", "status"], 180)
|
|
494
|
+
return {"rc": rc, "output": out}
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _h_pool_claim(params: dict, svc: dict | None = None) -> dict:
|
|
498
|
+
workspace = str(params["workspace"])
|
|
499
|
+
task_id = str(params["task_id"])
|
|
500
|
+
if not TID_RE.match(task_id):
|
|
501
|
+
raise OpError(f"task_id 非法(TID 白名单): {task_id!r}")
|
|
502
|
+
s = _server(str(params.get("server", "")))
|
|
503
|
+
rc, out = _remote_cli(s, ["flash", "pool", "claim", workspace, task_id], 120)
|
|
504
|
+
if rc != 0:
|
|
505
|
+
raise OpError(f"pool claim 失败(rc={rc}): {out[-400:]}")
|
|
506
|
+
return {"output": out}
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _h_pool_release(params: dict, svc: dict | None = None) -> dict:
|
|
510
|
+
s = _server(str(params.get("server", "")))
|
|
511
|
+
rc, out = _remote_cli(s, ["flash", "pool", "release", str(params["workspace"])], 120)
|
|
512
|
+
if rc != 0:
|
|
513
|
+
raise OpError(f"pool release 失败(rc={rc}): {out[-400:]}")
|
|
514
|
+
return {"output": out}
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
# --------------------------------------------------------------------------- 设备占用登记
|
|
518
|
+
|
|
519
|
+
def _device_store(svc: dict | None) -> device_locks.LockStore:
|
|
520
|
+
"""从服务注入面取登记存储;缺失即接线错误(测试直调 handler 时同样暴露)。"""
|
|
521
|
+
store = (svc or {}).get("locks")
|
|
522
|
+
if not isinstance(store, device_locks.LockStore):
|
|
523
|
+
raise OpError("服务未注入设备占用登记存储(内部接线错误:build_handler 应传 locks)")
|
|
524
|
+
return store
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _targets_safe() -> tuple[list[str], str | None]:
|
|
528
|
+
"""hdc 在线清单的安全获取:故障降级为 ([], note),绝不把 hdc 故障误报成「设备已释放」。"""
|
|
529
|
+
try:
|
|
530
|
+
return list(_board("").targets()), None
|
|
531
|
+
except Exception as e: # noqa: BLE001 - hdc/inventory 任何故障都只降级为保守呈现
|
|
532
|
+
return [], f"hdc 不可用,在线状态未知(登记设备按失联保守处理): {e}"
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _pool_safe() -> tuple[list[dict], bool]:
|
|
536
|
+
"""workspace_pool.yaml 的安全读取:(rows, initialized);无工作区/无文件/坏文件均降级空池。"""
|
|
537
|
+
try:
|
|
538
|
+
pf = flash.pool_file()
|
|
539
|
+
if not pf.is_file():
|
|
540
|
+
return [], False
|
|
541
|
+
return list(flash.load_pool()), True
|
|
542
|
+
except (wsroot.WorkspaceRequiredError, OSError, ValueError):
|
|
543
|
+
return [], False
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def _h_device_lock(params: dict, svc: dict | None = None) -> dict:
|
|
547
|
+
"""登记设备占用(不查 hdc 在线:锁的是身份不是在场——失联设备也可能被登记)。
|
|
548
|
+
|
|
549
|
+
互斥语义由 store 强制:同 task 幂等、异 task 拒绝并点名占用方(HTTP 400)。
|
|
550
|
+
"""
|
|
551
|
+
serial = str(params["device_serial"])
|
|
552
|
+
task_id = str(params["task_id"])
|
|
553
|
+
workspace = str(params["workspace"])
|
|
554
|
+
if not DEVICE_NAME_RE.match(serial):
|
|
555
|
+
raise OpError(f"device_serial 非法(仅 ^[A-Za-z0-9._-]{{1,64}}$): {serial!r}")
|
|
556
|
+
if not TID_RE.match(task_id):
|
|
557
|
+
raise OpError(f"task_id 非法(TID 白名单): {task_id!r}")
|
|
558
|
+
if not workspace.strip():
|
|
559
|
+
raise OpError("workspace 不能为空——填写该任务领取的工作区路径")
|
|
560
|
+
try:
|
|
561
|
+
return _device_store(svc).lock(serial, task_id, workspace)
|
|
562
|
+
except device_locks.LockError as e:
|
|
563
|
+
raise OpError(str(e)) from e
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def _h_device_unlock(params: dict, svc: dict | None = None) -> dict:
|
|
567
|
+
"""释放设备占用:正常释放幂等;异常遗留(task 不符/holder 不存活/失联)须 confirm_abandoned。"""
|
|
568
|
+
serial = str(params["device_serial"])
|
|
569
|
+
task_id = str(params["task_id"])
|
|
570
|
+
confirm = bool(params.get("confirm_abandoned", False))
|
|
571
|
+
if not DEVICE_NAME_RE.match(serial):
|
|
572
|
+
raise OpError(f"device_serial 非法(仅 ^[A-Za-z0-9._-]{{1,64}}$): {serial!r}")
|
|
573
|
+
if not TID_RE.match(task_id):
|
|
574
|
+
raise OpError(f"task_id 非法(TID 白名单): {task_id!r}")
|
|
575
|
+
targets, _note = _targets_safe() # hdc 故障只影响 device_present(保守按失联)
|
|
576
|
+
try:
|
|
577
|
+
return _device_store(svc).unlock(serial, task_id, confirm_abandoned=confirm,
|
|
578
|
+
device_present=serial in targets)
|
|
579
|
+
except device_locks.LockError as e:
|
|
580
|
+
raise OpError(str(e)) from e
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _h_device_locks(params: dict, svc: dict | None = None) -> dict:
|
|
584
|
+
"""设备占用查询:每台设备 free/held/lost + 工作区池对账(WARN 只读呈现,不自动改写)。"""
|
|
585
|
+
targets, hdc_note = _targets_safe()
|
|
586
|
+
rows, initialized = _pool_safe()
|
|
587
|
+
try:
|
|
588
|
+
return _device_store(svc).query(targets, rows, initialized, note=hdc_note)
|
|
589
|
+
except device_locks.LockError as e:
|
|
590
|
+
raise OpError(str(e)) from e
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _h_ui_dump(params: dict, svc: dict | None = None) -> dict:
|
|
594
|
+
b = _board(str(params.get("board", "")))
|
|
595
|
+
ev = _pc_data() / "evidence" / datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
596
|
+
ev.mkdir(parents=True, exist_ok=True)
|
|
597
|
+
out = ev / "layout.json"
|
|
598
|
+
ui_probe.dump_layout(out, hdc=b._argv(), settle_s=float(params.get("settle_s", 0.5)))
|
|
599
|
+
return {"layout": json.loads(out.read_text(encoding="utf-8")), "path": str(out)}
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def _h_ui_click(params: dict, svc: dict | None = None) -> dict:
|
|
603
|
+
b = _board(str(params.get("board", "")))
|
|
604
|
+
sel = params.get("selector") or {}
|
|
605
|
+
r = ui_probe.resolve_and_click(sel, hdc=b._argv(),
|
|
606
|
+
settle_s=float(params.get("settle_s", 1.5)))
|
|
607
|
+
if not r["ok"]:
|
|
608
|
+
raise OpError(f"选择器无匹配或 uinput 失败: {sel}(用 ui_dump 查树内容)")
|
|
609
|
+
detail = {"selector": sel, "clicked_text": ui_probe.node_text(r["node"]),
|
|
610
|
+
"x": r["x"], "y": r["y"]}
|
|
611
|
+
if params.get("dump_after", True):
|
|
612
|
+
ev = _pc_data() / "evidence" / datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
613
|
+
ev.mkdir(parents=True, exist_ok=True)
|
|
614
|
+
out = ev / "layout.json"
|
|
615
|
+
ui_probe.dump_layout(out, hdc=b._argv(), settle_s=0.3)
|
|
616
|
+
detail["after_layout"] = str(out)
|
|
617
|
+
return detail
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _h_sign_hap(params: dict, svc: dict | None = None) -> dict:
|
|
621
|
+
"""离线签名(debug 需板在线取 UDID;release 跨设备免 UDID)。HDC env 传 hdc 前缀参数整串,
|
|
622
|
+
sign_hap.py 侧 shlex 切分回 list(与 apply.step_hap_sign 同款)。"""
|
|
623
|
+
project = str(params["project"])
|
|
624
|
+
mode = str(params.get("mode", "debug"))
|
|
625
|
+
if mode not in ("debug", "release"):
|
|
626
|
+
raise OpError(f"mode 必须是 debug|release: {mode!r}")
|
|
627
|
+
p = Path(project)
|
|
628
|
+
if not (p / "AppScope" / "app.json5").is_file():
|
|
629
|
+
raise OpError(f"project 必须是含 AppScope/app.json5 的工程目录: {project}")
|
|
630
|
+
b = _board("")
|
|
631
|
+
env = dict(os.environ)
|
|
632
|
+
env["HDC"] = " ".join(shlex.quote(x) for x in b._argv())
|
|
633
|
+
rc, out, err = _run_script_soft("sign_hap.py", [project, "--mode", mode], timeout=600, env=env)
|
|
634
|
+
if rc != 0:
|
|
635
|
+
raise OpError(f"签名失败(rc={rc}): {(out + err).strip()[-400:]}")
|
|
636
|
+
signed_path = ""
|
|
637
|
+
m = re.search(r"^signed:\s*(.+?)(?:\s+\(bundle=.*)?$", (out + err), re.M)
|
|
638
|
+
if m:
|
|
639
|
+
signed_path = m.group(1).strip()
|
|
640
|
+
size = Path(signed_path).stat().st_size if signed_path and Path(signed_path).is_file() else None
|
|
641
|
+
return {"mode": mode, "signed": signed_path or None, "size": size,
|
|
642
|
+
"output_tail": (out + err).strip()[-2000:]}
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def _apply_args(spec: str, run: bool, run_id: str, params: dict) -> list[str]:
|
|
646
|
+
"""服务器 CLI 调用面:plan/run 共用,params 以 --params k=v(yaml 序列化单参数)。"""
|
|
647
|
+
args = ["apply", spec, "run" if run else "plan"]
|
|
648
|
+
if run:
|
|
649
|
+
args += ["--run-id", run_id]
|
|
650
|
+
if params.get("only"):
|
|
651
|
+
args += ["--only", str(params["only"])]
|
|
652
|
+
if params.get("from_step"):
|
|
653
|
+
args += ["--from-step", str(params["from_step"])]
|
|
654
|
+
if params.get("keep_going"):
|
|
655
|
+
args.append("--keep-going")
|
|
656
|
+
pairs = [f"{k}={_param_str(v)}" for k, v in (params.get("params") or {}).items()]
|
|
657
|
+
if pairs:
|
|
658
|
+
# apply 的 --params 是 nargs="*":重复出现只保留最后一次,因此必须一次给全
|
|
659
|
+
args += ["--params", *pairs]
|
|
660
|
+
return args
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
# 0.4 控制面迁服务器(D2/D3):apply/pool 的写面在服务器工作区,PC 侧只做 ssh shim。
|
|
664
|
+
CLI_REMOTE = "~/devloop/bin/ohos-devloop"
|
|
665
|
+
RC_MARK = "__DEVLOOP_RC__"
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def _server_workspace(s: apply.Server) -> str:
|
|
669
|
+
root = str(s.cfg.get("workspace_root") or "").strip()
|
|
670
|
+
if not root or root.startswith("<"):
|
|
671
|
+
raise OpError("inventory servers.<名>.workspace_root 未配置(0.4 控制面在服务器需要它,"
|
|
672
|
+
"例如 /root/devloop-workspace)")
|
|
673
|
+
return root
|
|
674
|
+
|
|
675
|
+
|
|
676
|
+
def _remote_cli(s: apply.Server, argv: list[str], timeout: int) -> tuple[int, str]:
|
|
677
|
+
"""服务器侧 CLI:cwd=工作区 → `~/devloop/bin/ohos-devloop <argv>` → rc 哨兵。
|
|
678
|
+
|
|
679
|
+
list 元素全量 shlex.quote;返回 (rc, 合并输出)。绝不本地执行 spec。
|
|
680
|
+
"""
|
|
681
|
+
root = _server_workspace(s)
|
|
682
|
+
line = " ".join(shlex.quote(arg) for arg in argv)
|
|
683
|
+
# kit 环境(DEVLOOP_PC_URL/TOKEN_FILE):板侧 transport=pc 与 MCP 直调都需要。
|
|
684
|
+
# devloop-env 自带 set -euo,source 后必须还原,避免未定义变量让后续命令中止;
|
|
685
|
+
# 文件缺失时静默跳过(非板类 job 不依赖它)。
|
|
686
|
+
env_prefix = ('set -a; [ -f "$HOME/devloop/bin/devloop-env" ] && '
|
|
687
|
+
'. "$HOME/devloop/bin/devloop-env" >/dev/null 2>&1; '
|
|
688
|
+
'set +a; set +eu; ')
|
|
689
|
+
cmd = (env_prefix + "cd " + shlex.quote(root) + " && " + CLI_REMOTE + " " + line
|
|
690
|
+
+ " 2>&1; printf '\\n" + RC_MARK + "%s\\n' \"$?\"")
|
|
691
|
+
out = s.ssh(cmd, timeout=timeout, check=False)
|
|
692
|
+
rc = -1
|
|
693
|
+
kept: list[str] = []
|
|
694
|
+
for ln in out.splitlines():
|
|
695
|
+
if ln.startswith(RC_MARK):
|
|
696
|
+
try:
|
|
697
|
+
rc = int(ln[len(RC_MARK):].strip())
|
|
698
|
+
except ValueError:
|
|
699
|
+
rc = -1
|
|
700
|
+
continue
|
|
701
|
+
kept.append(ln)
|
|
702
|
+
return rc, "\n".join(kept).strip()
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def _remote_read(s: apply.Server, path: str) -> tuple[int, str]:
|
|
706
|
+
"""读服务器文件(run 档案):cat + rc 哨兵,缺失/不可读按 rc!=0 返回。"""
|
|
707
|
+
cmd = (f"cat {shlex.quote(path)} 2>&1; printf '\\n{RC_MARK}%s\\n' \"$?\"")
|
|
708
|
+
out = s.ssh(cmd, timeout=60, check=False)
|
|
709
|
+
rc = -1
|
|
710
|
+
kept: list[str] = []
|
|
711
|
+
for ln in out.splitlines():
|
|
712
|
+
if ln.startswith(RC_MARK):
|
|
713
|
+
try:
|
|
714
|
+
rc = int(ln[len(RC_MARK):].strip())
|
|
715
|
+
except ValueError:
|
|
716
|
+
rc = -1
|
|
717
|
+
continue
|
|
718
|
+
kept.append(ln)
|
|
719
|
+
return rc, "\n".join(kept).strip()
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def _apply_spec(spec: str, s: apply.Server) -> str:
|
|
723
|
+
"""spec 是服务器侧 POSIX 路径:以 `/` 开头即绝对,必须落在服务器工作区内;
|
|
724
|
+
其余按服务器工作区 cwd 解析(不能用 os.path.isabs——Windows 会把 `/root/...` 判成相对)。"""
|
|
725
|
+
if spec.startswith("/"):
|
|
726
|
+
root = _server_workspace(s)
|
|
727
|
+
if not _server_path_allowed(spec, root.rstrip("/") + "/*"):
|
|
728
|
+
raise OpError(f"spec 绝对路径必须在服务器工作区内: {spec}(工作区 {root})")
|
|
729
|
+
return spec
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def _h_apply_plan(params: dict, svc: dict | None = None) -> dict:
|
|
733
|
+
spec = str(params["spec"])
|
|
734
|
+
s = _server(str(params.get("server", "")))
|
|
735
|
+
rc, out = _remote_cli(s, _apply_args(_apply_spec(spec, s), False, "", params), 120)
|
|
736
|
+
return {"rc": rc, "output": out[-4000:]}
|
|
737
|
+
|
|
738
|
+
|
|
739
|
+
def _h_apply_run(params: dict, svc: dict | None = None) -> dict:
|
|
740
|
+
spec = str(params["spec"])
|
|
741
|
+
s = _server(str(params.get("server", "")))
|
|
742
|
+
_apply_spec(spec, s)
|
|
743
|
+
run_id = f"pc-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
|
|
744
|
+
rc, out = _remote_cli(s, _apply_args(spec, True, run_id, params), 86400)
|
|
745
|
+
return {"rc": rc, "run_id": run_id, "output_tail": out[-2000:]}
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def _h_apply_results(params: dict, svc: dict | None = None) -> dict:
|
|
749
|
+
run_id = str(params["run_id"])
|
|
750
|
+
if not RUN_ID_RE.match(run_id):
|
|
751
|
+
raise OpError(f"run_id 非法(白名单): {run_id!r}")
|
|
752
|
+
s = _server(str(params.get("server", "")))
|
|
753
|
+
path = f"{_server_workspace(s)}/runs/{run_id}/results.json"
|
|
754
|
+
rc, text = _remote_read(s, path)
|
|
755
|
+
if rc != 0:
|
|
756
|
+
raise OpError(f"run 档案不存在或不可读: {path}({text[:200]})")
|
|
757
|
+
try:
|
|
758
|
+
return json.loads(text)
|
|
759
|
+
except ValueError as e:
|
|
760
|
+
raise OpError(f"run 档案不是合法 JSON({path}): {e}") from e
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
# --------------------------------------------------------------------------- file(PC→服务器写入)
|
|
764
|
+
|
|
765
|
+
def _sha256_file(path: Path) -> str:
|
|
766
|
+
"""流式 sha256(工程/截图可达百 MB,不整文件读入内存)。"""
|
|
767
|
+
h = hashlib.sha256()
|
|
768
|
+
with path.open("rb") as f:
|
|
769
|
+
for chunk in iter(lambda: f.read(1 << 16), b""):
|
|
770
|
+
h.update(chunk)
|
|
771
|
+
return h.hexdigest()
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
def _iter_tree(root: Path) -> list[Path]:
|
|
775
|
+
"""工程树文件枚举:跳过构建产物/IDE/版本库目录(与 apply.HAP_BUILD_EXCLUDES 同源)。"""
|
|
776
|
+
files: list[Path] = []
|
|
777
|
+
for p in sorted(root.rglob("*")):
|
|
778
|
+
rel = p.relative_to(root)
|
|
779
|
+
if any(part in apply.HAP_BUILD_EXCLUDES for part in rel.parts):
|
|
780
|
+
continue
|
|
781
|
+
if p.is_file():
|
|
782
|
+
files.append(p)
|
|
783
|
+
return files
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def _h_file_push(params: dict, svc: dict | None = None) -> dict:
|
|
787
|
+
"""PC 本地文件/目录 → 服务器工作区(D6):白名单 → 覆盖门 → 推送 → size+sha256 双值对账。
|
|
788
|
+
|
|
789
|
+
仅服务于「PC 是数据源、服务器是权威归档」的方向:B0 工程同步、截图原图与板端备份归档、
|
|
790
|
+
签名材料轮换。目的路径必须落在 inventory servers.<名>.workspace_root 之下(防任意写)。
|
|
791
|
+
目录模式:本地打包 tar.gz(排除构建产物)+ 逐文件 sha256 清单,远端解包后
|
|
792
|
+
`sha256sum -c` 回验,任一文件不符即 fail-closed。
|
|
793
|
+
"""
|
|
794
|
+
local = str(params["local"])
|
|
795
|
+
server_path = str(params["server_path"])
|
|
796
|
+
src = Path(local)
|
|
797
|
+
if not src.is_absolute():
|
|
798
|
+
raise OpError(f"local 必须是 PC 侧绝对路径: {local}")
|
|
799
|
+
if not src.exists():
|
|
800
|
+
raise OpError(f"local 不存在: {local}")
|
|
801
|
+
cap_mb = int(params.get("max_size_mb", 512))
|
|
802
|
+
|
|
803
|
+
s = _server(str(params.get("server", "")))
|
|
804
|
+
root = str(s.cfg.get("workspace_root") or "").strip()
|
|
805
|
+
if not root or root.startswith("<"):
|
|
806
|
+
raise OpError("inventory servers.<名>.workspace_root 未配置(服务器工作区根,"
|
|
807
|
+
"例如 /root/devloop-workspace)")
|
|
808
|
+
if not _server_path_allowed(server_path, root.rstrip("/") + "/*"):
|
|
809
|
+
raise OpError(f"server_path 不在服务器工作区下({root}): {server_path}")
|
|
810
|
+
|
|
811
|
+
q = shlex.quote(server_path)
|
|
812
|
+
out = s.ssh(f"if [ -e {q} ]; then echo EXISTS; else echo ABSENT; fi", check=False)
|
|
813
|
+
exists = "EXISTS" in out
|
|
814
|
+
if exists and params.get("overwrite") is not True:
|
|
815
|
+
raise OpError(f"服务器已存在同名路径(传 overwrite:true 才覆盖): {server_path}")
|
|
816
|
+
|
|
817
|
+
if src.is_dir():
|
|
818
|
+
files = _iter_tree(src)
|
|
819
|
+
if not files:
|
|
820
|
+
raise OpError(f"目录没有可推送文件(排除构建产物后为空): {src}")
|
|
821
|
+
with tempfile.TemporaryDirectory(prefix="devloop-push-") as td:
|
|
822
|
+
tmp = Path(td)
|
|
823
|
+
tar_path = tmp / "tree.tar.gz"
|
|
824
|
+
manifest = tmp / "MANIFEST.sha256"
|
|
825
|
+
lines = []
|
|
826
|
+
with tarfile.open(tar_path, "w:gz") as tar:
|
|
827
|
+
for f in files:
|
|
828
|
+
rel = f.relative_to(src).as_posix()
|
|
829
|
+
lines.append(f"{_sha256_file(f)} {rel}")
|
|
830
|
+
tar.add(f, arcname=rel)
|
|
831
|
+
manifest.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
|
|
832
|
+
tar.add(manifest, arcname="MANIFEST.sha256")
|
|
833
|
+
size = tar_path.stat().st_size
|
|
834
|
+
if size > cap_mb * 1024 * 1024:
|
|
835
|
+
raise OpError(f"目录包 {size} 字节超过上限 {cap_mb}MiB(提高 max_size_mb)")
|
|
836
|
+
s.ssh(f"mkdir -p {q}")
|
|
837
|
+
remote_tar = f"{server_path.rstrip('/')}/.devloop-push-{uuid.uuid4().hex}.tar.gz"
|
|
838
|
+
s.scp_put(tar_path, remote_tar)
|
|
839
|
+
cmd = ("{ cd " + q + " && tar -xzf " + shlex.quote(remote_tar)
|
|
840
|
+
+ " && sha256sum -c MANIFEST.sha256 >/dev/null && echo PUSH_OK; "
|
|
841
|
+
+ "rm -f " + shlex.quote(remote_tar) + "; } 2>&1")
|
|
842
|
+
res = s.ssh(cmd, timeout=900, check=False)
|
|
843
|
+
if "PUSH_OK" not in res:
|
|
844
|
+
raise OpError(f"目录同步失败(tar 解包或 sha256 校验未过): {res[-400:]}")
|
|
845
|
+
return {"mode": "dir", "server_path": server_path, "files": len(files),
|
|
846
|
+
"size": size, "sha256": _sha256_file(tar_path), "replaced": exists}
|
|
847
|
+
|
|
848
|
+
if not src.is_file():
|
|
849
|
+
raise OpError(f"local 既不是文件也不是目录: {local}")
|
|
850
|
+
size = src.stat().st_size
|
|
851
|
+
if size <= 0:
|
|
852
|
+
raise OpError(f"local 文件为空(拒绝推送零字节): {local}")
|
|
853
|
+
if size > cap_mb * 1024 * 1024:
|
|
854
|
+
raise OpError(f"文件 {size} 字节超过上限 {cap_mb}MiB(分片或提高 max_size_mb)")
|
|
855
|
+
|
|
856
|
+
parent = server_path.rsplit("/", 1)[0]
|
|
857
|
+
s.ssh(f"mkdir -p {shlex.quote(parent)}")
|
|
858
|
+
s.scp_put(src, server_path)
|
|
859
|
+
remote_size = s.ssh(f"stat -c %s {q}").strip()
|
|
860
|
+
if remote_size != str(size):
|
|
861
|
+
raise OpError(f"远端大小不符: local={size} remote={remote_size or '缺失'}")
|
|
862
|
+
local_sha = _sha256_file(src)
|
|
863
|
+
remote_sha = s.ssh(f"sha256sum {q} | cut -d' ' -f1").strip()
|
|
864
|
+
if remote_sha != local_sha:
|
|
865
|
+
raise OpError(f"sha256 不符(传输损坏): local={local_sha} remote={remote_sha or '缺失'}")
|
|
866
|
+
return {"mode": "file", "server_path": server_path, "size": size,
|
|
867
|
+
"sha256": local_sha, "replaced": exists}
|
|
868
|
+
|
|
869
|
+
|
|
870
|
+
# --------------------------------------------------------------------------- rkflash(RK3568 upgrade_tool 刷机)
|
|
871
|
+
|
|
872
|
+
def _rkflash_abs_path(v: str, label: str) -> str:
|
|
873
|
+
"""rkflash 输入必须是 PC 侧绝对路径(config.cfg / upgrade_tool / hdc)。"""
|
|
874
|
+
p = Path(v)
|
|
875
|
+
if not p.is_absolute():
|
|
876
|
+
raise OpError(f"{label} 必须是绝对路径: {v}")
|
|
877
|
+
return str(p)
|
|
878
|
+
|
|
879
|
+
|
|
880
|
+
def _local_default(key: str, label: str) -> str:
|
|
881
|
+
"""inventory local 节的 PC 侧缺省路径(E2E-17:Agent 不需要感知 PC 路径)。
|
|
882
|
+
|
|
883
|
+
未配置/占位符(`<...>`)→ 可操作错误,指出去 config/inventory.yaml 的哪个键。
|
|
884
|
+
"""
|
|
885
|
+
v = str((_inv().get("local") or {}).get(key) or "").strip()
|
|
886
|
+
if not v or v.startswith("<"):
|
|
887
|
+
raise OpError(f"{label} 未配置:在 PC 工作区 config/inventory.yaml 的 local.{key} "
|
|
888
|
+
f"配置绝对路径(或调用时显式传入)")
|
|
889
|
+
return v
|
|
890
|
+
|
|
891
|
+
|
|
892
|
+
def _rkflash_config(params: dict) -> str:
|
|
893
|
+
"""config.cfg:显式 PC 绝对路径,或缺省 images 目录平铺的 config.cfg(flash extract 产物)。"""
|
|
894
|
+
raw = str(params.get("config") or "").strip()
|
|
895
|
+
if raw:
|
|
896
|
+
p = _rkflash_abs_path(raw, "config")
|
|
897
|
+
if not Path(p).is_file():
|
|
898
|
+
raise OpError(f"config.cfg 不存在: {p}")
|
|
899
|
+
return p
|
|
900
|
+
imgs = _local_default("images_dir", "固件解压目录 images_dir")
|
|
901
|
+
p = Path(imgs) / "config.cfg"
|
|
902
|
+
if not p.is_file():
|
|
903
|
+
raise OpError(f"config.cfg 不存在且未配置: {p} —— 先 ohos-devloop flash extract"
|
|
904
|
+
f"(或显式传 config 绝对路径)")
|
|
905
|
+
return str(p)
|
|
906
|
+
|
|
907
|
+
|
|
908
|
+
def _rkflash_tool(params: dict) -> str:
|
|
909
|
+
"""upgrade_tool.exe:显式 PC 绝对路径,或缺省 inventory local.upgrade_tool。"""
|
|
910
|
+
raw = str(params.get("tool") or "").strip()
|
|
911
|
+
if raw:
|
|
912
|
+
p = _rkflash_abs_path(raw, "tool")
|
|
913
|
+
if not Path(p).is_file():
|
|
914
|
+
raise OpError(f"upgrade_tool 不存在: {p}")
|
|
915
|
+
return p
|
|
916
|
+
t = _local_default("upgrade_tool", "upgrade_tool 路径")
|
|
917
|
+
p = Path(t)
|
|
918
|
+
if not p.is_file():
|
|
919
|
+
raise OpError(f"upgrade_tool 不存在: {p}"
|
|
920
|
+
f"(检查 config/inventory.yaml 的 local.upgrade_tool 是否指向有效文件)")
|
|
921
|
+
return str(p)
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def _hdc_param_get(key: str, tries: int = 3) -> str | None:
|
|
925
|
+
"""经 PC 本地 hdc 读板参数(best-effort:刷机后设备可能仍在重启,失败返回 None 不报错)。"""
|
|
926
|
+
hdc = str((_inv().get("local") or {}).get("hdc") or "").strip()
|
|
927
|
+
if not hdc or hdc.startswith("<"):
|
|
928
|
+
return None
|
|
929
|
+
for _ in range(tries):
|
|
930
|
+
try:
|
|
931
|
+
p = subprocess.run([hdc, "shell", "param", "get", key],
|
|
932
|
+
capture_output=True, text=True, timeout=20)
|
|
933
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
934
|
+
return None
|
|
935
|
+
v = (p.stdout or "").strip()
|
|
936
|
+
if p.returncode == 0 and v:
|
|
937
|
+
return v
|
|
938
|
+
time.sleep(3)
|
|
939
|
+
return None
|
|
940
|
+
|
|
941
|
+
|
|
942
|
+
def _h_rkflash_plan(params: dict, svc: dict | None = None) -> dict:
|
|
943
|
+
config = _rkflash_config(params)
|
|
944
|
+
args = ["plan", config]
|
|
945
|
+
if params.get("by"):
|
|
946
|
+
args += ["--by", str(params["by"])]
|
|
947
|
+
if params.get("only"):
|
|
948
|
+
args += ["--only", str(params["only"])]
|
|
949
|
+
rc, out, err = _run_script_soft("rkflash.py", args, timeout=120)
|
|
950
|
+
return {"rc": rc, "output": (out + err).strip()}
|
|
951
|
+
|
|
952
|
+
|
|
953
|
+
def _h_rkflash_run(params: dict, svc: dict | None = None) -> dict:
|
|
954
|
+
config = _rkflash_config(params)
|
|
955
|
+
tool = _rkflash_tool(params)
|
|
956
|
+
args = ["run", config, "--tool", tool]
|
|
957
|
+
if params.get("by"):
|
|
958
|
+
args += ["--by", str(params["by"])]
|
|
959
|
+
if params.get("only"):
|
|
960
|
+
args += ["--only", str(params["only"])]
|
|
961
|
+
if params.get("location"):
|
|
962
|
+
args += ["--location", str(params["location"])]
|
|
963
|
+
if params.get("no_reset"):
|
|
964
|
+
args += ["--no-reset"]
|
|
965
|
+
if params.get("confirmed") is not True:
|
|
966
|
+
# 与 CLI 缺省一致:不带 --yes 只打印计划、不碰设备(fail-closed 默认)。
|
|
967
|
+
# 证据目录与结果判定都发生在 rkflash.py 内部(runs/rkflash-<时间戳>/)。
|
|
968
|
+
args_no_yes = list(args)
|
|
969
|
+
rc, out, err = _run_script_soft("rkflash.py", args_no_yes, timeout=120)
|
|
970
|
+
return {"rc": rc, "dry_run": True, "output": (out + err).strip()}
|
|
971
|
+
rc, out, err = _run_script_soft("rkflash.py", args + ["--yes"], timeout=1800)
|
|
972
|
+
result = {"rc": rc, "dry_run": False, "output_tail": (out + err).strip()[-2000:]}
|
|
973
|
+
if rc == 0:
|
|
974
|
+
# E2E-19:刷机成功收尾对账——回读板基线,供调用方(服务器侧)更新 inventory 期望基线。
|
|
975
|
+
result["new_baseline"] = _hdc_param_get("const.product.software.version")
|
|
976
|
+
return result
|
|
977
|
+
|
|
978
|
+
|
|
979
|
+
def _h_rkflash_verify(params: dict, svc: dict | None = None) -> dict:
|
|
980
|
+
config = _rkflash_config(params)
|
|
981
|
+
args = ["verify", config]
|
|
982
|
+
if params.get("hdc"):
|
|
983
|
+
args += ["--hdc", _rkflash_abs_path(str(params["hdc"]), "hdc")]
|
|
984
|
+
else:
|
|
985
|
+
hdc = str((_inv().get("local") or {}).get("hdc") or "").strip()
|
|
986
|
+
if hdc and not hdc.startswith("<"):
|
|
987
|
+
args += ["--hdc", hdc]
|
|
988
|
+
if params.get("only"):
|
|
989
|
+
args += ["--only", str(params["only"])]
|
|
990
|
+
rc, out, err = _run_script_soft("rkflash.py", args, timeout=900)
|
|
991
|
+
return {"rc": rc, "output": (out + err).strip()}
|
|
992
|
+
|
|
993
|
+
|
|
994
|
+
# --------------------------------------------------------------------------- 自建镜像(服务器 → PC)
|
|
995
|
+
|
|
996
|
+
IMAGE_FILE_RE = re.compile(r"^(?:[A-Za-z0-9][A-Za-z0-9._-]*\.(?:img|bin)|config\.cfg|parameter\.txt|manifest_tag\.xml)$")
|
|
997
|
+
|
|
998
|
+
|
|
999
|
+
def _h_flash_pull_images(params: dict, svc: dict | None = None) -> dict:
|
|
1000
|
+
"""把服务器自建镜像目录拉回 PC:白名单 + 大小/总量上限 + sha256 双值 + config.cfg 路径重写。
|
|
1001
|
+
|
|
1002
|
+
镜像包里的 config.cfg 钉着构建机绝对路径(实测 CI 包与服务器包都是 D:\\rk3568\\images),
|
|
1003
|
+
落地后按 dest 重写,rkflash plan/run/verify 即可直接消费新目录。
|
|
1004
|
+
"""
|
|
1005
|
+
server_path = str(params["server_path"]).rstrip("/")
|
|
1006
|
+
dest_raw = str(params["dest"]).strip()
|
|
1007
|
+
dest = Path(dest_raw)
|
|
1008
|
+
if not dest.is_absolute():
|
|
1009
|
+
raise OpError(f"dest 必须是 PC 侧绝对路径: {dest_raw}")
|
|
1010
|
+
s = _server(str(params.get("server", "")))
|
|
1011
|
+
if not _server_path_allowed_any(server_path, s):
|
|
1012
|
+
raise OpError(f"server_path 不在服务器大仓或工作区前缀下: {server_path}")
|
|
1013
|
+
|
|
1014
|
+
files = params.get("files") or []
|
|
1015
|
+
if not isinstance(files, list) or not all(isinstance(f, str) for f in files):
|
|
1016
|
+
raise OpError("files 必须是字符串数组(空数组 = 目录内白名单文件全拉)")
|
|
1017
|
+
names = [f for f in files if f]
|
|
1018
|
+
for name in names:
|
|
1019
|
+
if Path(name).name != name or not IMAGE_FILE_RE.match(name):
|
|
1020
|
+
raise OpError(f"文件名不在白名单(*.img|*.bin|config.cfg|parameter.txt|manifest_tag.xml): {name!r}")
|
|
1021
|
+
if not names:
|
|
1022
|
+
out = s.ssh(f"ls -1 {shlex.quote(server_path)} 2>/dev/null", timeout=60, check=False)
|
|
1023
|
+
names = [line.strip() for line in out.splitlines()
|
|
1024
|
+
if IMAGE_FILE_RE.match(line.strip())]
|
|
1025
|
+
if not names:
|
|
1026
|
+
raise OpError(f"服务器镜像目录为空或不可读: {server_path}")
|
|
1027
|
+
if len(names) > int(params.get("max_files", 32)):
|
|
1028
|
+
raise OpError(f"文件数超过上限 {params.get('max_files', 32)}: {len(names)}")
|
|
1029
|
+
names = sorted(set(names))
|
|
1030
|
+
|
|
1031
|
+
quoted = " ".join(shlex.quote(n) for n in names)
|
|
1032
|
+
listing = s.ssh(f"cd {shlex.quote(server_path)} && for f in {quoted}; do "
|
|
1033
|
+
f"[ -f \"$f\" ] && echo \"$f $(stat -c %s \"$f\")\"; done",
|
|
1034
|
+
timeout=120, check=False)
|
|
1035
|
+
sizes: dict[str, int] = {}
|
|
1036
|
+
for line in listing.splitlines():
|
|
1037
|
+
parts = line.split()
|
|
1038
|
+
if len(parts) == 2 and parts[0] in names and parts[1].isdigit():
|
|
1039
|
+
sizes[parts[0]] = int(parts[1])
|
|
1040
|
+
missing = [n for n in names if n not in sizes]
|
|
1041
|
+
if missing:
|
|
1042
|
+
raise OpError(f"服务器镜像缺失: {', '.join(missing)}({server_path})")
|
|
1043
|
+
total = sum(sizes.values())
|
|
1044
|
+
cap = int(params.get("max_size_mb", 8192)) * 1024 * 1024
|
|
1045
|
+
if total > cap:
|
|
1046
|
+
raise OpError(f"镜像总量 {total / 1024**3:.1f}GB 超过上限 {params.get('max_size_mb', 8192)}MB"
|
|
1047
|
+
"(确认不是误传整个目录)")
|
|
1048
|
+
|
|
1049
|
+
dest.mkdir(parents=True, exist_ok=True)
|
|
1050
|
+
entries: list[dict] = []
|
|
1051
|
+
for name in names:
|
|
1052
|
+
local = dest / name
|
|
1053
|
+
s.scp_get(f"{server_path}/{name}", local)
|
|
1054
|
+
if not local.is_file() or local.stat().st_size != sizes[name]:
|
|
1055
|
+
got = local.stat().st_size if local.is_file() else "缺失"
|
|
1056
|
+
raise OpError(f"拉取大小不符: {name} server={sizes[name]} local={got}")
|
|
1057
|
+
remote_sha = s.ssh(f"sha256sum {shlex.quote(server_path + '/' + name)} | cut -d' ' -f1",
|
|
1058
|
+
timeout=600).strip()
|
|
1059
|
+
local_sha = _sha256_file(local)
|
|
1060
|
+
if remote_sha != local_sha:
|
|
1061
|
+
raise OpError(f"sha256 不符(传输损坏): {name} remote={remote_sha} local={local_sha}")
|
|
1062
|
+
entries.append({"name": name, "size": sizes[name], "sha256": local_sha})
|
|
1063
|
+
|
|
1064
|
+
import rkflash # 同目录模块:只为按 dest 重写 config.cfg 路径
|
|
1065
|
+
cfg = dest / "config.cfg"
|
|
1066
|
+
rewritten = 0
|
|
1067
|
+
if cfg.is_file():
|
|
1068
|
+
rewritten = rkflash.rewrite_config_paths(cfg, cfg, dest)
|
|
1069
|
+
for entry in entries:
|
|
1070
|
+
if entry["name"] == "config.cfg":
|
|
1071
|
+
entry["sha256"] = _sha256_file(cfg)
|
|
1072
|
+
entry["rewritten"] = True
|
|
1073
|
+
|
|
1074
|
+
(dest / "manifest.json").write_text(json.dumps(
|
|
1075
|
+
{"schema": 1, "source": server_path, "dest": str(dest), "bytes": total,
|
|
1076
|
+
"files": entries, "recorded_at": datetime.now().astimezone().isoformat(timespec="seconds")},
|
|
1077
|
+
ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
1078
|
+
return {"dest": str(dest), "count": len(entries), "bytes": total,
|
|
1079
|
+
"rewritten": rewritten, "files": entries}
|
|
1080
|
+
def _h_job_wait(params: dict, svc: dict | None = None) -> dict:
|
|
1081
|
+
"""长轮询等待异步 job 终态(E2E-18 兜底:不支持服务端通知的 runtime 用)。
|
|
1082
|
+
|
|
1083
|
+
只做有界轮询(timeout_s ≤ 60,2s 间隔),终态即回;超时回 running + timeout 标记,
|
|
1084
|
+
由调用方决定再等或去干别的;job 被驱逐/服务重启后回 unknown(apply.run 可经
|
|
1085
|
+
apply.results 续读落盘档案)。
|
|
1086
|
+
"""
|
|
1087
|
+
job_id = str(params.get("job_id") or "")
|
|
1088
|
+
if not job_id:
|
|
1089
|
+
raise OpError("job_id 必填")
|
|
1090
|
+
try:
|
|
1091
|
+
timeout_s = int(params.get("timeout_s") or 30)
|
|
1092
|
+
except (TypeError, ValueError):
|
|
1093
|
+
raise OpError("timeout_s 必须是整数")
|
|
1094
|
+
if not 1 <= timeout_s <= 60:
|
|
1095
|
+
raise OpError("timeout_s 须在 1..60 之间")
|
|
1096
|
+
jobs = (svc or {}).get("jobs")
|
|
1097
|
+
if jobs is None:
|
|
1098
|
+
raise OpError("job 表不可用(服务内部错误)")
|
|
1099
|
+
deadline = time.time() + timeout_s
|
|
1100
|
+
while time.time() < deadline:
|
|
1101
|
+
j = jobs.get(job_id)
|
|
1102
|
+
if j is None:
|
|
1103
|
+
return {"job_id": job_id, "state": "unknown",
|
|
1104
|
+
"error": "job 不存在(可能已超 32 条被驱逐或服务重启;"
|
|
1105
|
+
"apply.run 可经 apply.results 续读落盘档案)"}
|
|
1106
|
+
if j.state != "running":
|
|
1107
|
+
return {"job_id": job_id, "op": j.op, "state": j.state, "rc": j.rc,
|
|
1108
|
+
"started": j.started, "ended": j.ended, "error": j.error}
|
|
1109
|
+
time.sleep(2)
|
|
1110
|
+
j = jobs.get(job_id)
|
|
1111
|
+
return {"job_id": job_id, "op": j.op if j else None,
|
|
1112
|
+
"state": j.state if j else "unknown", "timeout": True}
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
# --------------------------------------------------------------------------- 注册表
|
|
1116
|
+
|
|
1117
|
+
OPS: dict[str, Op] = {}
|
|
1118
|
+
|
|
1119
|
+
|
|
1120
|
+
def _register(op: Op) -> None:
|
|
1121
|
+
if op.name in OPS:
|
|
1122
|
+
raise ValueError(f"op 重复注册: {op.name!r}")
|
|
1123
|
+
OPS[op.name] = op
|
|
1124
|
+
|
|
1125
|
+
|
|
1126
|
+
_register(Op(
|
|
1127
|
+
"pc.info", "PC 服务信息",
|
|
1128
|
+
"服务版本/工作区/inventory 条目与就绪状态(token 只回是否配置,绝不回值)",
|
|
1129
|
+
{}, (), _h_pc_info))
|
|
1130
|
+
_register(Op(
|
|
1131
|
+
"board.list", "设备列表",
|
|
1132
|
+
"hdc list targets(设备在线清单)",
|
|
1133
|
+
{"board": {"type": "string", "description": "inventory boards 条目名(缺省首条)"}},
|
|
1134
|
+
(), _h_board_list))
|
|
1135
|
+
_register(Op(
|
|
1136
|
+
"board.shell", "设备 shell",
|
|
1137
|
+
"在开发板上执行 hdc shell 命令(设备侧 shell,不是 PC 本地 shell)",
|
|
1138
|
+
{"command": {"type": "string", "minLength": 1, "maxLength": 8192},
|
|
1139
|
+
"timeout_s": {"type": "integer", "minimum": 1, "maximum": 300, "default": 30},
|
|
1140
|
+
"board": {"type": "string", "description": "inventory boards 条目名(缺省首条)"}},
|
|
1141
|
+
("command",), _h_board_shell))
|
|
1142
|
+
_register(Op(
|
|
1143
|
+
"board.param", "设备参数",
|
|
1144
|
+
"读取开发板 param get <key>(如 const.product.software.version)",
|
|
1145
|
+
{"key": {"type": "string", "pattern": "^[A-Za-z0-9._-]{1,128}$"},
|
|
1146
|
+
"board": {"type": "string"}},
|
|
1147
|
+
("key",), _h_board_param))
|
|
1148
|
+
_register(Op(
|
|
1149
|
+
"flash.list", "已解压固件",
|
|
1150
|
+
"列出当前已解压固件来源与分区文件(非抛错:rc 原样回传供诊断)",
|
|
1151
|
+
{}, (), _h_flash_list))
|
|
1152
|
+
_register(Op(
|
|
1153
|
+
"flash.ls", "镜像目录清单",
|
|
1154
|
+
"只读列出 images 目录(白名单根 = inventory local.images_dir)的条目名/类型/大小,"
|
|
1155
|
+
"可选一层子目录;供确认 manifest_tag.xml 等文件是否存在/在子目录(E2E-20)",
|
|
1156
|
+
{"path": {"type": "string", "description": "images 目录内的相对子路径(缺省根目录)"}},
|
|
1157
|
+
(), _h_flash_ls))
|
|
1158
|
+
_register(Op(
|
|
1159
|
+
"board.preflight", "设备预检",
|
|
1160
|
+
"设备在线 + 基线版本 + 校时 + 熄屏 24h + 存量 faultlog 盘点(e2e 前置);"
|
|
1161
|
+
"expect_version 覆盖 inventory(自建镜像刷板后的动态基线;缺省回退 PC inventory 并标注来源,E2E-19)",
|
|
1162
|
+
{"board": {"type": "string"},
|
|
1163
|
+
"expect_version": {"type": "string", "maxLength": 64,
|
|
1164
|
+
"description": "期望 software.version 包含的串(服务器侧动态基线;缺省取 inventory)"}},
|
|
1165
|
+
(), _h_board_preflight))
|
|
1166
|
+
_register(Op(
|
|
1167
|
+
"board.push", "推板(保护链)",
|
|
1168
|
+
"服务器产物推板:基线预检 → scp 拉取 → 板端备份 → remount → send → md5 双值比对 → chmod/sync;"
|
|
1169
|
+
"基线期望优先取 expect_version(动态基线),缺省回退 PC inventory 并标注来源(E2E-19)",
|
|
1170
|
+
{"server_path": {"type": "string"}, "device_path": {"type": "string"},
|
|
1171
|
+
"board": {"type": "string"}, "server": {"type": "string"},
|
|
1172
|
+
"expect_version": {"type": "string", "maxLength": 64,
|
|
1173
|
+
"description": "期望 software.version 包含的串(服务器侧动态基线;缺省取 inventory)"}},
|
|
1174
|
+
("server_path", "device_path"), _h_board_push))
|
|
1175
|
+
_register(Op(
|
|
1176
|
+
"board.install", "安装 hap",
|
|
1177
|
+
"校时 → bm uninstall → hdc install → bm dump 含 applicationinfo 才算成功",
|
|
1178
|
+
{"server_path": {"type": "string"}, "bundle": {"type": "string"},
|
|
1179
|
+
"board": {"type": "string"}},
|
|
1180
|
+
("server_path", "bundle"), _h_board_install))
|
|
1181
|
+
_register(Op(
|
|
1182
|
+
"board.screenshot", "设备截图",
|
|
1183
|
+
"snapshot_display 截图 → recv → rm;回 path/sha256/size/base64(>4MiB 省略 base64)",
|
|
1184
|
+
{"board": {"type": "string"}}, (), _h_board_screenshot))
|
|
1185
|
+
_register(Op(
|
|
1186
|
+
"board.hilog", "设备日志",
|
|
1187
|
+
"hilog -x 尾部(截断保留尾部 2MiB,回 truncated 标记)",
|
|
1188
|
+
{"lines": {"type": "integer", "minimum": 1, "maximum": 100000, "default": 200},
|
|
1189
|
+
"board": {"type": "string"}},
|
|
1190
|
+
(), _h_board_hilog))
|
|
1191
|
+
_register(Op(
|
|
1192
|
+
"flash.fetch", "下载镜像(异步)",
|
|
1193
|
+
"从 CI 每日构建下载最新镜像包(device 默认 dayu200;近7天取最新成功构建)",
|
|
1194
|
+
{"device": {"type": "string", "default": "dayu200"}},
|
|
1195
|
+
(), _h_flash_fetch, async_job=True))
|
|
1196
|
+
_register(Op(
|
|
1197
|
+
"flash.extract", "解包镜像(异步)",
|
|
1198
|
+
"固件包平铺解压到 images 目录(缺省自动选 download/ 下最新;archive 须 .tar.gz/.tgz 绝对路径)",
|
|
1199
|
+
{"archive": {"type": "string"}},
|
|
1200
|
+
(), _h_flash_extract, async_job=True))
|
|
1201
|
+
_register(Op(
|
|
1202
|
+
"flash.sync_repo", "大仓对齐(异步)",
|
|
1203
|
+
"在服务器对齐大仓到镜像基线(0.4 服务器执行;root 短名交 CLI 解析,task_id 走 TID 白名单)",
|
|
1204
|
+
{"root": {"type": "string"}, "task_id": {"type": "string"}},
|
|
1205
|
+
(), _h_flash_sync_repo, async_job=True))
|
|
1206
|
+
_register(Op(
|
|
1207
|
+
"pool.status", "工作区池状态",
|
|
1208
|
+
"在服务器扫描工作区并与 workspace_pool.yaml 对账(0.4 池权威在服务器)",
|
|
1209
|
+
{}, (), _h_pool_status))
|
|
1210
|
+
_register(Op(
|
|
1211
|
+
"pool.claim", "领取工作区",
|
|
1212
|
+
"在服务器登记任务↔工作区映射(workspace_pool.yaml,权威在服务器)",
|
|
1213
|
+
{"workspace": {"type": "string"}, "task_id": {"type": "string"}},
|
|
1214
|
+
("workspace", "task_id"), _h_pool_claim))
|
|
1215
|
+
_register(Op(
|
|
1216
|
+
"pool.release", "释放工作区",
|
|
1217
|
+
"在服务器解除工作区占用登记(验证完结后手工释放)",
|
|
1218
|
+
{"workspace": {"type": "string"}},
|
|
1219
|
+
("workspace",), _h_pool_release))
|
|
1220
|
+
_register(Op(
|
|
1221
|
+
"ui.dump", "UI 树取证",
|
|
1222
|
+
"dumpLayout 采集 + 标准化(黑名单裁剪)→ 回标准化 JSON 与落盘路径",
|
|
1223
|
+
{"board": {"type": "string"}, "settle_s": {"type": "number", "default": 0.5}},
|
|
1224
|
+
(), _h_ui_dump))
|
|
1225
|
+
_register(Op(
|
|
1226
|
+
"ui.click", "UI 点击",
|
|
1227
|
+
"选择器定位 → uinput 点击 → 按需 dump 回 after_layout(证据落盘)",
|
|
1228
|
+
{"selector": {"type": "object"}, "board": {"type": "string"},
|
|
1229
|
+
"settle_s": {"type": "number", "default": 1.5}, "dump_after": {"type": "boolean", "default": True}},
|
|
1230
|
+
("selector",), _h_ui_click))
|
|
1231
|
+
_register(Op(
|
|
1232
|
+
"sign.hap", "测试应用签名",
|
|
1233
|
+
"离线 debug/release 签名(project 须含 AppScope/app.json5;debug 需板在线取 UDID)",
|
|
1234
|
+
{"project": {"type": "string"}, "mode": {"type": "string", "default": "debug"}},
|
|
1235
|
+
("project",), _h_sign_hap))
|
|
1236
|
+
_register(Op(
|
|
1237
|
+
"apply.plan", "job spec 离线预演",
|
|
1238
|
+
"服务器执行 apply plan:解析 spec 输出执行计划(不连任何机器)",
|
|
1239
|
+
{"spec": {"type": "string"}, "params": {"type": "object"}},
|
|
1240
|
+
("spec",), _h_apply_plan))
|
|
1241
|
+
_register(Op(
|
|
1242
|
+
"apply.run", "job spec 执行(异步)",
|
|
1243
|
+
"服务器执行 apply run 全流程(异步 job;落服务器 runs/<run_id>/results.json,可跨重启续读)",
|
|
1244
|
+
{"spec": {"type": "string"}, "params": {"type": "object"},
|
|
1245
|
+
"only": {"type": "string"}, "from_step": {"type": "string"},
|
|
1246
|
+
"keep_going": {"type": "boolean"}},
|
|
1247
|
+
("spec",), _h_apply_run, async_job=True))
|
|
1248
|
+
_register(Op(
|
|
1249
|
+
"apply.results", "读取 run 结果",
|
|
1250
|
+
"读服务器工作区 runs/{run_id}/results.json(run 档案续读)",
|
|
1251
|
+
{"run_id": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$"}},
|
|
1252
|
+
("run_id",), _h_apply_results))
|
|
1253
|
+
_register(Op(
|
|
1254
|
+
"file.push", "文件上传到服务器",
|
|
1255
|
+
"PC 本地文件或目录(绝对路径)经 ssh 推到服务器工作区:目录打 tar + 逐文件 sha256 回验;回 size/sha256 双值",
|
|
1256
|
+
{"local": {"type": "string", "description": "PC 侧绝对路径(文件)"},
|
|
1257
|
+
"server_path": {"type": "string", "description": "服务器绝对路径,须在 workspace_root 下"},
|
|
1258
|
+
"server": {"type": "string", "description": "inventory servers 条目名(缺省首条)"},
|
|
1259
|
+
"overwrite": {"type": "boolean", "default": False,
|
|
1260
|
+
"description": "目标已存在时是否覆盖(缺省拒绝)"},
|
|
1261
|
+
"max_size_mb": {"type": "integer", "minimum": 1, "maximum": 4096, "default": 512}},
|
|
1262
|
+
("local", "server_path"), _h_file_push))
|
|
1263
|
+
_register(Op(
|
|
1264
|
+
"device.lock", "锁定设备",
|
|
1265
|
+
"登记设备↔任务占用(一设备一任务):同 task 幂等,异 task 拒绝并指明占用方;"
|
|
1266
|
+
"不查 hdc 在线(锁的是身份不是在场,失联设备也可登记)",
|
|
1267
|
+
{"device_serial": {"type": "string", "pattern": "^[A-Za-z0-9._-]{1,64}$"},
|
|
1268
|
+
"task_id": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$"},
|
|
1269
|
+
"workspace": {"type": "string", "minLength": 1}},
|
|
1270
|
+
("device_serial", "task_id", "workspace"), _h_device_lock))
|
|
1271
|
+
_register(Op(
|
|
1272
|
+
"device.unlock", "释放设备",
|
|
1273
|
+
"解除设备占用:正常释放与「本就空闲」幂等;异常遗留(task 不符/holder 不存活/设备失联)"
|
|
1274
|
+
"不带 confirm_abandoned 拒绝且登记不变,带上才解除并留审计行",
|
|
1275
|
+
{"device_serial": {"type": "string", "pattern": "^[A-Za-z0-9._-]{1,64}$"},
|
|
1276
|
+
"task_id": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$"},
|
|
1277
|
+
"confirm_abandoned": {"type": "boolean", "default": False}},
|
|
1278
|
+
("device_serial", "task_id"), _h_device_unlock))
|
|
1279
|
+
_register(Op(
|
|
1280
|
+
"device.locks", "设备占用查询",
|
|
1281
|
+
"列出每台已连接设备的占用状态(空闲/占用者/失联)并与 workspace_pool.yaml 对账"
|
|
1282
|
+
"(不一致以 WARN 呈现,不自动改写);hdc 不可用时登记设备按失联保守处理",
|
|
1283
|
+
{}, (), _h_device_locks))
|
|
1284
|
+
_register(Op(
|
|
1285
|
+
"flash.rkflash_plan", "刷机命令序列(离线)",
|
|
1286
|
+
"rkflash plan:读 config.cfg/parameter.txt 生成 upgrade_tool 命令序列(不碰设备);"
|
|
1287
|
+
"config 缺省取 inventory local.images_dir 平铺 config.cfg(E2E-17:无需传 PC 路径)",
|
|
1288
|
+
{"config": {"type": "string", "description": "config.cfg 的 PC 侧绝对路径(缺省 images_dir 平铺 config.cfg)"},
|
|
1289
|
+
"by": {"type": "string", "enum": ["lba", "name"], "description": "分区写入方式(缺省 lba)"},
|
|
1290
|
+
"only": {"type": "string", "description": "只处理这些显示名(逗号分隔,大小写不敏感)"}},
|
|
1291
|
+
(), _h_rkflash_plan))
|
|
1292
|
+
_register(Op(
|
|
1293
|
+
"flash.rkflash_run", "执行刷机(异步)",
|
|
1294
|
+
"rkflash run:逐条驱动 upgrade_tool 烧写(Loader/Maskrom 判定 + fail-closed 证据);"
|
|
1295
|
+
"confirmed=true 才真执行,否则只打印计划不碰设备;证据落 runs/rkflash-<时间戳>/;"
|
|
1296
|
+
"config/tool 缺省取 inventory local(images_dir/upgrade_tool,E2E-17),"
|
|
1297
|
+
"成功后回读 new_baseline 供基线对账(E2E-19)",
|
|
1298
|
+
{"config": {"type": "string", "description": "config.cfg 的 PC 侧绝对路径(缺省 images_dir 平铺 config.cfg)"},
|
|
1299
|
+
"tool": {"type": "string", "description": "upgrade_tool.exe 的 PC 侧绝对路径(缺省 local.upgrade_tool)"},
|
|
1300
|
+
"confirmed": {"type": "boolean", "description": "true 才执行刷写(对应 CLI --yes)"},
|
|
1301
|
+
"by": {"type": "string", "enum": ["lba", "name"]},
|
|
1302
|
+
"only": {"type": "string"},
|
|
1303
|
+
"location": {"type": "string", "description": "多设备时按 ld 输出的 LocationID 指定"},
|
|
1304
|
+
"no_reset": {"type": "boolean", "description": "烧完不重启设备"}},
|
|
1305
|
+
("confirmed",), _h_rkflash_run, async_job=True))
|
|
1306
|
+
_register(Op(
|
|
1307
|
+
"flash.rkflash_verify", "板侧 md5 核对",
|
|
1308
|
+
"rkflash verify:hdc 读板侧分区 md5 与本地镜像对账(userdata 不比对;结果写 verify.json);"
|
|
1309
|
+
"config/hdc 缺省取 inventory local(E2E-17)",
|
|
1310
|
+
{"config": {"type": "string", "description": "config.cfg 的 PC 侧绝对路径(缺省 images_dir 平铺 config.cfg)"},
|
|
1311
|
+
"hdc": {"type": "string", "description": "hdc 可执行文件(缺省 local.hdc,再缺省 PATH)"},
|
|
1312
|
+
"only": {"type": "string"}},
|
|
1313
|
+
(), _h_rkflash_verify))
|
|
1314
|
+
_register(Op(
|
|
1315
|
+
"flash.pull_images", "拉取自建镜像(异步)",
|
|
1316
|
+
"服务器自建镜像目录 → PC 落地目录:文件名白名单、总量上限、逐文件 sha256 双值、"
|
|
1317
|
+
"config.cfg 路径按落地目录重写、manifest.json 留档",
|
|
1318
|
+
{"server_path": {"type": "string", "description": "服务器镜像目录(如 <大仓>/out/rk3568/packages/phone/images)"},
|
|
1319
|
+
"dest": {"type": "string", "description": "PC 侧绝对目录(不存在则创建)"},
|
|
1320
|
+
"files": {"type": "array", "items": {"type": "string"},
|
|
1321
|
+
"maxItems": 32, "description": "只拉这些文件名(缺省:目录内白名单文件全拉)"},
|
|
1322
|
+
"server": {"type": "string", "description": "inventory servers 条目名(缺省首条)"},
|
|
1323
|
+
"max_size_mb": {"type": "integer", "minimum": 1, "maximum": 16384, "default": 8192},
|
|
1324
|
+
"max_files": {"type": "integer", "minimum": 1, "maximum": 64, "default": 32}},
|
|
1325
|
+
("server_path", "dest"), _h_flash_pull_images, async_job=True))
|
|
1326
|
+
_register(Op(
|
|
1327
|
+
"job.wait", "等待异步任务终态",
|
|
1328
|
+
"长轮询等待 job 到终态(timeout_s ≤ 60,2s 间隔):终态即回 state/rc;超时回 running+timeout,"
|
|
1329
|
+
"由调用方决定再等或并行做别的。替代 Agent sleep 轮询(E2E-18);job 被驱逐/服务重启回 unknown",
|
|
1330
|
+
{"job_id": {"type": "string", "description": "job_status 返回的 job id"},
|
|
1331
|
+
"timeout_s": {"type": "integer", "minimum": 1, "maximum": 60,
|
|
1332
|
+
"description": "最长等待秒数(缺省 30)"}},
|
|
1333
|
+
("job_id",), _h_job_wait))
|
|
1334
|
+
|
|
1335
|
+
|
|
1336
|
+
def ops_meta() -> list[dict]:
|
|
1337
|
+
"""HTTP GET /v1/ops 的清单形态(name/title/description/input_schema)。"""
|
|
1338
|
+
return [{"name": o.name, "title": o.title, "description": o.description,
|
|
1339
|
+
"input_schema": {"type": "object", "properties": o.params,
|
|
1340
|
+
"required": list(o.required),
|
|
1341
|
+
"additionalProperties": False}}
|
|
1342
|
+
for o in OPS.values()]
|
|
1343
|
+
|
|
1344
|
+
|
|
1345
|
+
def tool_manifest() -> dict:
|
|
1346
|
+
"""stdio MCP 适配器消费的 manifest:每个 op 一条 POST 工具 + job_status/job_log 两条固定 GET。
|
|
1347
|
+
|
|
1348
|
+
顶层 version 是 manifest schema 号(保持 1,tests/test_pc_service 断言它);
|
|
1349
|
+
http_api_version / mcp_tools_version 是契约版本(HTTP_API_VERSION / MCP_TOOLS_VERSION),
|
|
1350
|
+
pc_mcp 启动握手按它们判定兼容。生成期 fail-fast:tool 名必须合法且唯一(冲突即抛,
|
|
1351
|
+
防注册表漂移)。"""
|
|
1352
|
+
tools: list[dict] = []
|
|
1353
|
+
seen: set[str] = set()
|
|
1354
|
+
for o in OPS.values():
|
|
1355
|
+
tname = o.name.replace(".", "_")
|
|
1356
|
+
if not TOOL_NAME_RE.match(tname):
|
|
1357
|
+
raise ValueError(f"tool 名非法: {tname!r}(op {o.name})")
|
|
1358
|
+
if tname in seen:
|
|
1359
|
+
raise ValueError(f"tool 名冲突: {tname!r}")
|
|
1360
|
+
seen.add(tname)
|
|
1361
|
+
tools.append({
|
|
1362
|
+
"name": tname,
|
|
1363
|
+
"description": o.description,
|
|
1364
|
+
"inputSchema": {"type": "object", "properties": o.params,
|
|
1365
|
+
"required": list(o.required),
|
|
1366
|
+
"additionalProperties": False},
|
|
1367
|
+
"http": {"method": "POST", "path": f"/v1/ops/{o.name}"},
|
|
1368
|
+
})
|
|
1369
|
+
for tname, path, desc in (
|
|
1370
|
+
("job_status", "/v1/jobs/{job_id}", "异步任务状态(state/rc/result/error)"),
|
|
1371
|
+
("job_log", "/v1/jobs/{job_id}/log", "异步任务输出尾部(stdout/stderr tail)")):
|
|
1372
|
+
tools.append({
|
|
1373
|
+
"name": tname,
|
|
1374
|
+
"description": desc,
|
|
1375
|
+
"inputSchema": {"type": "object",
|
|
1376
|
+
"properties": {"job_id": {"type": "string"}},
|
|
1377
|
+
"required": ["job_id"],
|
|
1378
|
+
"additionalProperties": False},
|
|
1379
|
+
"http": {"method": "GET", "path": path},
|
|
1380
|
+
})
|
|
1381
|
+
return {"version": 1, "http_api_version": HTTP_API_VERSION,
|
|
1382
|
+
"mcp_tools_version": MCP_TOOLS_VERSION, "tools": tools}
|
|
1383
|
+
|
|
1384
|
+
|
|
1385
|
+
def manifest_json() -> str:
|
|
1386
|
+
"""manifest 的确定性序列化(pc_service ops --json 与 server_agent tools.json 共用同一形态)。"""
|
|
1387
|
+
return json.dumps(tool_manifest(), ensure_ascii=False, indent=2) + "\n"
|