p2pmesh 0.5.2__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.
- mesh/__init__.py +95 -0
- mesh/address.py +211 -0
- mesh/agent.py +701 -0
- mesh/auth.py +167 -0
- mesh/capability.py +398 -0
- mesh/cli.py +1037 -0
- mesh/delta.py +521 -0
- mesh/hub.py +1287 -0
- mesh/queue.py +1041 -0
- mesh/task.py +529 -0
- mesh/wire.py +453 -0
- p2pmesh-0.5.2.dist-info/METADATA +552 -0
- p2pmesh-0.5.2.dist-info/RECORD +17 -0
- p2pmesh-0.5.2.dist-info/WHEEL +5 -0
- p2pmesh-0.5.2.dist-info/entry_points.txt +2 -0
- p2pmesh-0.5.2.dist-info/licenses/LICENSE +21 -0
- p2pmesh-0.5.2.dist-info/top_level.txt +1 -0
mesh/agent.py
ADDED
|
@@ -0,0 +1,701 @@
|
|
|
1
|
+
"""节点 agent:把一台机器的文件、能力、算力暴露成 Mesh 端点。
|
|
2
|
+
|
|
3
|
+
安全模型(三层)
|
|
4
|
+
----------------
|
|
5
|
+
1. **路径围栏**:每个 root 是一个命名目录,所有访问都经 :func:`jail` 解析。
|
|
6
|
+
用 ``realpath`` 解析后再验证包含关系,所以**符号链接逃逸也会被拦下**。
|
|
7
|
+
2. **root 模式**:``ro`` 的 root 直接拒绝任何写操作。
|
|
8
|
+
3. **写作用域**:作业执行前后对比改动文件,用 :func:`task.check_scope` 校验。
|
|
9
|
+
越界就报错并列出越界路径 —— 这是防止 agent 乱改文件的关键一层。
|
|
10
|
+
|
|
11
|
+
令牌
|
|
12
|
+
----
|
|
13
|
+
所有 ``/rpc/*`` 都要 ``Authorization: Bearer <token>``;``/health`` 不需要,
|
|
14
|
+
方便控制面探活。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import os
|
|
21
|
+
import platform
|
|
22
|
+
import shutil
|
|
23
|
+
import subprocess
|
|
24
|
+
import tempfile
|
|
25
|
+
import threading
|
|
26
|
+
import time
|
|
27
|
+
|
|
28
|
+
from . import address, capability, delta, queue, task, wire
|
|
29
|
+
|
|
30
|
+
__all__ = ["AgentError", "Node", "jail", "serve"]
|
|
31
|
+
|
|
32
|
+
MAX_READ = 8 << 20 # 单次 read 上限 8MB
|
|
33
|
+
DEFAULT_BACKUP_FILES = 20000 # 回滚备份的文件数上限
|
|
34
|
+
DEFAULT_BACKUP_BYTES = 64 << 20 # 回滚备份的字节上限(超出就只检测不备份)
|
|
35
|
+
MAX_SIG_BLOCKS = 200000 # 签名表最大块数(防内存爆)
|
|
36
|
+
MAX_EXEC_OUT = 1 << 18 # 命令输出截断到 256KB
|
|
37
|
+
READ_CHUNK = 1 << 20
|
|
38
|
+
SKIP_DIRS = (".git", "__pycache__", "node_modules", ".venv") # 作用域扫描跳过
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class AgentError(Exception):
|
|
42
|
+
"""节点侧拒绝:路径越界、只读、参数非法等。"""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def jail(base, target):
|
|
46
|
+
"""把 ``target`` 关进 ``base`` 里。越界抛 :class:`AgentError`。
|
|
47
|
+
|
|
48
|
+
两边都先 ``realpath``,所以 ``..`` 和符号链接都逃不出去。
|
|
49
|
+
"""
|
|
50
|
+
base = os.path.realpath(base)
|
|
51
|
+
target = os.path.realpath(target)
|
|
52
|
+
if target == base:
|
|
53
|
+
return target
|
|
54
|
+
if not target.startswith(base + os.sep):
|
|
55
|
+
raise AgentError("路径越界:%s 不在 %s 之内" % (target, base))
|
|
56
|
+
return target
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _sha256_file(path, chunk=READ_CHUNK):
|
|
60
|
+
h = hashlib.sha256()
|
|
61
|
+
with open(path, "rb") as f:
|
|
62
|
+
while True:
|
|
63
|
+
block = f.read(chunk)
|
|
64
|
+
if not block:
|
|
65
|
+
break
|
|
66
|
+
h.update(block)
|
|
67
|
+
return h.hexdigest()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _parse_addr(addr):
|
|
71
|
+
"""把地址统一解析成 MeshAddress,并把地址层错误收敛成 AgentError。
|
|
72
|
+
|
|
73
|
+
调用方只该 catch ``AgentError`` 一种异常 —— 否则每加一层校验,
|
|
74
|
+
调用方就得多 catch 一种类型。
|
|
75
|
+
"""
|
|
76
|
+
if isinstance(addr, address.MeshAddress):
|
|
77
|
+
return addr
|
|
78
|
+
try:
|
|
79
|
+
return address.parse(addr)
|
|
80
|
+
except address.AddressError as exc:
|
|
81
|
+
raise AgentError("地址不合法:%s" % exc)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Node(object):
|
|
85
|
+
"""一台机器在 Mesh 里的化身。"""
|
|
86
|
+
|
|
87
|
+
def __init__(self, node_id, roots=None, token="", name=None, tags=None,
|
|
88
|
+
slots_total=1, agents=None, models=None, tool_names=None,
|
|
89
|
+
exec_enabled=False, exec_allow_shell=False, probe_versions=False,
|
|
90
|
+
runner=None, rollback=True,
|
|
91
|
+
backup_max_files=DEFAULT_BACKUP_FILES,
|
|
92
|
+
backup_max_bytes=DEFAULT_BACKUP_BYTES):
|
|
93
|
+
if not address.is_valid_name(node_id):
|
|
94
|
+
raise AgentError(
|
|
95
|
+
"节点名不合法:%r(需字母、数字或汉字开头,可含 . _ -,最长 64 字符)"
|
|
96
|
+
% (node_id,))
|
|
97
|
+
self.node_id = node_id
|
|
98
|
+
self.token = token
|
|
99
|
+
self.name = name or platform.node() or node_id
|
|
100
|
+
self.tags = list(tags or [])
|
|
101
|
+
self.slots_total = int(slots_total)
|
|
102
|
+
self.slots_used = 0
|
|
103
|
+
self.agents = list(agents or ["mock", "cli", "http"])
|
|
104
|
+
self.models = list(models or [])
|
|
105
|
+
self.tool_names = list(tool_names or capability.DEFAULT_TOOLS)
|
|
106
|
+
self.exec_enabled = bool(exec_enabled)
|
|
107
|
+
self.exec_allow_shell = bool(exec_allow_shell)
|
|
108
|
+
self.probe_versions = bool(probe_versions)
|
|
109
|
+
self.runner = runner
|
|
110
|
+
# 回滚:作业跑之前把 root 里的文件备份一份,越界就整体还原。
|
|
111
|
+
# 越界写检测是事后的 —— 不备份就只能报警,不能撤销。
|
|
112
|
+
self.rollback = bool(rollback)
|
|
113
|
+
self.backup_max_files = int(backup_max_files)
|
|
114
|
+
self.backup_max_bytes = int(backup_max_bytes)
|
|
115
|
+
|
|
116
|
+
self.roots = {}
|
|
117
|
+
self._cap = None
|
|
118
|
+
self._lock = threading.RLock()
|
|
119
|
+
self.started_at = time.time()
|
|
120
|
+
|
|
121
|
+
for item in (roots or []):
|
|
122
|
+
self.add_root(item["name"], item["path"], item.get("mode", "rw"))
|
|
123
|
+
|
|
124
|
+
# ------------------------------------------------------------------
|
|
125
|
+
# root 管理
|
|
126
|
+
# ------------------------------------------------------------------
|
|
127
|
+
def add_root(self, name, path, mode="rw"):
|
|
128
|
+
if not name:
|
|
129
|
+
raise AgentError("root 必须有名字")
|
|
130
|
+
if mode not in ("rw", "ro"):
|
|
131
|
+
raise AgentError("root 模式只能是 rw 或 ro,收到 %r" % (mode,))
|
|
132
|
+
abs_path = os.path.realpath(os.path.expanduser(path))
|
|
133
|
+
if not os.path.isdir(abs_path):
|
|
134
|
+
raise AgentError("root 目录不存在:%s" % abs_path)
|
|
135
|
+
with self._lock:
|
|
136
|
+
self.roots[name] = {"path": abs_path, "mode": mode}
|
|
137
|
+
self._cap = None
|
|
138
|
+
return abs_path
|
|
139
|
+
|
|
140
|
+
def roots_info(self):
|
|
141
|
+
return [{"name": n, "path": r["path"], "mode": r["mode"]}
|
|
142
|
+
for n, r in sorted(self.roots.items())]
|
|
143
|
+
|
|
144
|
+
# ------------------------------------------------------------------
|
|
145
|
+
# 路径解析
|
|
146
|
+
# ------------------------------------------------------------------
|
|
147
|
+
def resolve(self, addr, mode="read"):
|
|
148
|
+
"""``mesh://node/env:root/path`` → 本机绝对路径(已过围栏)。"""
|
|
149
|
+
addr = _parse_addr(addr)
|
|
150
|
+
if not addr.root:
|
|
151
|
+
raise AgentError("地址缺少 root:%s" % addr)
|
|
152
|
+
root = self.roots.get(addr.root)
|
|
153
|
+
if root is None:
|
|
154
|
+
raise AgentError("本节点没有 root %r(可用:%s)"
|
|
155
|
+
% (addr.root, ", ".join(sorted(self.roots)) or "无"))
|
|
156
|
+
if mode == "write" and root["mode"] != "rw":
|
|
157
|
+
raise AgentError("root %r 是只读的" % addr.root)
|
|
158
|
+
|
|
159
|
+
base = root["path"]
|
|
160
|
+
if not addr.path:
|
|
161
|
+
return jail(base, base)
|
|
162
|
+
|
|
163
|
+
# 先关父目录,再拼文件名 —— 这样"写一个新文件"也能正确校验
|
|
164
|
+
parent = os.path.dirname(addr.path)
|
|
165
|
+
leaf = os.path.basename(addr.path)
|
|
166
|
+
if parent:
|
|
167
|
+
parent = jail(base, os.path.join(base, parent))
|
|
168
|
+
else:
|
|
169
|
+
parent = base
|
|
170
|
+
return jail(base, os.path.join(parent, leaf))
|
|
171
|
+
|
|
172
|
+
# ------------------------------------------------------------------
|
|
173
|
+
# 能力
|
|
174
|
+
# ------------------------------------------------------------------
|
|
175
|
+
def capability(self):
|
|
176
|
+
"""返回本节点能力快照(静态部分缓存,动态部分每次刷新)。"""
|
|
177
|
+
with self._lock:
|
|
178
|
+
if self._cap is None:
|
|
179
|
+
self._cap = capability.probe(
|
|
180
|
+
self.node_id, name=self.name, tags=self.tags,
|
|
181
|
+
roots=self.roots_info(), tools=self.tool_names,
|
|
182
|
+
slots_total=self.slots_total, slots_used=self.slots_used,
|
|
183
|
+
agents=self.agents, models=self.models,
|
|
184
|
+
exec_enabled=self.exec_enabled,
|
|
185
|
+
exec_allow_shell=self.exec_allow_shell,
|
|
186
|
+
with_versions=self.probe_versions,
|
|
187
|
+
)
|
|
188
|
+
cap = self._cap
|
|
189
|
+
|
|
190
|
+
cap.loadavg = capability._loadavg()
|
|
191
|
+
mem = capability._meminfo()
|
|
192
|
+
if mem:
|
|
193
|
+
cap.mem_total = mem.get("MemTotal", cap.mem_total)
|
|
194
|
+
cap.mem_avail = mem.get("MemAvailable", cap.mem_avail)
|
|
195
|
+
base = next(iter(self.roots.values()))["path"] if self.roots else os.getcwd()
|
|
196
|
+
usage = capability._disk(base)
|
|
197
|
+
cap.disk_total, cap.disk_free = usage["total"], usage["free"]
|
|
198
|
+
cap.slots_used = self.slots_used
|
|
199
|
+
cap.last_seen = time.time()
|
|
200
|
+
return cap
|
|
201
|
+
|
|
202
|
+
# ------------------------------------------------------------------
|
|
203
|
+
# 槽位
|
|
204
|
+
# ------------------------------------------------------------------
|
|
205
|
+
def acquire_slot(self):
|
|
206
|
+
with self._lock:
|
|
207
|
+
if self.slots_used >= self.slots_total:
|
|
208
|
+
return False
|
|
209
|
+
self.slots_used += 1
|
|
210
|
+
return True
|
|
211
|
+
|
|
212
|
+
def release_slot(self):
|
|
213
|
+
with self._lock:
|
|
214
|
+
if self.slots_used > 0:
|
|
215
|
+
self.slots_used -= 1
|
|
216
|
+
|
|
217
|
+
# ------------------------------------------------------------------
|
|
218
|
+
# 文件操作
|
|
219
|
+
# ------------------------------------------------------------------
|
|
220
|
+
def op_ls(self, payload):
|
|
221
|
+
path = self.resolve(payload.get("addr") or "", "read")
|
|
222
|
+
if not os.path.isdir(path):
|
|
223
|
+
raise AgentError("不是目录:%s" % path)
|
|
224
|
+
limit = int(payload.get("limit") or 1000)
|
|
225
|
+
entries = []
|
|
226
|
+
with os.scandir(path) as it:
|
|
227
|
+
for entry in it:
|
|
228
|
+
try:
|
|
229
|
+
st = entry.stat(follow_symlinks=False)
|
|
230
|
+
except OSError:
|
|
231
|
+
continue
|
|
232
|
+
entries.append({
|
|
233
|
+
"name": entry.name,
|
|
234
|
+
"dir": entry.is_dir(follow_symlinks=False),
|
|
235
|
+
"link": entry.is_symlink(),
|
|
236
|
+
"size": st.st_size,
|
|
237
|
+
"mtime": st.st_mtime,
|
|
238
|
+
})
|
|
239
|
+
if len(entries) >= limit:
|
|
240
|
+
break
|
|
241
|
+
entries.sort(key=lambda e: (not e["dir"], e["name"]))
|
|
242
|
+
return {"entries": entries, "count": len(entries), "truncated": len(entries) >= limit}
|
|
243
|
+
|
|
244
|
+
def op_stat(self, payload):
|
|
245
|
+
path = self.resolve(payload.get("addr") or "", "read")
|
|
246
|
+
if not os.path.exists(path):
|
|
247
|
+
return {"exists": False}
|
|
248
|
+
st = os.stat(path)
|
|
249
|
+
out = {
|
|
250
|
+
"exists": True,
|
|
251
|
+
"dir": os.path.isdir(path),
|
|
252
|
+
"size": st.st_size,
|
|
253
|
+
"mtime": st.st_mtime,
|
|
254
|
+
"mode": oct(st.st_mode & 0o777),
|
|
255
|
+
}
|
|
256
|
+
if payload.get("sha") and os.path.isfile(path):
|
|
257
|
+
out["sha"] = _sha256_file(path)
|
|
258
|
+
return out
|
|
259
|
+
|
|
260
|
+
def op_read(self, payload):
|
|
261
|
+
path = self.resolve(payload.get("addr") or "", "read")
|
|
262
|
+
if not os.path.isfile(path):
|
|
263
|
+
raise AgentError("不是文件:%s" % path)
|
|
264
|
+
offset = max(0, int(payload.get("offset") or 0))
|
|
265
|
+
limit = int(payload.get("limit") or -1)
|
|
266
|
+
if limit < 0 or limit > MAX_READ:
|
|
267
|
+
limit = MAX_READ
|
|
268
|
+
with open(path, "rb") as f:
|
|
269
|
+
f.seek(offset)
|
|
270
|
+
data = f.read(limit)
|
|
271
|
+
return {"data": wire.b64e(data), "size": len(data),
|
|
272
|
+
"eof": len(data) < limit, "total": os.path.getsize(path)}
|
|
273
|
+
|
|
274
|
+
def op_write(self, payload):
|
|
275
|
+
path = self.resolve(payload.get("addr") or "", "write")
|
|
276
|
+
data = wire.b64d(payload.get("data") or "")
|
|
277
|
+
|
|
278
|
+
# 可选的写作用��校验(纵深防御:root 之外再加一层)
|
|
279
|
+
scope = payload.get("scope") or []
|
|
280
|
+
if scope:
|
|
281
|
+
rel = os.path.relpath(path, self._root_path_for(payload.get("addr")))
|
|
282
|
+
rel = rel.replace(os.sep, "/")
|
|
283
|
+
if not any(task.glob_match(g, rel) for g in scope):
|
|
284
|
+
raise AgentError("写入 %s 超出作业作用域 %s" % (rel, scope))
|
|
285
|
+
|
|
286
|
+
expected = payload.get("expected_sha")
|
|
287
|
+
if expected and os.path.isfile(path):
|
|
288
|
+
actual = _sha256_file(path)
|
|
289
|
+
if actual != expected:
|
|
290
|
+
raise AgentError("文件已被改动:期望 %s…,实际 %s…"
|
|
291
|
+
% (expected[:12], actual[:12]))
|
|
292
|
+
|
|
293
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
294
|
+
tmp = path + ".mesh-write-tmp"
|
|
295
|
+
try:
|
|
296
|
+
with open(tmp, "wb") as f:
|
|
297
|
+
f.write(data)
|
|
298
|
+
f.flush()
|
|
299
|
+
os.fsync(f.fileno())
|
|
300
|
+
os.replace(tmp, path)
|
|
301
|
+
except Exception:
|
|
302
|
+
try:
|
|
303
|
+
os.unlink(tmp)
|
|
304
|
+
except OSError:
|
|
305
|
+
pass
|
|
306
|
+
raise
|
|
307
|
+
return {"sha": hashlib.sha256(data).hexdigest(), "size": len(data)}
|
|
308
|
+
|
|
309
|
+
def op_rm(self, payload):
|
|
310
|
+
"""删一个文件 —— 分发时"源那边删了"要能在目标上同样删掉。
|
|
311
|
+
|
|
312
|
+
只删文件:删目录等于把一个子树的删除语义(空目录?递归?)塞进一个
|
|
313
|
+
RPC,那件事该由作业自己用 ``exec`` 干。root 是 ``ro`` 的照样拒绝。
|
|
314
|
+
"""
|
|
315
|
+
path = self.resolve(payload.get("addr") or "", "write")
|
|
316
|
+
|
|
317
|
+
scope = payload.get("scope") or []
|
|
318
|
+
if scope:
|
|
319
|
+
rel = os.path.relpath(path, self._root_path_for(payload.get("addr")))
|
|
320
|
+
rel = rel.replace(os.sep, "/")
|
|
321
|
+
if not any(task.glob_match(g, rel) for g in scope):
|
|
322
|
+
raise AgentError("删除 %s 超出作业作用域 %s" % (rel, scope))
|
|
323
|
+
|
|
324
|
+
if os.path.isdir(path) and not os.path.islink(path):
|
|
325
|
+
raise AgentError("rm 只删文件,不删目录:%s" % path)
|
|
326
|
+
if not os.path.lexists(path):
|
|
327
|
+
return {"removed": False, "existed": False}
|
|
328
|
+
os.remove(path)
|
|
329
|
+
return {"removed": True, "existed": True}
|
|
330
|
+
|
|
331
|
+
def _root_path_for(self, addr):
|
|
332
|
+
addr = _parse_addr(addr)
|
|
333
|
+
root = self.roots.get(addr.root)
|
|
334
|
+
return root["path"] if root else os.getcwd()
|
|
335
|
+
|
|
336
|
+
# ------------------------------------------------------------------
|
|
337
|
+
# 差分端点(rsync 流程)
|
|
338
|
+
# ------------------------------------------------------------------
|
|
339
|
+
def op_sig(self, payload):
|
|
340
|
+
"""接收方要旧文件的块校验表。"""
|
|
341
|
+
path = self.resolve(payload.get("addr") or "", "read")
|
|
342
|
+
block_size = int(payload.get("block_size") or delta.DEFAULT_BLOCK_SIZE)
|
|
343
|
+
try:
|
|
344
|
+
delta._check_block_size(block_size)
|
|
345
|
+
except delta.DeltaError as exc:
|
|
346
|
+
raise AgentError(str(exc))
|
|
347
|
+
if not os.path.isfile(path):
|
|
348
|
+
return {"sig": [], "old_sha": "", "size": 0}
|
|
349
|
+
size = os.path.getsize(path)
|
|
350
|
+
if size // block_size > MAX_SIG_BLOCKS:
|
|
351
|
+
raise AgentError("文件太大,签名表会超过 %d 块" % MAX_SIG_BLOCKS)
|
|
352
|
+
with open(path, "rb") as f:
|
|
353
|
+
data = f.read()
|
|
354
|
+
return {
|
|
355
|
+
"sig": [list(item) for item in delta.block_signature(data, block_size)],
|
|
356
|
+
"old_sha": hashlib.sha256(data).hexdigest(),
|
|
357
|
+
"size": size,
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
def op_delta(self, payload):
|
|
361
|
+
"""发送方:只有签名表,产出从接收��旧版到本节点当前版��差分。"""
|
|
362
|
+
path = self.resolve(payload.get("addr") or "", "read")
|
|
363
|
+
if not os.path.isfile(path):
|
|
364
|
+
raise AgentError("不是文件:%s" % path)
|
|
365
|
+
block_size = int(payload.get("block_size") or delta.DEFAULT_BLOCK_SIZE)
|
|
366
|
+
sig = payload.get("sig") or []
|
|
367
|
+
with open(path, "rb") as f:
|
|
368
|
+
new = f.read()
|
|
369
|
+
try:
|
|
370
|
+
d = delta.diff_with_sig(sig, new, block_size,
|
|
371
|
+
old_sha=payload.get("old_sha") or "")
|
|
372
|
+
except delta.DeltaError as exc:
|
|
373
|
+
raise AgentError("生成差分失败:%s" % exc)
|
|
374
|
+
return {"delta": d.to_dict(), "estimate": delta.estimate(d)}
|
|
375
|
+
|
|
376
|
+
def op_patch(self, payload):
|
|
377
|
+
"""接收方:用本地旧文件 + 差分重建。"""
|
|
378
|
+
path = self.resolve(payload.get("addr") or "", "write")
|
|
379
|
+
if not os.path.isfile(path):
|
|
380
|
+
raise AgentError("基线文件不存在:%s" % path)
|
|
381
|
+
try:
|
|
382
|
+
d = delta.Delta.from_dict(payload.get("delta") or {})
|
|
383
|
+
sha = delta.patch_file(path, d, path)
|
|
384
|
+
except delta.DeltaError as exc:
|
|
385
|
+
raise AgentError("应用差分失败:%s" % exc)
|
|
386
|
+
return {"sha": sha, "size": os.path.getsize(path)}
|
|
387
|
+
|
|
388
|
+
# ------------------------------------------------------------------
|
|
389
|
+
# 命令执行
|
|
390
|
+
# ------------------------------------------------------------------
|
|
391
|
+
def op_exec(self, payload):
|
|
392
|
+
if not self.exec_enabled:
|
|
393
|
+
raise AgentError("本节点未开启命令执行(exec_enabled=False)")
|
|
394
|
+
cmd = payload.get("cmd") or ""
|
|
395
|
+
if not cmd:
|
|
396
|
+
raise AgentError("缺少 cmd")
|
|
397
|
+
cwd = payload.get("cwd") or ""
|
|
398
|
+
if cwd:
|
|
399
|
+
cwd = self.resolve(cwd, "read")
|
|
400
|
+
else:
|
|
401
|
+
cwd = next(iter(self.roots.values()))["path"] if self.roots else os.getcwd()
|
|
402
|
+
timeout = max(0.1, min(float(payload.get("timeout") or 60), 3600.0))
|
|
403
|
+
try:
|
|
404
|
+
proc = subprocess.run(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE,
|
|
405
|
+
stderr=subprocess.PIPE, timeout=timeout)
|
|
406
|
+
except subprocess.TimeoutExpired:
|
|
407
|
+
raise AgentError("命令超时(%.0fs)" % timeout)
|
|
408
|
+
return {
|
|
409
|
+
"rc": proc.returncode,
|
|
410
|
+
"stdout": proc.stdout[:MAX_EXEC_OUT].decode("utf-8", "replace"),
|
|
411
|
+
"stderr": proc.stderr[:MAX_EXEC_OUT].decode("utf-8", "replace"),
|
|
412
|
+
"truncated": len(proc.stdout) > MAX_EXEC_OUT or len(proc.stderr) > MAX_EXEC_OUT,
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
# ------------------------------------------------------------------
|
|
416
|
+
# 作业执行
|
|
417
|
+
# ------------------------------------------------------------------
|
|
418
|
+
def _job_root_name(self, job):
|
|
419
|
+
name = (job.req or {}).get("root")
|
|
420
|
+
if name:
|
|
421
|
+
if name not in self.roots:
|
|
422
|
+
raise AgentError("作业要求的 root %r 不存在(可用:%s)"
|
|
423
|
+
% (name, ", ".join(sorted(self.roots)) or "无"))
|
|
424
|
+
return name
|
|
425
|
+
if len(self.roots) == 1:
|
|
426
|
+
return next(iter(self.roots))
|
|
427
|
+
raise AgentError("作业未指定 root,而本节点有多个 root:%s"
|
|
428
|
+
% ", ".join(sorted(self.roots)))
|
|
429
|
+
|
|
430
|
+
def _dirs(self, job):
|
|
431
|
+
"""root 内所有子目录(相对路径),回滚时用来清理作业新建的空目录。"""
|
|
432
|
+
root_name = self._job_root_name(job)
|
|
433
|
+
base = self.roots[root_name]["path"]
|
|
434
|
+
out = set()
|
|
435
|
+
for dirpath, dirnames, _filenames in os.walk(base):
|
|
436
|
+
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
|
437
|
+
rel = os.path.relpath(dirpath, base).replace(os.sep, "/")
|
|
438
|
+
if rel != ".":
|
|
439
|
+
out.add(rel)
|
|
440
|
+
return out
|
|
441
|
+
|
|
442
|
+
def _snapshot(self, job, max_files=20000):
|
|
443
|
+
"""root 内每个文件的 ``(mtime_ns, size)`` —— 作业前后的比对基线。
|
|
444
|
+
|
|
445
|
+
为什么不用"记下开始时间、事后找 mtime >= 开始时间"这种朴素做法:
|
|
446
|
+
文件系统的 mtime 和 :func:`time.time` 不是同一个精度、甚至会小幅偏移
|
|
447
|
+
(实测能差几毫秒),同一瞬间写出的文件就会被判成"没改过"。
|
|
448
|
+
写作用域校验靠这个清单把关,漏检等于闸门失效,所以改成自己比自己。
|
|
449
|
+
"""
|
|
450
|
+
root_name = self._job_root_name(job)
|
|
451
|
+
base = self.roots[root_name]["path"]
|
|
452
|
+
snap = {}
|
|
453
|
+
for dirpath, dirnames, filenames in os.walk(base):
|
|
454
|
+
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
|
455
|
+
for name in filenames:
|
|
456
|
+
if len(snap) >= max_files:
|
|
457
|
+
return snap
|
|
458
|
+
full = os.path.join(dirpath, name)
|
|
459
|
+
try:
|
|
460
|
+
st = os.stat(full)
|
|
461
|
+
except OSError:
|
|
462
|
+
continue
|
|
463
|
+
rel = os.path.relpath(full, base).replace(os.sep, "/")
|
|
464
|
+
snap[rel] = (st.st_mtime_ns, st.st_size)
|
|
465
|
+
return snap
|
|
466
|
+
|
|
467
|
+
def _changed_since(self, job, baseline, max_files=20000):
|
|
468
|
+
"""相对 ``baseline`` 快照被新增/改动/删除的文件。返回 ``(changed, deleted)``。
|
|
469
|
+
|
|
470
|
+
注意:**扫整个 root**,不是只扫写作用域目录。否则 agent 写到作用域之外
|
|
471
|
+
的文件根本不会被发现 —— 那样作用域校验就形同虚设。
|
|
472
|
+
代价是每次作业后要走一遍目录树,用 ``max_files`` 兜底防爆。
|
|
473
|
+
"""
|
|
474
|
+
root_name = self._job_root_name(job)
|
|
475
|
+
base = self.roots[root_name]["path"]
|
|
476
|
+
|
|
477
|
+
changed = []
|
|
478
|
+
alive = set()
|
|
479
|
+
seen = 0
|
|
480
|
+
for dirpath, dirnames, filenames in os.walk(base):
|
|
481
|
+
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
|
482
|
+
for name in filenames:
|
|
483
|
+
seen += 1
|
|
484
|
+
if seen > max_files:
|
|
485
|
+
return sorted(changed), sorted(set(baseline) - alive)
|
|
486
|
+
full = os.path.join(dirpath, name)
|
|
487
|
+
try:
|
|
488
|
+
st = os.stat(full)
|
|
489
|
+
except OSError:
|
|
490
|
+
continue
|
|
491
|
+
rel = os.path.relpath(full, base).replace(os.sep, "/")
|
|
492
|
+
alive.add(rel)
|
|
493
|
+
if baseline.get(rel) != (st.st_mtime_ns, st.st_size):
|
|
494
|
+
changed.append(rel)
|
|
495
|
+
# 删掉的文件也算改动 —— 不然越界删除就成了隐形操作
|
|
496
|
+
return sorted(changed), sorted(set(baseline) - alive)
|
|
497
|
+
|
|
498
|
+
def _run_cmd(self, job, timeout=1800.0):
|
|
499
|
+
"""跑 ``job.cmd``。
|
|
500
|
+
|
|
501
|
+
提示词通过**环境变量和 stdin** 传入,不做字符串拼接 —— 避免提示词里
|
|
502
|
+
的内容被当成 shell 语法执行。
|
|
503
|
+
"""
|
|
504
|
+
root_name = self._job_root_name(job)
|
|
505
|
+
cwd = self.roots[root_name]["path"]
|
|
506
|
+
env = dict(os.environ)
|
|
507
|
+
env.update({
|
|
508
|
+
"MESH_JOB_ID": job.id,
|
|
509
|
+
"MESH_PROJECT": job.project,
|
|
510
|
+
"MESH_PROMPT": job.prompt,
|
|
511
|
+
"MESH_FEEDBACK": job.feedback,
|
|
512
|
+
"MESH_READ": ",".join(job.read),
|
|
513
|
+
"MESH_WRITE": ",".join(job.write),
|
|
514
|
+
"MESH_ROOT": cwd,
|
|
515
|
+
})
|
|
516
|
+
try:
|
|
517
|
+
proc = subprocess.run(
|
|
518
|
+
job.cmd, shell=True, cwd=cwd, env=env,
|
|
519
|
+
input=(job.prompt or "").encode("utf-8"),
|
|
520
|
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
|
|
521
|
+
except subprocess.TimeoutExpired:
|
|
522
|
+
raise AgentError("作业超时(%.0fs)" % timeout)
|
|
523
|
+
return {
|
|
524
|
+
"rc": proc.returncode,
|
|
525
|
+
"stdout": proc.stdout[:MAX_EXEC_OUT].decode("utf-8", "replace"),
|
|
526
|
+
"stderr": proc.stderr[:MAX_EXEC_OUT].decode("utf-8", "replace"),
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
# ------------------------------------------------------------------
|
|
530
|
+
# 回滚
|
|
531
|
+
# ------------------------------------------------------------------
|
|
532
|
+
def _backup(self, job, files, dirs):
|
|
533
|
+
"""把 root 里的文件备份到临时目录。返回 ``(备份, 跳过原因)``。
|
|
534
|
+
|
|
535
|
+
只备份自己声明的 root 之内、跳过 .git 之类的目录。超出条数/字节上限
|
|
536
|
+
就不备份 —— 宁可明确说"这次只检测不撤销",也不要为了备份把机器拖死。
|
|
537
|
+
"""
|
|
538
|
+
if not self.rollback:
|
|
539
|
+
return None, "未开启回滚(--no-rollback)"
|
|
540
|
+
total = sum(size for _mtime, size in files.values())
|
|
541
|
+
if len(files) > self.backup_max_files:
|
|
542
|
+
return None, ("文件太多(%d > %d),只检测不备份"
|
|
543
|
+
% (len(files), self.backup_max_files))
|
|
544
|
+
if total > self.backup_max_bytes:
|
|
545
|
+
return None, ("备份体积太大(%d > %d 字节),只检测不备份"
|
|
546
|
+
% (total, self.backup_max_bytes))
|
|
547
|
+
|
|
548
|
+
root_name = self._job_root_name(job)
|
|
549
|
+
base = self.roots[root_name]["path"]
|
|
550
|
+
store = tempfile.mkdtemp(prefix="mesh-backup-")
|
|
551
|
+
try:
|
|
552
|
+
for rel in files:
|
|
553
|
+
src = os.path.join(base, *rel.split("/"))
|
|
554
|
+
dst = os.path.join(store, "files", *rel.split("/"))
|
|
555
|
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
|
556
|
+
shutil.copy2(src, dst) # copy2 保留 mtime,还原后才能跟基线对上
|
|
557
|
+
except OSError:
|
|
558
|
+
shutil.rmtree(store, ignore_errors=True)
|
|
559
|
+
raise
|
|
560
|
+
return {"dir": store, "files": set(files), "dirs": set(dirs)}, ""
|
|
561
|
+
|
|
562
|
+
@staticmethod
|
|
563
|
+
def _drop_backup(backup):
|
|
564
|
+
if backup:
|
|
565
|
+
shutil.rmtree(backup["dir"], ignore_errors=True)
|
|
566
|
+
|
|
567
|
+
def _restore(self, job, backup, changed, deleted):
|
|
568
|
+
"""把越界的改动抹掉:改动过的还原,新建的删掉,删掉的写回去。"""
|
|
569
|
+
root_name = self._job_root_name(job)
|
|
570
|
+
base = self.roots[root_name]["path"]
|
|
571
|
+
store = os.path.join(backup["dir"], "files")
|
|
572
|
+
restored, removed, failed = [], [], []
|
|
573
|
+
|
|
574
|
+
def put_back(rel):
|
|
575
|
+
src = os.path.join(store, *rel.split("/"))
|
|
576
|
+
dst = os.path.join(base, *rel.split("/"))
|
|
577
|
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
|
578
|
+
shutil.copy2(src, dst)
|
|
579
|
+
|
|
580
|
+
for rel in list(changed) + list(deleted):
|
|
581
|
+
had_backup = rel in backup["files"]
|
|
582
|
+
try:
|
|
583
|
+
if had_backup:
|
|
584
|
+
put_back(rel)
|
|
585
|
+
restored.append(rel)
|
|
586
|
+
else:
|
|
587
|
+
dst = os.path.join(base, *rel.split("/"))
|
|
588
|
+
if os.path.isfile(dst):
|
|
589
|
+
os.remove(dst) # 作业新建的文件
|
|
590
|
+
removed.append(rel)
|
|
591
|
+
except OSError as exc:
|
|
592
|
+
failed.append("%s:%s" % (rel, exc))
|
|
593
|
+
|
|
594
|
+
# 作业新建的空目录也清掉
|
|
595
|
+
pruned = []
|
|
596
|
+
try:
|
|
597
|
+
current = self._dirs(job)
|
|
598
|
+
for rel in sorted(current - backup["dirs"], key=len, reverse=True):
|
|
599
|
+
path = os.path.join(base, *rel.split("/"))
|
|
600
|
+
try:
|
|
601
|
+
os.rmdir(path) # 非空会抛,正好跳过
|
|
602
|
+
pruned.append(rel)
|
|
603
|
+
except OSError:
|
|
604
|
+
pass
|
|
605
|
+
except OSError:
|
|
606
|
+
pass
|
|
607
|
+
|
|
608
|
+
return {"restored": restored, "removed": removed,
|
|
609
|
+
"deleted_back": [r for r in deleted if r in backup["files"]],
|
|
610
|
+
"pruned_dirs": pruned, "failed": failed}
|
|
611
|
+
|
|
612
|
+
def op_job(self, payload):
|
|
613
|
+
"""跑一条作业,落盘后强制校验写作用域,越界就回滚。"""
|
|
614
|
+
job = queue.Job.from_dict(payload.get("job") or {})
|
|
615
|
+
if not self.acquire_slot():
|
|
616
|
+
raise AgentError("槽位已满(%d/%d)" % (self.slots_used, self.slots_total))
|
|
617
|
+
baseline = self._snapshot(job)
|
|
618
|
+
backup, skip_reason = None, ""
|
|
619
|
+
try:
|
|
620
|
+
backup, skip_reason = self._backup(job, baseline, self._dirs(job))
|
|
621
|
+
except OSError as exc:
|
|
622
|
+
skip_reason = "备份失败:%s" % exc
|
|
623
|
+
|
|
624
|
+
try:
|
|
625
|
+
if self.runner is not None:
|
|
626
|
+
out = self.runner(job) or {}
|
|
627
|
+
elif job.cmd:
|
|
628
|
+
out = self._run_cmd(job, timeout=float(payload.get("timeout") or 1800))
|
|
629
|
+
else:
|
|
630
|
+
raise AgentError("作业既没有 cmd,节点也没有配置 runner")
|
|
631
|
+
if not isinstance(out, dict):
|
|
632
|
+
raise AgentError("runner 必须返回字典(收到 %s)" % type(out).__name__)
|
|
633
|
+
|
|
634
|
+
changed, deleted = self._changed_since(job, baseline)
|
|
635
|
+
# 删掉作用域外的文件同样是越界,别只盯写入
|
|
636
|
+
violations = task.check_scope(job, list(changed) + list(deleted))
|
|
637
|
+
|
|
638
|
+
out = dict(out)
|
|
639
|
+
out["changed"] = changed
|
|
640
|
+
out["deleted"] = deleted
|
|
641
|
+
out["violations"] = violations
|
|
642
|
+
# runner 自己报的 ok 优先:自定义执行器完全可以不用 rc 表达失败
|
|
643
|
+
# (比如大模型回复"这题我做不了"),一律按 rc==0 判成功会把
|
|
644
|
+
# 失败静默成一个绿色的作业。
|
|
645
|
+
verdict = out.get("ok")
|
|
646
|
+
if verdict is None:
|
|
647
|
+
verdict = out.get("rc", 0) == 0
|
|
648
|
+
out["ok"] = bool(verdict) and not violations
|
|
649
|
+
|
|
650
|
+
if violations:
|
|
651
|
+
rollback = {"restored": [], "removed": [], "failed": [],
|
|
652
|
+
"skipped": skip_reason}
|
|
653
|
+
if backup is not None:
|
|
654
|
+
rollback = self._restore(job, backup, changed, deleted)
|
|
655
|
+
# 复核一遍:还原之后理论上应该回到基线
|
|
656
|
+
after_changed, after_deleted = self._changed_since(job, baseline)
|
|
657
|
+
rollback["clean"] = not after_changed and not after_deleted
|
|
658
|
+
rollback["skipped"] = ""
|
|
659
|
+
if not rollback["clean"]:
|
|
660
|
+
rollback["leftover"] = after_changed + after_deleted
|
|
661
|
+
out["rollback"] = rollback
|
|
662
|
+
out["error"] = ("越界改动 %d 个文件(作用域 %s):%s%s"
|
|
663
|
+
% (len(violations), job.write,
|
|
664
|
+
", ".join(violations[:10]),
|
|
665
|
+
(";已回滚" if rollback.get("clean")
|
|
666
|
+
else ";未能完全回滚")))
|
|
667
|
+
return out
|
|
668
|
+
finally:
|
|
669
|
+
self._drop_backup(backup)
|
|
670
|
+
self.release_slot()
|
|
671
|
+
|
|
672
|
+
# ------------------------------------------------------------------
|
|
673
|
+
# 服务装配
|
|
674
|
+
# ------------------------------------------------------------------
|
|
675
|
+
def build_server(self, host="127.0.0.1", port=0, tls=None):
|
|
676
|
+
srv = wire.Server(host=host, port=port, token=self.token,
|
|
677
|
+
node_id=self.node_id, tls=tls)
|
|
678
|
+
srv.add("cap", lambda payload: self.capability().to_dict())
|
|
679
|
+
srv.add("ls", self.op_ls)
|
|
680
|
+
srv.add("stat", self.op_stat)
|
|
681
|
+
srv.add("read", self.op_read)
|
|
682
|
+
srv.add("write", self.op_write)
|
|
683
|
+
srv.add("rm", self.op_rm)
|
|
684
|
+
srv.add("sig", self.op_sig)
|
|
685
|
+
srv.add("delta", self.op_delta)
|
|
686
|
+
srv.add("patch", self.op_patch)
|
|
687
|
+
srv.add("exec", self.op_exec)
|
|
688
|
+
srv.add("job", self.op_job)
|
|
689
|
+
return srv
|
|
690
|
+
|
|
691
|
+
def __repr__(self):
|
|
692
|
+
return "Node(%s, roots=%s, slots=%d/%d)" % (
|
|
693
|
+
self.node_id, ",".join(sorted(self.roots)) or "-",
|
|
694
|
+
self.slots_used, self.slots_total)
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def serve(node, host="127.0.0.1", port=8765, tls=None):
|
|
698
|
+
"""起一个节点服务并阻塞。返回 Server(已启动)。"""
|
|
699
|
+
srv = node.build_server(host=host, port=port, tls=tls)
|
|
700
|
+
srv.start()
|
|
701
|
+
return srv
|