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,332 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""设备占用登记(Phase 13 LOCK-01/02/03)——PC 侧「设备↔任务」占用状态的唯一写者。
|
|
4
|
+
|
|
5
|
+
为什么存在:设备与镜像在 Windows PC,主 Agent 在编译服务器;同一台设备被两个任务同时
|
|
6
|
+
操作会互相踩坏。本模块把占用登记收敛成一个 JSON 单文件,随 pc 服务启动加载、跨服务重启
|
|
7
|
+
保留、异常遗留必须用户核对(confirm_abandoned)才能解除。
|
|
8
|
+
|
|
9
|
+
存储:`~/.ohos-devloop/pc_service/device-locks.json`(PC 本地状态,不上库、不含凭据):
|
|
10
|
+
{"schema": 1, "locks": {<serial>: {device_serial, task_id, workspace, holder_pid,
|
|
11
|
+
locked_at}}, "audit": [{at, action, device_serial, task_id, unlocked_by, reason}]}
|
|
12
|
+
|
|
13
|
+
写纪律(threat_model T-13-03):
|
|
14
|
+
- 原子写:同目录 `.device-locks.json.tmp-<uuid>` → os.replace → 立即回读逐键比对;
|
|
15
|
+
任一步失败抛 LockError(绝不静默)。
|
|
16
|
+
- 进程内并发由 threading.Lock 串行化。
|
|
17
|
+
- 单写者假设:同一时刻只跑一个 pc 服务进程;重启前先停旧进程(旧进程的 holder_pid
|
|
18
|
+
在重启后自然不存活,于是解锁会走 confirm_abandoned 门——这正是设计意图)。
|
|
19
|
+
|
|
20
|
+
失败关闭(T-13-01):登记文件损坏/结构不符 → load() 抛 LockError(含路径与修复指引),
|
|
21
|
+
服务拒绝启动;绝不静默清空登记。
|
|
22
|
+
|
|
23
|
+
本模块只依赖 stdlib,禁止 import pc_ops/pc_service(pc_ops 反向 import 本模块,成环)。
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import threading
|
|
30
|
+
import uuid
|
|
31
|
+
from datetime import datetime
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
# PC 发行版引导(ohos-devloop-pc):本目录与 pc/ 入 sys.path,再经 ohos_devloop_pc 注入
|
|
35
|
+
# 服务器 scripts 兄弟目录——脚本直跑与包导入两种形态都能解析扁平兄弟模块(见 pc/README.md)。
|
|
36
|
+
import sys
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
|
|
39
|
+
_PC_DIR = Path(__file__).resolve().parent
|
|
40
|
+
for _cand in (str(_PC_DIR), str(_PC_DIR.parent)):
|
|
41
|
+
if _cand not in sys.path:
|
|
42
|
+
sys.path.insert(0, _cand)
|
|
43
|
+
import ohos_devloop_pc # noqa: E402,F401
|
|
44
|
+
|
|
45
|
+
DEFAULT_LOCK_FILE = Path.home() / ".ohos-devloop" / "pc_service" / "device-locks.json"
|
|
46
|
+
AUDIT_LIMIT = 100
|
|
47
|
+
LOCK_SCHEMA = 1
|
|
48
|
+
|
|
49
|
+
_REQUIRED_KEYS = ("device_serial", "task_id", "workspace", "holder_pid", "locked_at")
|
|
50
|
+
_STR_KEYS = ("device_serial", "task_id", "workspace", "locked_at")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class LockError(Exception):
|
|
54
|
+
"""登记文件或占用语义错误:消息直接可执行(含路径/占用方/修复指引)。"""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _holder_alive(pid) -> bool:
|
|
58
|
+
"""持锁进程探活;任何异常或未知一律视为不存活(保守:解除须用户核对)。
|
|
59
|
+
|
|
60
|
+
坑位:Windows 上 `os.kill(pid, 0)` 会走 TerminateProcess(真的杀进程),
|
|
61
|
+
因此 NT 分支用 OpenProcess + GetExitCodeProcess(STILL_ACTIVE),
|
|
62
|
+
只有 POSIX 才用 os.kill(pid, 0)。
|
|
63
|
+
PID 复用(旧 PID 被新进程占用)视为已接受风险:holder_pid 只是旁证,
|
|
64
|
+
解除仍要求 task 匹配或 confirm_abandoned。
|
|
65
|
+
"""
|
|
66
|
+
try:
|
|
67
|
+
n = int(pid)
|
|
68
|
+
except (TypeError, ValueError):
|
|
69
|
+
return False
|
|
70
|
+
if isinstance(pid, bool) or n <= 0:
|
|
71
|
+
return False
|
|
72
|
+
if os.name == "nt": # pragma: no cover - CI/维护机为 Windows 时实测
|
|
73
|
+
try:
|
|
74
|
+
import ctypes
|
|
75
|
+
kernel32 = ctypes.windll.kernel32
|
|
76
|
+
handle = kernel32.OpenProcess(0x1000, False, n) # QUERY_LIMITED_INFORMATION
|
|
77
|
+
if not handle:
|
|
78
|
+
return False
|
|
79
|
+
try:
|
|
80
|
+
code = ctypes.c_ulong()
|
|
81
|
+
if not kernel32.GetExitCodeProcess(handle, ctypes.byref(code)):
|
|
82
|
+
return False
|
|
83
|
+
return code.value == 259 # STILL_ACTIVE
|
|
84
|
+
finally:
|
|
85
|
+
kernel32.CloseHandle(handle)
|
|
86
|
+
except Exception:
|
|
87
|
+
return False
|
|
88
|
+
try:
|
|
89
|
+
os.kill(n, 0)
|
|
90
|
+
return True
|
|
91
|
+
except (OSError, ValueError, TypeError):
|
|
92
|
+
return False
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _penultimate(path) -> str:
|
|
96
|
+
parts = Path(str(path or "")).parts
|
|
97
|
+
return parts[-2] if len(parts) >= 2 else ""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _match_pool_row(pool_rows, workspace) -> tuple[dict | None, str | None]:
|
|
101
|
+
"""池行定位(镜像 flash.pool_row 口径):先 exact(rstrip '/'),再按路径倒数第二段包含匹配。
|
|
102
|
+
|
|
103
|
+
返回 (row|None, ambiguous_note|None);多命中视为未登记并给「不唯一」告警。
|
|
104
|
+
"""
|
|
105
|
+
key = str(workspace or "").rstrip("/")
|
|
106
|
+
if not key:
|
|
107
|
+
return None, None
|
|
108
|
+
exact = [r for r in pool_rows
|
|
109
|
+
if str(r.get("path") or "").rstrip("/") == key]
|
|
110
|
+
if exact:
|
|
111
|
+
return exact[0], None
|
|
112
|
+
parts = Path(key).parts
|
|
113
|
+
seg = parts[-2] if len(parts) >= 2 else (parts[-1] if parts else "")
|
|
114
|
+
frag = [r for r in pool_rows if seg and seg in _penultimate(r.get("path"))]
|
|
115
|
+
if len(frag) > 1:
|
|
116
|
+
return None, f"工作区关键字不唯一: {seg}(workspace {workspace})"
|
|
117
|
+
return (frag[0] if frag else None), None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class LockStore:
|
|
121
|
+
"""设备占用登记:load 启动加载、lock 互斥、unlock 正常/遗留门、query 查状态。"""
|
|
122
|
+
|
|
123
|
+
def __init__(self, path: str | Path = DEFAULT_LOCK_FILE):
|
|
124
|
+
self.path = Path(path)
|
|
125
|
+
self.locks: dict[str, dict] = {}
|
|
126
|
+
self.audit: list[dict] = []
|
|
127
|
+
self._lock = threading.Lock()
|
|
128
|
+
|
|
129
|
+
# ------------------------------------------------------------------ 载入/落盘
|
|
130
|
+
|
|
131
|
+
def load(self) -> "LockStore":
|
|
132
|
+
"""启动加载:文件缺失 = 空登记;损坏/结构不符 = LockError(fail-closed)。"""
|
|
133
|
+
with self._lock:
|
|
134
|
+
if not self.path.is_file():
|
|
135
|
+
self.locks, self.audit = {}, []
|
|
136
|
+
return self
|
|
137
|
+
try:
|
|
138
|
+
data = json.loads(self.path.read_text(encoding="utf-8"))
|
|
139
|
+
except json.JSONDecodeError as e:
|
|
140
|
+
raise LockError(self._repair(f"不是合法 JSON({e})")) from e
|
|
141
|
+
except OSError as e:
|
|
142
|
+
raise LockError(self._repair(f"无法读取({e})")) from e
|
|
143
|
+
try:
|
|
144
|
+
locks, audit = self._validate_payload(data)
|
|
145
|
+
except ValueError as e:
|
|
146
|
+
raise LockError(self._repair(str(e))) from e
|
|
147
|
+
self.locks, self.audit = locks, audit
|
|
148
|
+
return self
|
|
149
|
+
|
|
150
|
+
def _repair(self, reason: str) -> str:
|
|
151
|
+
return (
|
|
152
|
+
f"设备占用登记不可用: {self.path} —— {reason}。"
|
|
153
|
+
f"人工核对后修复该文件,或移走它再重启 pc 服务(文件不含凭据;"
|
|
154
|
+
f"绝不清空登记启动)。")
|
|
155
|
+
|
|
156
|
+
@staticmethod
|
|
157
|
+
def _validate_payload(data) -> tuple[dict, list]:
|
|
158
|
+
if not isinstance(data, dict):
|
|
159
|
+
raise ValueError("顶层必须是 JSON object")
|
|
160
|
+
if data.get("schema") != LOCK_SCHEMA:
|
|
161
|
+
raise ValueError(f"schema 必须为 {LOCK_SCHEMA},实际 {data.get('schema')!r}")
|
|
162
|
+
locks = data.get("locks")
|
|
163
|
+
if not isinstance(locks, dict):
|
|
164
|
+
raise ValueError("locks 必须是 object")
|
|
165
|
+
clean: dict[str, dict] = {}
|
|
166
|
+
for serial, entry in locks.items():
|
|
167
|
+
if not isinstance(entry, dict):
|
|
168
|
+
raise ValueError(f"locks[{serial!r}] 必须是 object")
|
|
169
|
+
missing = [k for k in _REQUIRED_KEYS if k not in entry]
|
|
170
|
+
if missing:
|
|
171
|
+
raise ValueError(f"locks[{serial!r}] 缺键 {missing}")
|
|
172
|
+
for key in _STR_KEYS:
|
|
173
|
+
if not isinstance(entry[key], str) or not entry[key]:
|
|
174
|
+
raise ValueError(f"locks[{serial!r}].{key} 必须是非空 string")
|
|
175
|
+
pid = entry["holder_pid"]
|
|
176
|
+
if isinstance(pid, bool) or not isinstance(pid, int) or pid <= 0:
|
|
177
|
+
raise ValueError(f"locks[{serial!r}].holder_pid 必须是正整数")
|
|
178
|
+
clean[str(serial)] = dict(entry)
|
|
179
|
+
audit = data.get("audit", [])
|
|
180
|
+
if not isinstance(audit, list):
|
|
181
|
+
raise ValueError("audit 必须是 array")
|
|
182
|
+
return clean, [dict(a) if isinstance(a, dict) else a for a in audit]
|
|
183
|
+
|
|
184
|
+
def _state(self) -> dict:
|
|
185
|
+
return {"schema": LOCK_SCHEMA, "locks": self.locks, "audit": self.audit}
|
|
186
|
+
|
|
187
|
+
def _save(self) -> None:
|
|
188
|
+
"""原子写 + 写后回读逐键校验;不一致抛 LockError(铁律:以落盘为准)。"""
|
|
189
|
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
190
|
+
tmp = self.path.parent / f".{self.path.name}.tmp-{uuid.uuid4().hex}"
|
|
191
|
+
payload = json.dumps(self._state(), sort_keys=True, ensure_ascii=False, indent=2)
|
|
192
|
+
try:
|
|
193
|
+
tmp.write_text(payload, encoding="utf-8", newline="\n")
|
|
194
|
+
os.replace(tmp, self.path)
|
|
195
|
+
except OSError as e:
|
|
196
|
+
raise LockError(self._repair(f"写入失败({e})")) from e
|
|
197
|
+
finally:
|
|
198
|
+
try:
|
|
199
|
+
tmp.unlink()
|
|
200
|
+
except OSError:
|
|
201
|
+
pass
|
|
202
|
+
try:
|
|
203
|
+
disk = json.loads(self.path.read_text(encoding="utf-8"))
|
|
204
|
+
except (OSError, json.JSONDecodeError) as e:
|
|
205
|
+
raise LockError(self._repair(f"写入后回读失败({e})")) from e
|
|
206
|
+
if disk != self._state():
|
|
207
|
+
raise LockError(self._repair("写入后回读与内存态不一致(原子写/并发校验失败)"))
|
|
208
|
+
|
|
209
|
+
# ------------------------------------------------------------------ 占用语义
|
|
210
|
+
|
|
211
|
+
def lock(self, device_serial: str, task_id: str, workspace: str) -> dict:
|
|
212
|
+
"""登记设备占用:同 task 幂等返回既有登记;异 task 拒绝并点名占用方。"""
|
|
213
|
+
serial = str(device_serial)
|
|
214
|
+
task = str(task_id)
|
|
215
|
+
with self._lock:
|
|
216
|
+
existing = self.locks.get(serial)
|
|
217
|
+
if existing is not None:
|
|
218
|
+
if existing["task_id"] == task:
|
|
219
|
+
return dict(existing) | {"locked": True}
|
|
220
|
+
raise LockError(
|
|
221
|
+
f"device {serial} held by task {existing['task_id']}"
|
|
222
|
+
f"(workspace {existing['workspace']})——先确认该任务是否仍在用或待其释放;"
|
|
223
|
+
f"task 与登记不符的解除需带 confirm_abandoned: true(用户核对后)")
|
|
224
|
+
entry = {"device_serial": serial, "task_id": task,
|
|
225
|
+
"workspace": str(workspace), "holder_pid": os.getpid(),
|
|
226
|
+
"locked_at": datetime.now().isoformat(timespec="seconds")}
|
|
227
|
+
locks_before = self.locks
|
|
228
|
+
self.locks = {**self.locks, serial: entry}
|
|
229
|
+
try:
|
|
230
|
+
self._save()
|
|
231
|
+
except LockError:
|
|
232
|
+
self.locks = locks_before
|
|
233
|
+
raise
|
|
234
|
+
return dict(entry) | {"locked": True}
|
|
235
|
+
|
|
236
|
+
def unlock(self, device_serial: str, task_id: str, confirm_abandoned: bool = False,
|
|
237
|
+
device_present: bool = True) -> dict:
|
|
238
|
+
"""释放设备:正常释放幂等;异常遗留(task 不符/holder 不存活/失联)须 confirm。"""
|
|
239
|
+
serial = str(device_serial)
|
|
240
|
+
task = str(task_id)
|
|
241
|
+
with self._lock:
|
|
242
|
+
entry = self.locks.get(serial)
|
|
243
|
+
if entry is None:
|
|
244
|
+
return {"released": False, "reason": "not-held", "device_serial": serial}
|
|
245
|
+
reasons: list[str] = []
|
|
246
|
+
if entry["task_id"] != task:
|
|
247
|
+
reasons.append(f"登记 task={entry['task_id']} 与请求 task={task} 不符")
|
|
248
|
+
if not _holder_alive(entry["holder_pid"]):
|
|
249
|
+
reasons.append(f"holder_pid={entry['holder_pid']} 已不存活")
|
|
250
|
+
if not device_present:
|
|
251
|
+
reasons.append("设备当前不在 hdc 在线列表(失联)")
|
|
252
|
+
anomaly = bool(reasons)
|
|
253
|
+
if anomaly and not confirm_abandoned:
|
|
254
|
+
raise LockError(
|
|
255
|
+
f"device {serial} 的解除被拒:{';'.join(reasons)}"
|
|
256
|
+
f"(登记 workspace={entry['workspace']},task={entry['task_id']})。"
|
|
257
|
+
f"确认设备与工作区已无在跑任务后,带 confirm_abandoned: true 重试"
|
|
258
|
+
f"(解除动作会留审计行)")
|
|
259
|
+
locks_before, audit_before = self.locks, self.audit
|
|
260
|
+
self.locks = {k: v for k, v in self.locks.items() if k != serial}
|
|
261
|
+
row = {"at": datetime.now().isoformat(timespec="seconds"),
|
|
262
|
+
"action": "unlock", "device_serial": serial,
|
|
263
|
+
"task_id": entry["task_id"], "unlocked_by": task,
|
|
264
|
+
"reason": "abandoned-confirm" if anomaly else "normal"}
|
|
265
|
+
self.audit = (self.audit + [row])[-AUDIT_LIMIT:]
|
|
266
|
+
try:
|
|
267
|
+
self._save()
|
|
268
|
+
except LockError:
|
|
269
|
+
self.locks, self.audit = locks_before, audit_before
|
|
270
|
+
raise
|
|
271
|
+
return {"released": True, "device_serial": serial,
|
|
272
|
+
"task_id": entry["task_id"], "reason": row["reason"]}
|
|
273
|
+
|
|
274
|
+
def query(self, targets, pool_rows=None, pool_initialized: bool = True,
|
|
275
|
+
note: str | None = None) -> dict:
|
|
276
|
+
"""每台设备 free/held/lost + 与 workspace_pool.yaml 对账(只读 WARN,绝不改写登记)。
|
|
277
|
+
|
|
278
|
+
- targets ∪ 登记键按序列号排序;登记且在 targets = held,登记但不在 = lost,未登记 = free。
|
|
279
|
+
- 对账(仅登记项):池未初始化 → reconcile null + 单条 note;行内 task 一致 = ok;
|
|
280
|
+
不一致/未登记/关键字不唯一 = warn(notes 与 reconcile_note 呈现,登记数据照抄)。
|
|
281
|
+
- note 参数(如 hdc 不可用)追加进 notes;devices 与 notes 顺序确定。
|
|
282
|
+
"""
|
|
283
|
+
target_set = {str(t) for t in (targets or [])}
|
|
284
|
+
rows = list(pool_rows or [])
|
|
285
|
+
with self._lock:
|
|
286
|
+
locks = {k: dict(v) for k, v in self.locks.items()}
|
|
287
|
+
notes: list[str] = []
|
|
288
|
+
devices = []
|
|
289
|
+
for serial in sorted(target_set | set(locks)):
|
|
290
|
+
entry = locks.get(serial)
|
|
291
|
+
if entry is None:
|
|
292
|
+
status = "free"
|
|
293
|
+
elif serial in target_set:
|
|
294
|
+
status = "held"
|
|
295
|
+
else:
|
|
296
|
+
status = "lost"
|
|
297
|
+
item = {
|
|
298
|
+
"device_serial": serial,
|
|
299
|
+
"status": status,
|
|
300
|
+
"task_id": entry["task_id"] if entry else None,
|
|
301
|
+
"workspace": entry["workspace"] if entry else None,
|
|
302
|
+
"holder_pid": entry["holder_pid"] if entry else None,
|
|
303
|
+
"locked_at": entry["locked_at"] if entry else None,
|
|
304
|
+
"reconcile": None,
|
|
305
|
+
"reconcile_note": None,
|
|
306
|
+
}
|
|
307
|
+
if entry is not None and pool_initialized:
|
|
308
|
+
row, ambiguous = _match_pool_row(rows, entry["workspace"])
|
|
309
|
+
if ambiguous:
|
|
310
|
+
item["reconcile"] = "warn"
|
|
311
|
+
item["reconcile_note"] = ambiguous
|
|
312
|
+
elif row is None:
|
|
313
|
+
item["reconcile"] = "warn"
|
|
314
|
+
item["reconcile_note"] = (
|
|
315
|
+
f"工作区 {entry['workspace']} 未在 workspace_pool.yaml 登记")
|
|
316
|
+
elif str(row.get("task") or "") != entry["task_id"]:
|
|
317
|
+
item["reconcile"] = "warn"
|
|
318
|
+
item["reconcile_note"] = (
|
|
319
|
+
f"对账不一致:设备登记 task={entry['task_id']},"
|
|
320
|
+
f"工作区池 task={row.get('task') or '空'}"
|
|
321
|
+
f"(工作区 {entry['workspace']})")
|
|
322
|
+
else:
|
|
323
|
+
item["reconcile"] = "ok"
|
|
324
|
+
if item["reconcile"] == "warn":
|
|
325
|
+
notes.append(item["reconcile_note"])
|
|
326
|
+
devices.append(item)
|
|
327
|
+
if not pool_initialized:
|
|
328
|
+
notes.insert(0, "工作区池未初始化(无 workspace_pool.yaml),对账跳过")
|
|
329
|
+
if note:
|
|
330
|
+
notes.append(str(note))
|
|
331
|
+
return {"pool_initialized": bool(pool_initialized), "notes": notes,
|
|
332
|
+
"devices": devices}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""挂载/卸载构建服务器工作区到本地盘符(SSHFS-Win 密钥认证)。
|
|
3
|
+
|
|
4
|
+
用法(无 CLI 子命令,脚本路径形态;仓库根目录执行):
|
|
5
|
+
python pc/ohos_devloop_pc/mount_ws.py W: # 挂载当前活跃工作区(workspace_pool.yaml 首个 BUSY/FREE)
|
|
6
|
+
python pc/ohos_devloop_pc/mount_ws.py W: 77da7296b # 按工作区短名挂载
|
|
7
|
+
python pc/ohos_devloop_pc/mount_ws.py unmount W: # 卸载(终止 sshfs 进程)
|
|
8
|
+
|
|
9
|
+
原理(2026-11-05 W: 掉线修复后实测打通,坑位见 RUNBOOK「W: 应急通道」):
|
|
10
|
+
直连 sshfs.exe -f root@HOST:/srv/workspace/<WS>/code X: <options>
|
|
11
|
+
- ssh_command 指向 SSHFS-Win 自带 cygwin ssh(8.3 短路径避开 Program Files 空格,
|
|
12
|
+
该选项按空格切分),认证走 ~/.ssh/config 的 Host 块(Port/IdentityFile)
|
|
13
|
+
- **必须 CREATE_NEW_CONSOLE + STARTUPINFO.SW_HIDE 启动**(等价 PowerShell
|
|
14
|
+
Start-Process -WindowStyle Hidden):cygwin 进程链需要真控制台 stdio,管道/
|
|
15
|
+
文件/DEVNULL 或无控制台(DETACHED_PROCESS/CREATE_NO_WINDOW)都导致 FUSE 创建
|
|
16
|
+
失败 (Status=c000000d);cmd start /b 挂在脚本控制台上,会话一关进程即死
|
|
17
|
+
(2026-11-05 W: 掉线根因);sshfs-win.exe svc 包装经 Popen 启动同样失败
|
|
18
|
+
(原因未明,弃用包装直连 sshfs.exe)
|
|
19
|
+
- **cwd 必须指向 WinFsp bin**(含 winfsp-x64.dll):cygfuse 靠进程 CWD/AppDir
|
|
20
|
+
解析该 DLL;PATH 对 cygwin 进程链无效(2026-11-04 的 WinFsp 2.1 SxS 重装进
|
|
21
|
+
Program Files (x86) 且未写系统 PATH)
|
|
22
|
+
- **必须 -o uid/gid=本地 uid**(fsptool id 解析):服务器目录属主是 huawei/users,
|
|
23
|
+
本地用户不做映射会被当 other → 只读(写报 Errno 13)
|
|
24
|
+
- 编辑纪律:挂载仅作应急人工通道(2026-11-09 起);服务器主 Agent 在领取工作区直接编辑,不经挂载裸改
|
|
25
|
+
"""
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import subprocess
|
|
29
|
+
import sys
|
|
30
|
+
import tempfile
|
|
31
|
+
import time
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
# PC 发行版引导(ohos-devloop-pc):本目录与 pc/ 入 sys.path,再经 ohos_devloop_pc 注入
|
|
35
|
+
# 服务器 scripts 兄弟目录——脚本直跑与包导入两种形态都能解析扁平兄弟模块(见 pc/README.md)。
|
|
36
|
+
import sys
|
|
37
|
+
from pathlib import Path
|
|
38
|
+
|
|
39
|
+
_PC_DIR = Path(__file__).resolve().parent
|
|
40
|
+
for _cand in (str(_PC_DIR), str(_PC_DIR.parent)):
|
|
41
|
+
if _cand not in sys.path:
|
|
42
|
+
sys.path.insert(0, _cand)
|
|
43
|
+
import ohos_devloop_pc # noqa: E402,F401
|
|
44
|
+
|
|
45
|
+
import yaml
|
|
46
|
+
|
|
47
|
+
import wsroot # 工作区根解析(BL-01 回归:包内 parent.parent 语义已变,不得再当仓库根)
|
|
48
|
+
|
|
49
|
+
def pool_file():
|
|
50
|
+
"""工作区池登记文件(读语义):无工作区(安装态)时 None——应急工具不连带 require_ws。"""
|
|
51
|
+
ws = wsroot.ws_root()
|
|
52
|
+
return (ws / "workspace_pool.yaml") if ws else None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def server() -> tuple[str, str]:
|
|
56
|
+
"""(user@host, port)。环境变量优先(MOUNT_WS_SERVER/MOUNT_WS_PORT),缺省读
|
|
57
|
+
inventory.yaml 首个 servers 条目(server_agent.resolve() 同款 env→inventory 链,
|
|
58
|
+
PUB-01 占位化后包内不再携带坐标常量)。"""
|
|
59
|
+
target = os.environ.get("MOUNT_WS_SERVER")
|
|
60
|
+
port = os.environ.get("MOUNT_WS_PORT")
|
|
61
|
+
if not target or not port:
|
|
62
|
+
inv = yaml.safe_load(wsroot.inventory_path().read_text(encoding="utf-8"))
|
|
63
|
+
s = next(iter((inv.get("servers") or {}).values()), {})
|
|
64
|
+
target = target or f"{s.get('user')}@{s.get('host')}"
|
|
65
|
+
port = port or str(s.get("port", 22))
|
|
66
|
+
return target, port
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
SSHFS = r"C:\Program Files\SSHFS-Win\bin\sshfs.exe"
|
|
70
|
+
# 8.3 短路径避开 Program Files 空格;必须正斜杠——sshfs 解析 ssh_command 时把反斜杠当转义吃掉
|
|
71
|
+
SSH_CMD = "C:/PROGRA~1/SSHFS-~1/bin/ssh.exe"
|
|
72
|
+
# 内部快照名不再内嵌(PUB-01 占位化):短名解析一律走 workspace_pool.yaml 登记簿
|
|
73
|
+
# (resolve_workspace/active_workspace 的 pool_file() 回退链是唯一事实来源)
|
|
74
|
+
KNOWN_WS: dict[str, str] = {}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def resolve_workspace(short: str) -> str:
|
|
78
|
+
if short in KNOWN_WS:
|
|
79
|
+
return KNOWN_WS[short]
|
|
80
|
+
for v in KNOWN_WS.values():
|
|
81
|
+
if short in v:
|
|
82
|
+
return v
|
|
83
|
+
# 从登记簿按短名还原完整目录名
|
|
84
|
+
pool = pool_file()
|
|
85
|
+
if pool is not None and pool.is_file():
|
|
86
|
+
text = pool.read_text(encoding="utf-8")
|
|
87
|
+
for line in text.splitlines():
|
|
88
|
+
if short in line and "openharmony_master_default_" in line:
|
|
89
|
+
return line.split("/")[-2]
|
|
90
|
+
raise SystemExit(f"未知工作区短名: {short}(短名从 workspace_pool.yaml 登记簿解析;"
|
|
91
|
+
"先 ohos-devloop flash pool init/status 登记工作区)")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def active_workspace() -> str:
|
|
95
|
+
pool = pool_file()
|
|
96
|
+
if pool is None or not pool.is_file():
|
|
97
|
+
raise SystemExit("workspace_pool.yaml 里没有工作区登记(先 ohos-devloop init 生成工作区)")
|
|
98
|
+
for line in pool.read_text(encoding="utf-8").splitlines():
|
|
99
|
+
if "openharmony_master_default_" in line and "/code" in line:
|
|
100
|
+
return line.split("/")[-2]
|
|
101
|
+
raise SystemExit("workspace_pool.yaml 里没有工作区登记")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def find_winfsp_bin() -> Path:
|
|
105
|
+
"""cygfuse 靠进程 CWD 解析 winfsp-x64.dll,返回含该 DLL 的目录。"""
|
|
106
|
+
candidates = [
|
|
107
|
+
Path(r"C:\Program Files (x86)\WinFsp\bin"), # WinFsp 2.1 SxS 实测布局
|
|
108
|
+
Path(r"C:\Program Files\WinFsp\bin"),
|
|
109
|
+
]
|
|
110
|
+
for p in candidates:
|
|
111
|
+
if (p / "winfsp-x64.dll").is_file():
|
|
112
|
+
return p
|
|
113
|
+
raise SystemExit(f"找不到 winfsp-x64.dll(WinFsp 未安装?候选: {candidates})")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def local_uid_gid() -> tuple:
|
|
117
|
+
"""fsptool 解析当前用户 uid/gid(强制映射给 sshfs,否则挂载只读)。"""
|
|
118
|
+
out = subprocess.run([str(find_winfsp_bin() / "fsptool-x64.exe"), "id"],
|
|
119
|
+
capture_output=True, text=True).stdout
|
|
120
|
+
uid = re.search(r"\(uid=(\d+)\)", out)
|
|
121
|
+
gid = re.search(r"\(gid=(\d+)\)", out)
|
|
122
|
+
if not (uid and gid):
|
|
123
|
+
raise SystemExit(f"fsptool 解析本地 uid/gid 失败: {out!r}")
|
|
124
|
+
return uid.group(1), gid.group(1)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def ensure_junction() -> Path:
|
|
128
|
+
"""主目录 junction:部分 agent harness 的 Edit/Write 写域只放行用户主目录树,
|
|
129
|
+
直接写 W:\\ 盘符会被拒(Read 正常);junction 让 agent 编辑路径落进允许域。
|
|
130
|
+
路径经 DEVLOOP_WS_JUNCTION 环境变量覆写(缺省从当前用户主目录派生 <home>/ws,
|
|
131
|
+
PUB-01 占位化后不再内嵌个人路径)。"""
|
|
132
|
+
junction = Path(os.environ.get("DEVLOOP_WS_JUNCTION", str(Path.home() / "ws")))
|
|
133
|
+
if junction.exists():
|
|
134
|
+
return junction
|
|
135
|
+
try:
|
|
136
|
+
junction.rmdir() # 悬空 junction(挂载已卸)也占名,先删再建;真目录会失败跳过
|
|
137
|
+
except OSError:
|
|
138
|
+
pass
|
|
139
|
+
subprocess.run(
|
|
140
|
+
["powershell", "-NoProfile", "-c",
|
|
141
|
+
f"New-Item -ItemType Junction -Path '{junction}' -Target 'W:\\' | Out-Null"],
|
|
142
|
+
check=True)
|
|
143
|
+
return junction
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def mount(drive: str, ws_short: str) -> None:
|
|
147
|
+
ws = resolve_workspace(ws_short) if ws_short else active_workspace()
|
|
148
|
+
uid, gid = local_uid_gid()
|
|
149
|
+
winfsp = find_winfsp_bin()
|
|
150
|
+
target, _ = server() # user@host(env MOUNT_WS_SERVER/MOUNT_WS_PORT → inventory servers.build-1)
|
|
151
|
+
errlog = Path(tempfile.gettempdir()) / "sshfs_ws.log"
|
|
152
|
+
# CREATE_NEW_CONSOLE + SW_HIDE:给 cygwin 进程链一个隐形真控制台(无控制台/
|
|
153
|
+
# DETACHED_PROCESS/CREATE_NO_WINDOW 都会 FUSE 创建失败);控制台独立于本脚本,
|
|
154
|
+
# 会话关闭不陪葬。stdio 必须显式落到文件——继承管道时 cygwin 链同样会挂
|
|
155
|
+
# (t2 实测:console+file 重定向为文件式启动唯一稳定组合)
|
|
156
|
+
# cwd=WinFsp bin:winfsp-x64.dll 的 LoadLibrary 搜索位(PATH 对 cygwin 链无效)
|
|
157
|
+
si = subprocess.STARTUPINFO()
|
|
158
|
+
si.dwFlags = subprocess.STARTF_USESHOWWINDOW
|
|
159
|
+
si.wShowWindow = 0 # SW_HIDE
|
|
160
|
+
with open(errlog, "wb") as err:
|
|
161
|
+
subprocess.Popen(
|
|
162
|
+
[SSHFS, "-f", f"{target}:/srv/workspace/{ws}/code", drive,
|
|
163
|
+
"-o", f"ssh_command={SSH_CMD}", "-o", "reconnect", "-o", "volname=ws",
|
|
164
|
+
"-o", f"uid={uid}", "-o", f"gid={gid}", "-o", "idmap=user"],
|
|
165
|
+
cwd=str(winfsp),
|
|
166
|
+
creationflags=subprocess.CREATE_NEW_CONSOLE,
|
|
167
|
+
startupinfo=si,
|
|
168
|
+
stdin=subprocess.DEVNULL, stdout=err, stderr=err,
|
|
169
|
+
close_fds=True)
|
|
170
|
+
for _ in range(20):
|
|
171
|
+
time.sleep(1)
|
|
172
|
+
probe = subprocess.run(["cmd", "/c", f"dir {drive}\\ 2>NUL"], capture_output=True)
|
|
173
|
+
if probe.returncode == 0 and b"<DIR>" in probe.stdout:
|
|
174
|
+
junction = ensure_junction()
|
|
175
|
+
print(f"已挂载 {drive} -> {ws}(uid/gid={uid}/{gid},日志: {errlog})")
|
|
176
|
+
print(f"agent 编辑路径: {junction}\\(= {drive}\\;harness Edit/Write 直接写 {drive} 会被写域拒绝)")
|
|
177
|
+
print(f"递归搜索请用: ohos-devloop sgrep <pattern>(挂载盘上递归 grep 很慢)")
|
|
178
|
+
return
|
|
179
|
+
tail = "\n".join(errlog.read_text(errors="replace").splitlines()[-6:])
|
|
180
|
+
raise SystemExit(f"挂载超时({errlog} 末尾:\n{tail})\n"
|
|
181
|
+
f"前台诊断: 在 WinFsp bin 目录下运行 "
|
|
182
|
+
f"\"{SSHFS}\" -f -d {target}:/srv/workspace/{ws}/code {drive} "
|
|
183
|
+
f"-o ssh_command='{SSH_CMD}'")
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def unmount(drive: str) -> None:
|
|
187
|
+
subprocess.run(["taskkill", "/f", "/im", "sshfs.exe"], capture_output=True)
|
|
188
|
+
subprocess.run(["taskkill", "/f", "/im", "sshfs-win.exe"], capture_output=True)
|
|
189
|
+
print(f"已卸载 {drive}(终止 sshfs 进程)")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def main() -> int:
|
|
193
|
+
if len(sys.argv) >= 3 and sys.argv[1] == "unmount":
|
|
194
|
+
unmount(sys.argv[2])
|
|
195
|
+
elif len(sys.argv) >= 2:
|
|
196
|
+
mount(sys.argv[1], sys.argv[2] if len(sys.argv) >= 3 else "")
|
|
197
|
+
else:
|
|
198
|
+
print(__doc__)
|
|
199
|
+
return 0
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
if __name__ == "__main__":
|
|
203
|
+
sys.exit(main())
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""ohos-devloop-pc —— Windows PC 操作代理统一 CLI 入口(独立发行版)。
|
|
4
|
+
|
|
5
|
+
与服务器 `ohos-devloop pc ...` 兼容入口等价(安装本包后服务器入口自动转发到本模块的
|
|
6
|
+
MAP_PC 动词);本入口是 PC 包的唯一 console script(`[project.scripts]`)。
|
|
7
|
+
|
|
8
|
+
子命令 → 同目录脚本一一映射(脚本直跑等价:`python pc/ohos_devloop_pc/<script>.py`):
|
|
9
|
+
|
|
10
|
+
ohos-devloop-pc serve → pc_service.py serve(HTTP 服务,只 bind 127.0.0.1)
|
|
11
|
+
ohos-devloop-pc token → pc_service.py token
|
|
12
|
+
ohos-devloop-pc tunnel → pc_service.py tunnel
|
|
13
|
+
ohos-devloop-pc check → pc_service.py check
|
|
14
|
+
ohos-devloop-pc ops [--json] → pc_service.py ops
|
|
15
|
+
ohos-devloop-pc setup → pc_service.py setup
|
|
16
|
+
ohos-devloop-pc self-check → pc_service.py self-check
|
|
17
|
+
ohos-devloop-pc rkflash → rkflash.py(RK3568 upgrade_tool 命令行刷机)
|
|
18
|
+
ohos-devloop-pc dayu600-skip-setup → dayu600_skip_setup.py
|
|
19
|
+
ohos-devloop-pc dayu600-flash-setup → dayu600_flash_setup.py
|
|
20
|
+
ohos-devloop-pc version → 打印本包与已安装 ohos-devloop 版本
|
|
21
|
+
ohos-devloop-pc pc <动词> ... → 前导 `pc` 别名(与服务器入口同形,等价省略)
|
|
22
|
+
|
|
23
|
+
安装:pipx install ohos-devloop-pc(自动拉取同版本 ohos-devloop,共享脚本模块来源)。
|
|
24
|
+
未安装 ohos-devloop 时本包 import 即抛带说明的 ImportError(见 __init__.py)。
|
|
25
|
+
"""
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
HERE = Path(__file__).resolve().parent
|
|
31
|
+
|
|
32
|
+
# 动词 → (同目录脚本, 预置参数)。与服务器 ohos_cli.MAP 同款结构:
|
|
33
|
+
# pc_service 七个动词本身是脚本的一级子命令(预置同名动词);rkflash 的 plan/emit/run/...
|
|
34
|
+
# 是脚本自己的二级子命令(原样透传);dayu600 两条是纯 flag CLI(动词只用于选脚本)。
|
|
35
|
+
MAP_PC = {
|
|
36
|
+
"serve": ("pc_service.py", ["serve"]),
|
|
37
|
+
"token": ("pc_service.py", ["token"]),
|
|
38
|
+
"tunnel": ("pc_service.py", ["tunnel"]),
|
|
39
|
+
"check": ("pc_service.py", ["check"]),
|
|
40
|
+
"ops": ("pc_service.py", ["ops"]),
|
|
41
|
+
"setup": ("pc_service.py", ["setup"]),
|
|
42
|
+
"self-check": ("pc_service.py", ["self-check"]),
|
|
43
|
+
"rkflash": ("rkflash.py", []),
|
|
44
|
+
"dayu600-skip-setup": ("dayu600_skip_setup.py", []),
|
|
45
|
+
"dayu600-flash-setup": ("dayu600_flash_setup.py", []),
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
USAGE = __doc__.split("安装:pipx install")[0] # docstring 到「安装」节前作 usage
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _dist_version(name: str) -> str:
|
|
52
|
+
"""已安装发行版版本;metadata 缺失(源码树直跑)回退 unknown。"""
|
|
53
|
+
try:
|
|
54
|
+
from importlib.metadata import version as v
|
|
55
|
+
|
|
56
|
+
return v(name) or "unknown"
|
|
57
|
+
except Exception:
|
|
58
|
+
return "unknown"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def version() -> str:
|
|
62
|
+
"""一行版本摘要:ohos-devloop-pc 与已安装 ohos-devloop(共享模块来源)版本。"""
|
|
63
|
+
return (f"ohos-devloop-pc {_dist_version('ohos-devloop-pc')} "
|
|
64
|
+
f"(ohos-devloop {_dist_version('ohos-devloop')})")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def main(argv: list[str] | None = None) -> int:
|
|
68
|
+
# 与服务器入口同款:Windows 中文帮助不乱码,行缓冲便于管道消费
|
|
69
|
+
try:
|
|
70
|
+
sys.stdout.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
|
|
71
|
+
sys.stderr.reconfigure(encoding="utf-8", errors="replace", line_buffering=True)
|
|
72
|
+
except Exception:
|
|
73
|
+
pass
|
|
74
|
+
args = list(sys.argv[1:] if argv is None else argv)
|
|
75
|
+
if args and args[0] == "pc": # 前导 pc 别名:ohos-devloop-pc pc setup 等价 ohos-devloop-pc setup
|
|
76
|
+
args = args[1:]
|
|
77
|
+
if not args:
|
|
78
|
+
print("用法: ohos-devloop-pc pc <动词> ...(动词列表见 ohos-devloop-pc --help)")
|
|
79
|
+
return 2
|
|
80
|
+
if not args or args[0] in ("-h", "--help"):
|
|
81
|
+
print(USAGE)
|
|
82
|
+
print(f"version: {version()}")
|
|
83
|
+
return 0
|
|
84
|
+
if args[0] in ("version", "--version", "-V"):
|
|
85
|
+
print(version())
|
|
86
|
+
return 0
|
|
87
|
+
sub, rest = args[0], args[1:]
|
|
88
|
+
entry = MAP_PC.get(sub)
|
|
89
|
+
if entry is None:
|
|
90
|
+
print(f"未知子命令: {sub}\n{USAGE}", file=sys.stderr)
|
|
91
|
+
return 2
|
|
92
|
+
script, pre = entry
|
|
93
|
+
target = HERE / script
|
|
94
|
+
if not target.is_file():
|
|
95
|
+
print(f"ERROR: {target} 不存在(包不完整?重装 ohos-devloop-pc)", file=sys.stderr)
|
|
96
|
+
return 2
|
|
97
|
+
p = subprocess.run([sys.executable, str(target), *pre, *rest])
|
|
98
|
+
return p.returncode
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
if __name__ == "__main__":
|
|
102
|
+
sys.exit(main())
|