pystepmap 0.1.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.
@@ -0,0 +1,673 @@
1
+ """运行项目的测试:在被测项目的根目录里用 /bin/sh -c 执行用户填的测试命令,挂上记录插件(core 的 pystepmap.trace,
2
+ 改名成 pystepmap_trace_plugin 放在数据目录里),
3
+ 命令结束(或超时、被取消)后把它起的整个进程组都结束掉。
4
+
5
+ 这是平台里唯一会执行被测项目代码的地方,和分析(worker.py)是两条分开的路:
6
+ - 分析:python -E -P -m pystepmap_server.worker,当前目录是平台数据目录,只读源码,不导入、不执行项目代码;
7
+ 分析、约束检查、MCP 的工具都只走那一条。
8
+ - 运行测试:用户自己填的命令,当前目录是项目根目录,按设计会执行项目代码(测试本身就是项目代码)。只有平台接口
9
+ POST /api/projects/{id}/runs(本机页面上点"运行测试",第一次运行一条命令前要确认)经 flows.run_project_tests
10
+ 走到这里;MCP 没有任何能启动、取消或配置测试运行的工具。
11
+
12
+ run_tests:命令自成一个会话和进程组(start_new_session),标准输入是空设备,标准输出和标准错误合在一起,只在内存里
13
+ 留最后 TAIL_LINES 行(每行最多 LINE_CHARS 字)——pytest 的输出里有断言展开的取值,不写进库、不写文件,服务重启即丢。
14
+ 环境变量在继承的基础上(先去掉平台服务自己的虚拟环境:指着它的 VIRTUAL_ENV、UV_PROJECT_ENVIRONMENT,PATH 里它的
15
+ bin,uv run 的运行期变量——测试命令要在用户自己的环境里找 python、pytest;这个虚拟环境就在被测项目里面时它就是项目
16
+ 的解释器,留着;见 _without_own_venv)加:
17
+ PYSTEPMAP_GRAPH、PYSTEPMAP_TRACE_OUT(插件读的图、写的记录)、PYTHONPATH=插件目录(接在原有的
18
+ 前面)、PYTEST_ADDOPTS=原有的 + " -p pystepmap_trace_plugin -p no:cacheprovider"(挂插件;不在项目里写 .pytest_cache)、
19
+ PYTHONDONTWRITEBYTECODE=1(不在项目里写 .pyc);只跑一条功能线的测试时再加 PYSTEPMAP_ONLY_TESTS=名单文件(命令本身不改)。
20
+ 结束进程组:超时(PYSTEPMAP_TEST_TIMEOUT 秒,默认 1800)或 cancel 置位(用户取消、服务退出)时先 SIGINT 整个进程组
21
+ (pytest 当作 Ctrl+C,照常跑 fixture 的收尾),最多等 INT_GRACE 秒;同时如果首进程还是 sh(几条命令的脚本),单给它
22
+ SIGTERM,免得 pytest 结束后它接着跑下一条命令;再 SIGTERM 整个进程组,KILL_GRACE 秒后还有剩下的 SIGKILL。
23
+ 命令自己正常结束时,进程组里剩下的后台进程(测试起的服务等,可能还拿着输出管道)也照样结束(SIGTERM 起),不等它们。
24
+ 管不到的:测试自己另开会话起的进程(setsid、start_new_session=True、守护进程化的服务)不在这个进程组里,结束进程组
25
+ 碰不到它们,看门狗也碰不到——它们会一直跑,要测试自己收拾。它们拿着输出管道时,读输出的线程最多等 READER_GRACE 秒
26
+ 就关掉我们这一端(不会一直挂着),之后它们往输出里写会收到 SIGPIPE / EPIPE。
27
+ 看门狗:每次运行另起一个小进程(python -I,自成会话,不受终端的 Ctrl+C 影响),它一直读一个管道,写端在平台服务手里。
28
+ 正常结束时服务往管道里写一个字节,看门狗随即退出;服务被强杀(SIGKILL、崩溃)时管道读到结尾,看门狗就结束测试的进程组
29
+ (同样先 SIGTERM,3 秒后 SIGKILL),再删掉这次运行的临时目录(只认 <数据目录>/runs/tmp-…)。服务下次启动时也会删掉
30
+ runs 下所有留下来的 tmp-… 目录(clean_leftovers;同一个数据目录只能开一个 pystepmap serve,所以这时不会有别的运行)。
31
+ 服务正常退出(Ctrl+C、SIGTERM)时,app 的收尾调用 stop_all:取消这个数据目录的全部运行并等它们记下"已取消"。
32
+
33
+ 插件目录(write_plugin_dir):<数据目录>/plugin/pystepmap_trace_plugin.py——core 的 trace.py 原样复制、改了名字的一个
34
+ 顶层模块,内容变了才重写。命令里的 python 按 PYTHONPATH 找到这一份,和服务端读记录的代码是同一个版本。不用 pystepmap 这个
35
+ 包名:被测项目自己有 pystepmap 包时(pystepmap 仓库自己)会被挡住。插件按文件的真实路径认出自己(_SELF),副本在数据目录
36
+ 里、不在任何项目的图里,所以不记录自己;被测项目自己的 trace.py(pystepmap 仓库里那份)是普通的项目代码,照常只记一次。
37
+
38
+ 进程内的运行表(launch / announce / set_phase / running / cancel_run / stop_all):每个(数据目录,项目)同时最多一次
39
+ 运行;记着取消用的事件、当前阶段(preparing 拿到锁、检查图是否过期、准备临时文件 → analyzing 只在图过期、运行前重新
40
+ 分析时 → testing 跑测试命令 → processing 读记录、核对、汇总、保存)和开始时间。最近一次运行的输出末尾(last_output)、最近一次没能存下运行记录的失败(last_failure:运行前的
41
+ 分析失败、保存失败等,接口在 POST 返回 202 之后靠它告诉界面发生了什么)也只在这里,不入库。测试命令跑着时的进度
42
+ (live.LiveRun,set_live / live)也挂在运行表上:testflows 在测试命令开始前挂上、结束后取下,live 只在阶段 testing 时
43
+ 给出;这里不导入 live(它只是一个对象)。
44
+ 这里不是流程代码,不加 pystepkit 标记。
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import contextlib
50
+ import importlib.util
51
+ import logging
52
+ import math
53
+ import os
54
+ import secrets
55
+ import select
56
+ import shutil
57
+ import signal
58
+ import subprocess
59
+ import sys
60
+ import threading
61
+ import time
62
+ from collections import deque
63
+ from collections.abc import Callable
64
+ from dataclasses import dataclass, field
65
+ from datetime import UTC, datetime
66
+ from pathlib import Path
67
+ from typing import Literal
68
+
69
+ from .store import private_dir, private_file
70
+
71
+ logger = logging.getLogger(__name__)
72
+
73
+ TIMEOUT_ENV = "PYSTEPMAP_TEST_TIMEOUT"
74
+ DEFAULT_TIMEOUT = 1800.0
75
+ TAIL_LINES = 200 # 输出只留最后几行
76
+ LINE_CHARS = 2000 # 每行最多几个字(更长的截断)
77
+ INT_GRACE = 5.0 # 超时、取消时先 SIGINT(pytest 照常收尾),等几秒再 SIGTERM
78
+ KILL_GRACE = 3.0 # SIGTERM 之后等几秒再 SIGKILL
79
+ KILL_WAIT = 2.0 # SIGKILL 之后最多再等几秒让进程组消失
80
+ READER_GRACE = 2.0 # 进程组结束之后最多等几秒把输出读完
81
+ WATCHDOG_WAIT = 5.0
82
+ START_WAIT = 30.0 # launch 最多等几秒让流程走到"标记正在忙"
83
+ PLUGIN_DIR = "plugin"
84
+ RUNS_DIR = "runs"
85
+ SCRATCH_PREFIX = "tmp-"
86
+ PLUGIN_MODULE = "pystepmap_trace_plugin" # 插件目录里 core 的 trace.py 改名后的模块名
87
+ PYTEST_PLUGIN_OPTIONS = f"-p {PLUGIN_MODULE} -p no:cacheprovider"
88
+ PHASES = ("preparing", "analyzing", "testing", "processing")
89
+ CANCELLED_BEFORE_START = "运行在开始之前就被取消了"
90
+
91
+ _READ_CHUNK = 8192 # 每次最多读几个字节(一行更长时只留第一段)
92
+ _POLL = 0.05
93
+
94
+ # 看门狗:平台服务被强杀时结束测试的进程组、删掉这次运行的临时目录。只用标准库,用 python -I 跑。
95
+ _WATCHDOG = r"""
96
+ import os, shutil, signal, sys, time
97
+ pgid, scratch = int(sys.argv[1]), sys.argv[2]
98
+ try:
99
+ told = sys.stdin.buffer.read(1)
100
+ except (OSError, KeyboardInterrupt):
101
+ told = b""
102
+ if told == b"d":
103
+ sys.exit(0)
104
+
105
+ def alive():
106
+ try:
107
+ os.killpg(pgid, 0)
108
+ except (ProcessLookupError, PermissionError):
109
+ return False
110
+ return True
111
+
112
+ def signal_group(sig):
113
+ try:
114
+ os.killpg(pgid, sig)
115
+ except (ProcessLookupError, PermissionError):
116
+ pass
117
+
118
+ if alive():
119
+ signal_group(signal.SIGTERM)
120
+ deadline = time.monotonic() + 3
121
+ while alive() and time.monotonic() < deadline:
122
+ time.sleep(0.05)
123
+ if alive():
124
+ signal_group(signal.SIGKILL)
125
+ if scratch and os.path.basename(scratch).startswith("tmp-") and os.path.basename(os.path.dirname(scratch)) == "runs":
126
+ shutil.rmtree(scratch, ignore_errors=True)
127
+ """
128
+
129
+
130
+ @dataclass
131
+ class RunResult:
132
+ status: Literal["finished", "timeout", "cancelled", "failed_to_start"]
133
+ exit_code: int | None # 命令(/bin/sh)的退出码;被信号结束时为负数;没跑完时 None
134
+ seconds: float
135
+ tail: list[str] # 输出的最后 TAIL_LINES 行,只留在内存里
136
+ reason: str = "" # 中文说明(超时、取消、没能启动时)
137
+
138
+
139
+ def run_timeout() -> float:
140
+ """测试命令的超时秒数:环境变量 PYSTEPMAP_TEST_TIMEOUT(可以带小数),没有或不是正的有限数时 1800。每次调用时读。"""
141
+ text = os.environ.get(TIMEOUT_ENV)
142
+ if text is None:
143
+ return DEFAULT_TIMEOUT
144
+ try:
145
+ value = float(text)
146
+ except ValueError:
147
+ value = math.nan
148
+ if not (math.isfinite(value) and value > 0):
149
+ logger.warning("环境变量 %s 的值 %r 不是正数秒数,按 %g 秒", TIMEOUT_ENV, text, DEFAULT_TIMEOUT)
150
+ return DEFAULT_TIMEOUT
151
+ return value
152
+
153
+
154
+ # ---------- 插件目录、临时目录 ----------
155
+
156
+ def _trace_source() -> bytes:
157
+ spec = importlib.util.find_spec("pystepmap.trace")
158
+ if spec is None or spec.origin is None:
159
+ raise OSError("找不到 pystepmap.trace(core 没有装好)")
160
+ return Path(spec.origin).read_bytes()
161
+
162
+
163
+ def _write_if_changed(path: Path, data: bytes) -> None:
164
+ """内容和权限都对时不动;否则写到同目录的临时文件再改名(正在跑的测试读到的总是完整的文件)。"""
165
+ try:
166
+ if path.read_bytes() == data and (os.name != "posix" or (path.stat().st_mode & 0o777) == 0o600):
167
+ return
168
+ except OSError:
169
+ pass
170
+ tmp = path.with_name(f".tmp-{secrets.token_hex(4)}-{path.name}")
171
+ try:
172
+ private_file(tmp)
173
+ tmp.write_bytes(data)
174
+ os.replace(tmp, path)
175
+ except BaseException:
176
+ tmp.unlink(missing_ok=True)
177
+ raise
178
+
179
+
180
+ def write_plugin_dir(home: Path) -> Path:
181
+ """<数据目录>/plugin/pystepmap_trace_plugin.py:core 的 trace.py 原样复制、改个名字(它只用标准库、不导入 pystepmap 的
182
+ 其他模块,改名照样能用)。目录 0700、文件 0600;内容变了才重写。以前的代码放的 plugin/pystepmap/ 包删掉。返回
183
+ <数据目录>/plugin(放进 PYTHONPATH 的那一级)。写不了时抛 OSError。"""
184
+ base = Path(home) / PLUGIN_DIR
185
+ private_dir(Path(home))
186
+ private_dir(base)
187
+ old = base / "pystepmap" # 以前是一个叫 pystepmap 的包:会挡住被测项目自己的 pystepmap 包
188
+ if old.is_symlink() or old.is_file():
189
+ old.unlink()
190
+ elif old.is_dir():
191
+ shutil.rmtree(old)
192
+ _write_if_changed(base / f"{PLUGIN_MODULE}.py", _trace_source())
193
+ for extra in base.iterdir(): # 以前中途失败留下的临时文件
194
+ if extra.name.startswith(".tmp-"):
195
+ extra.unlink(missing_ok=True)
196
+ return base
197
+
198
+
199
+ def make_scratch(home: Path) -> Path:
200
+ """这次运行的临时目录 <数据目录>/runs/tmp-<随机>(0700):图的副本、记录文件放在这里。写不了时抛 OSError。"""
201
+ runs = Path(home) / RUNS_DIR
202
+ private_dir(Path(home))
203
+ private_dir(runs)
204
+ path = runs / f"{SCRATCH_PREFIX}{secrets.token_hex(6)}"
205
+ path.mkdir(mode=0o700)
206
+ if os.name == "posix":
207
+ path.chmod(0o700)
208
+ return path
209
+
210
+
211
+ def remove_scratch(path: Path | None) -> None:
212
+ """删掉这次运行的临时目录(可以重复调用,不存在时什么都不做)。"""
213
+ if path is not None:
214
+ shutil.rmtree(path, ignore_errors=True)
215
+
216
+
217
+ def clean_leftovers(home: Path) -> None:
218
+ """删掉 <数据目录>/runs 下所有 tmp-… 目录:上次服务被强杀、看门狗也没来得及删的。只在服务启动时调用。"""
219
+ runs = Path(home) / RUNS_DIR
220
+ try:
221
+ found = [p for p in runs.iterdir() if p.name.startswith(SCRATCH_PREFIX)]
222
+ except OSError:
223
+ return
224
+ for p in found:
225
+ shutil.rmtree(p, ignore_errors=True)
226
+
227
+
228
+ # ---------- 运行一条命令 ----------
229
+
230
+ def _same_path(a: str | None, b: str) -> bool:
231
+ return bool(a) and os.path.isabs(a) and os.path.realpath(a) == b
232
+
233
+
234
+ def _inside_dir(path: str, root: str) -> bool:
235
+ return path == root or path.startswith(root.rstrip(os.sep) + os.sep)
236
+
237
+
238
+ def _without_own_venv(env: dict[str, str], root: str) -> dict[str, str]:
239
+ """去掉平台服务自己的虚拟环境(uv run pystepmap serve、或激活了 pystepmap 的 .venv 时带进来的):指着它的
240
+ VIRTUAL_ENV(连同 VIRTUAL_ENV_PROMPT)和 UV_PROJECT_ENVIRONMENT、PATH 里它的 bin 那一项(只去这一项),以及 uv run
241
+ 的运行期变量(UV_RUN_RECURSION_DEPTH 和随它设的 UV、UV_INTERNAL__ 开头的)。别的照留。服务不在虚拟环境里跑时
242
+ (sys.prefix 就是基础解释器)不碰 VIRTUAL_ENV 和 PATH;这个虚拟环境就在被测项目里面时(pystepmap 装在项目自己的
243
+ venv 里,比如在 pystepmap 仓库自己里跑它的测试)也不碰——那就是项目的解释器。uv run 的运行期变量总是去掉(它们只属于
244
+ 启动服务的那一次 uv run)。"""
245
+ env = dict(env)
246
+ own = os.path.realpath(sys.prefix)
247
+ if sys.prefix != sys.base_prefix and not _inside_dir(own, os.path.realpath(root)):
248
+ if _same_path(env.get("VIRTUAL_ENV"), own):
249
+ env.pop("VIRTUAL_ENV")
250
+ env.pop("VIRTUAL_ENV_PROMPT", None)
251
+ if _same_path(env.get("UV_PROJECT_ENVIRONMENT"), own):
252
+ env.pop("UV_PROJECT_ENVIRONMENT")
253
+ own_bin = os.path.join(own, "Scripts" if os.name == "nt" else "bin")
254
+ if "PATH" in env:
255
+ env["PATH"] = os.pathsep.join(p for p in env["PATH"].split(os.pathsep) if not _same_path(p, own_bin))
256
+ if env.pop("UV_RUN_RECURSION_DEPTH", None) is not None: # 在 uv run 里:UV 是它设的
257
+ env.pop("UV", None)
258
+ for name in [k for k in env if k.startswith("UV_INTERNAL__")]:
259
+ env.pop(name)
260
+ return env
261
+
262
+
263
+ def _environment(root: str, graph_path: Path, trace_path: Path, plugin_dir: Path,
264
+ only_path: Path | None = None) -> dict[str, str]:
265
+ env = _without_own_venv(dict(os.environ), root)
266
+ env["PYSTEPMAP_GRAPH"] = str(graph_path)
267
+ env["PYSTEPMAP_TRACE_OUT"] = str(trace_path)
268
+ env.pop("PYSTEPMAP_ONLY_TESTS", None) # 继承来的不算:只跑哪些测试由这次运行自己定
269
+ if only_path is not None:
270
+ env["PYSTEPMAP_ONLY_TESTS"] = str(only_path)
271
+ old_path = env.get("PYTHONPATH", "")
272
+ env["PYTHONPATH"] = str(plugin_dir) + (os.pathsep + old_path if old_path else "")
273
+ old_opts = env.get("PYTEST_ADDOPTS", "")
274
+ env["PYTEST_ADDOPTS"] = (old_opts + " " if old_opts.strip() else "") + PYTEST_PLUGIN_OPTIONS
275
+ env["PYTHONDONTWRITEBYTECODE"] = "1"
276
+ return env
277
+
278
+
279
+ def _pump(fd: int, tail: deque, stop: threading.Event) -> None:
280
+ """把输出逐行放进 tail(只留最后 TAIL_LINES 行)。每读到一块只从后往前找这一块里最后 TAIL_LINES 行(前面的反正会被
281
+ 挤掉:输出刷屏时花的时间和一块里有多少行无关,也不和接口抢太多 GIL),手里最多留一段不到 _READ_CHUNK 字节的半行。很长的行只留
282
+ 第一段(截到 LINE_CHARS 字),后面的部分丢掉。用 select 等数据、每 0.1 秒看一次 stop:管道的写端被一个逃出进程组
283
+ 的进程拿着时(读不到结尾),run_tests 置位 stop 就能让这个线程结束,再关掉我们这一端。"""
284
+ rest = b"" # 还没遇到换行的半行(最多 _READ_CHUNK 字节)
285
+ skipping = False # 正在丢一行太长的后半截
286
+
287
+ def emit(raw: bytes) -> None:
288
+ tail.append(raw[:LINE_CHARS * 4].decode("utf-8", "replace").rstrip("\r")[:LINE_CHARS])
289
+
290
+ try:
291
+ while not stop.is_set():
292
+ ready, _, _ = select.select([fd], [], [], _POLL * 2)
293
+ if not ready:
294
+ continue
295
+ chunk = os.read(fd, 65536)
296
+ if not chunk:
297
+ break
298
+ data = rest + chunk
299
+ end = data.rfind(b"\n")
300
+ if end >= 0:
301
+ rest = data[end + 1:] # 最后一段没有换行
302
+ lines: list[bytes] = []
303
+ while len(lines) < TAIL_LINES: # 从后往前只找最后 TAIL_LINES 行:不切开整块
304
+ start = data.rfind(b"\n", 0, end) + 1
305
+ lines.append(data[start:end])
306
+ if start == 0:
307
+ if skipping: # 一直找到了开头:第一行是那行太长的结尾
308
+ lines.pop()
309
+ break
310
+ end = start - 1
311
+ skipping = False # 见到了换行:太长的那一行结束了
312
+ for line in reversed(lines):
313
+ emit(line)
314
+ else:
315
+ rest = data
316
+ if len(rest) > _READ_CHUNK:
317
+ if not skipping:
318
+ emit(rest)
319
+ skipping = True
320
+ rest = b""
321
+ if rest and not skipping:
322
+ emit(rest)
323
+ except (OSError, ValueError): # 管道出了问题:输出就到这里
324
+ pass
325
+
326
+
327
+ def _group_alive(pgid: int) -> bool:
328
+ try:
329
+ os.killpg(pgid, 0)
330
+ except (ProcessLookupError, PermissionError): # 没了(编号被别人的进程组用了也说明我们的早没了)
331
+ return False
332
+ return True
333
+
334
+
335
+ def _signal_group(pgid: int, sig: int) -> None:
336
+ with contextlib.suppress(ProcessLookupError, PermissionError):
337
+ os.killpg(pgid, sig)
338
+
339
+
340
+ def _wait_group(proc: subprocess.Popen, pgid: int, seconds: float) -> bool:
341
+ """最多等 seconds 秒让进程组里一个进程都不剩(同时回收首进程)。"""
342
+ deadline = time.monotonic() + seconds
343
+ while True:
344
+ proc.poll()
345
+ if not _group_alive(pgid):
346
+ return True
347
+ if time.monotonic() >= deadline:
348
+ return False
349
+ time.sleep(0.02)
350
+
351
+
352
+ def _leader_is_shell(pid: int) -> bool:
353
+ """进程组的首进程现在还是我们起的 /bin/sh(命令是几条命令的脚本);只有一条命令时 sh 直接换成了那个程序(exec),
354
+ 就不是了。看不出来时当作不是(宁可让脚本多跑下一条,也不提前打断 pytest 的收尾)。"""
355
+ try:
356
+ name = subprocess.run(["ps", "-o", "comm=", "-p", str(pid)], capture_output=True, text=True, timeout=2,
357
+ check=False).stdout.strip()
358
+ except (OSError, subprocess.SubprocessError):
359
+ return False
360
+ return os.path.basename(name) in ("sh", "bash", "dash", "zsh", "ksh")
361
+
362
+
363
+ def _end_group(proc: subprocess.Popen, pgid: int, *, interrupt: bool) -> None:
364
+ """结束整个进程组;首进程总是被回收。interrupt(超时、取消、服务退出)时先 SIGINT——pytest 当作 Ctrl+C,照常跑
365
+ fixture 的收尾——最多等 INT_GRACE 秒;同时首进程如果还是 sh(命令是几条命令的脚本),单给它 SIGTERM:pytest 被打断
366
+ 以退出码 2 结束后,sh 不会接着跑下一条命令。然后(命令自己正常结束、只剩后台进程时直接从这里开始)SIGTERM 整个
367
+ 进程组,KILL_GRACE 秒后还有剩下的 SIGKILL。注意:sh 的后台进程(&)不理 SIGINT,要等到 SIGTERM。"""
368
+ proc.poll()
369
+ if not _group_alive(pgid):
370
+ proc.wait()
371
+ return
372
+ if interrupt:
373
+ if proc.poll() is None and _leader_is_shell(proc.pid):
374
+ with contextlib.suppress(ProcessLookupError, PermissionError):
375
+ os.kill(proc.pid, signal.SIGTERM) # 先停住脚本:之后的命令不再开始
376
+ _signal_group(pgid, signal.SIGINT)
377
+ if _wait_group(proc, pgid, INT_GRACE):
378
+ proc.wait()
379
+ return
380
+ _signal_group(pgid, signal.SIGTERM)
381
+ if not _wait_group(proc, pgid, KILL_GRACE):
382
+ _signal_group(pgid, signal.SIGKILL)
383
+ _wait_group(proc, pgid, KILL_WAIT)
384
+ proc.wait()
385
+
386
+
387
+ def _start_watchdog(pgid: int, scratch: Path | None) -> subprocess.Popen | None:
388
+ try:
389
+ return subprocess.Popen([sys.executable, "-I", "-c", _WATCHDOG, str(pgid), str(scratch or "")],
390
+ stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
391
+ start_new_session=True)
392
+ except OSError as e: # 起不来就不要看门狗:服务被强杀时测试进程会留下,记一条警告
393
+ logger.warning("没能启动测试运行的看门狗进程(%s),服务被强杀时测试进程不会被结束", e.strerror or e)
394
+ return None
395
+
396
+
397
+ def _release_watchdog(watchdog: subprocess.Popen | None) -> None:
398
+ """告诉看门狗"正常结束了"(写一个字节),等它退出。"""
399
+ if watchdog is None:
400
+ return
401
+ with contextlib.suppress(OSError, ValueError):
402
+ watchdog.stdin.write(b"d")
403
+ with contextlib.suppress(OSError, ValueError):
404
+ watchdog.stdin.close()
405
+ try:
406
+ watchdog.wait(WATCHDOG_WAIT)
407
+ except subprocess.TimeoutExpired:
408
+ watchdog.kill()
409
+ watchdog.wait()
410
+
411
+
412
+ def _wait_for(proc: subprocess.Popen, cancel: threading.Event, deadline: float) -> str:
413
+ while True:
414
+ if proc.poll() is not None:
415
+ return "finished"
416
+ if cancel.is_set():
417
+ return "cancelled"
418
+ if time.monotonic() >= deadline:
419
+ return "timeout"
420
+ cancel.wait(_POLL)
421
+
422
+
423
+ def run_tests(root: str, command: str, *, graph_path: Path, trace_path: Path, plugin_dir: Path,
424
+ timeout: float, cancel: threading.Event, output: deque | None = None,
425
+ scratch: Path | None = None, only_path: Path | None = None) -> RunResult:
426
+ """在 root 里用 /bin/sh -c 执行 command(环境变量、进程组、超时、取消见模块说明),返回结果。从不抛 Exception:
427
+ 起不来时 status 为 failed_to_start。output 给出时(一个 deque)输出边跑边放进去(运行中看输出用);scratch 是这次
428
+ 运行的临时目录,服务被强杀时看门狗删掉它。cancel 在开始之前就置位时什么都不执行,直接 cancelled。only_path:
429
+ 只跑一条功能线的测试时,名单文件(JSON,测试 id 的列表)的路径——记录插件收集完测试后只留名单里的
430
+ (PYSTEPMAP_ONLY_TESTS,见 core 的 trace.pytest_collection_modifyitems;名单读不了时插件一个测试都不跑)。"""
431
+ tail: deque = output if output is not None else deque(maxlen=TAIL_LINES)
432
+ if cancel.is_set():
433
+ return RunResult("cancelled", None, 0.0, [], CANCELLED_BEFORE_START)
434
+ env = _environment(root, graph_path, trace_path, plugin_dir, only_path)
435
+ started = time.monotonic()
436
+ try:
437
+ proc = subprocess.Popen(["/bin/sh", "-c", command], cwd=root, env=env, stdin=subprocess.DEVNULL,
438
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, start_new_session=True)
439
+ except (OSError, ValueError) as e:
440
+ return RunResult("failed_to_start", None, 0.0, [], f"命令没能启动:{getattr(e, 'strerror', None) or e}")
441
+ pgid = proc.pid # 新会话的首进程:进程组号就是它的进程号
442
+ watchdog: subprocess.Popen | None = None
443
+ reader: threading.Thread | None = None
444
+ stop = threading.Event()
445
+ status, exit_code, seconds, problem = "", None, 0.0, None
446
+ try: # 看门狗、读输出的线程也在这里面起:起不来时进程组照样结束
447
+ watchdog = _start_watchdog(pgid, scratch)
448
+ reader = threading.Thread(target=_pump, args=(proc.stdout.fileno(), tail, stop), daemon=True,
449
+ name="pystepmap-test-output")
450
+ reader.start()
451
+ status = _wait_for(proc, cancel, started + timeout)
452
+ seconds = time.monotonic() - started
453
+ exit_code = proc.returncode if status == "finished" else None
454
+ except (RuntimeError, OSError, ValueError) as e: # 读输出的线程起不来(系统线程用完)等:当作没能启动
455
+ problem = e
456
+ finally: # 怎么结束的都一样:不留下进程。没跑完(超时、取消、出错、被打断)时先 SIGINT
457
+ _end_group(proc, pgid, interrupt=status != "finished")
458
+ _release_watchdog(watchdog)
459
+ if reader is not None and reader.is_alive():
460
+ reader.join(READER_GRACE) # 进程组没了:通常马上读到结尾
461
+ stop.set() # 还没完:写端在一个逃出进程组的进程手里,不等它
462
+ reader.join(1.0)
463
+ proc.stdout.close()
464
+ if problem is not None:
465
+ return RunResult("failed_to_start", None, round(time.monotonic() - started, 3), list(tail),
466
+ f"命令没能启动:没能开始读取命令的输出({type(problem).__name__})")
467
+ reason = {"timeout": f"测试运行超过 {timeout:g} 秒,已中止(可以用环境变量 {TIMEOUT_ENV} 调整秒数)",
468
+ "cancelled": "运行被取消了"}.get(status, "")
469
+ return RunResult(status, exit_code, round(seconds, 3), list(tail), reason)
470
+
471
+
472
+ # ---------- 进程内的运行表 ----------
473
+
474
+ @dataclass
475
+ class _Run:
476
+ cancel: threading.Event
477
+ started_at: str
478
+ started: float
479
+ phase: str = "preparing"
480
+ announced: bool = False # 流程已经走到"标记正在忙"
481
+ given_up: bool = False # launch 已经不等了(之后的失败要记下来)
482
+ result: dict | None = None
483
+ ready: threading.Event = field(default_factory=threading.Event)
484
+ thread: threading.Thread | None = None
485
+ cancelled_by: str | None = None # "user"(cancel_run)或 "shutdown"(stop_all)
486
+ forgotten: bool = False # 跑着的时候项目被删了(forget):结束时什么都不记
487
+ live: object | None = None # 测试命令跑着时的进度(live.LiveRun),testflows 挂上、取下
488
+ scope: dict | None = None # 只跑一条功能线的测试时 {"line", "line_title", "tests"};全部测试时 None
489
+
490
+
491
+ _lock = threading.Lock()
492
+ _runs: dict[tuple[str, str], _Run] = {}
493
+ _outputs: dict[tuple[str, str], deque | list] = {}
494
+ _failures: dict[tuple[str, str], dict] = {}
495
+
496
+
497
+ def _key(home: Path, project_id: str) -> tuple[str, str]:
498
+ return str(Path(home)), project_id
499
+
500
+
501
+ def _now() -> str:
502
+ return datetime.now(UTC).isoformat(timespec="seconds")
503
+
504
+
505
+ def _failure_of(result: dict | None) -> dict | None:
506
+ """流程的结局没存下运行记录(没有 run_id)时,给界面看的失败:{"title", "reason", "code", "at"}。"""
507
+ if result is None or result.get("kind") == "ok" or result.get("run_id") is not None:
508
+ return None
509
+ return {"title": result.get("title", ""), "reason": result.get("reason", ""), "code": result.get("code", ""),
510
+ "at": _now()}
511
+
512
+
513
+ def launch(home: Path, project_id: str, target: Callable[[threading.Event], dict], *,
514
+ wait: float = START_WAIT, scope: dict | None = None) -> dict | None:
515
+ """在后台线程里跑 target(cancel)(运行测试的流程)。等到流程宣布开始(announce:已经拿到项目的锁)就返回 None;
516
+ 流程在那之前就结束了(项目不存在、没填命令、正在分析……)时返回它的结局,由接口直接回给界面。本进程里这个项目
517
+ 已经有一次运行时返回 busy 的结局。流程之后的失败(没存下运行记录的)记在 last_failure 里。"""
518
+ key = _key(home, project_id)
519
+ run = _Run(threading.Event(), _now(), time.monotonic(), scope=scope)
520
+ with _lock:
521
+ if key in _runs:
522
+ return {"kind": "failed", "title": "正在运行测试", "reason": "这个项目正在运行测试,等它跑完或先取消",
523
+ "code": "busy"}
524
+ _runs[key] = run
525
+
526
+ def body() -> None:
527
+ result: dict | None = None
528
+ try:
529
+ result = target(run.cancel)
530
+ except BaseException as e: # 后台线程:不能让异常悄悄消失
531
+ logger.exception("运行项目 %s 的测试时出错", project_id)
532
+ result = {"kind": "failed", "title": "运行测试时内部出错", "reason": f"内部错误:{type(e).__name__}",
533
+ "code": "internal"}
534
+ finally:
535
+ with _lock:
536
+ run.result = result
537
+ _runs.pop(key, None)
538
+ if run.forgotten: # 项目删了:它的输出、失败都不留
539
+ _outputs.pop(key, None)
540
+ _failures.pop(key, None)
541
+ elif run.announced or run.given_up:
542
+ failure = _failure_of(result)
543
+ if failure is None:
544
+ _failures.pop(key, None)
545
+ else:
546
+ _failures[key] = failure
547
+ run.ready.set()
548
+
549
+ run.thread = threading.Thread(target=body, name=f"pystepmap-run-{project_id}", daemon=True)
550
+ run.thread.start()
551
+ run.ready.wait(wait)
552
+ with _lock:
553
+ if run.result is not None and not run.announced:
554
+ return run.result
555
+ run.given_up = True
556
+ return None
557
+
558
+
559
+ def announce(home: Path, project_id: str) -> None:
560
+ """流程已经拿到项目的锁:launch 可以返回了;之前记着的失败作废。不在运行表里(直接调用流程)时什么都不做。"""
561
+ key = _key(home, project_id)
562
+ with _lock:
563
+ run = _runs.get(key)
564
+ if run is None:
565
+ return
566
+ run.announced = True
567
+ run.phase = "preparing"
568
+ _failures.pop(key, None)
569
+ run.ready.set()
570
+
571
+
572
+ def set_phase(home: Path, project_id: str, phase: str) -> None:
573
+ with _lock:
574
+ run = _runs.get(_key(home, project_id))
575
+ if run is not None:
576
+ run.phase = phase
577
+
578
+
579
+ def set_live(home: Path, project_id: str, live: object | None) -> None:
580
+ """挂上(测试命令开始前)或取下(结束后,None)这次运行的进度。不在运行表里时什么都不做。"""
581
+ with _lock:
582
+ run = _runs.get(_key(home, project_id))
583
+ if run is not None:
584
+ run.live = live
585
+
586
+
587
+ def live(home: Path, project_id: str) -> object | None:
588
+ """正在跑测试命令(阶段 testing)的那次运行挂着的进度;别的时候 None。"""
589
+ with _lock:
590
+ run = _runs.get(_key(home, project_id))
591
+ if run is None or not run.announced or run.phase != "testing":
592
+ return None
593
+ return run.live
594
+
595
+
596
+ def running(home: Path, project_id: str) -> dict | None:
597
+ """本进程里这个项目正在进行的运行:{"started_at", "seconds", "phase", "scope"};没有时 None。scope:只跑一条
598
+ 功能线的测试时 {"line", "line_title", "tests"},全部测试时 None(launch 时给的)。"""
599
+ with _lock:
600
+ run = _runs.get(_key(home, project_id))
601
+ if run is None or not run.announced:
602
+ return None
603
+ return {"started_at": run.started_at, "seconds": round(time.monotonic() - run.started, 1), "phase": run.phase,
604
+ "scope": run.scope}
605
+
606
+
607
+ def cancel_run(home: Path, project_id: str) -> str | None:
608
+ """请求取消正在进行的运行,返回它此刻的阶段(没有在跑的:None)。testing 时结束测试命令;preparing、analyzing 时
609
+ 测试命令不再开始(analyzing:等运行前的分析做完就停);processing 时测试命令已经跑完,取消没有用——不置位,照常存完。"""
610
+ with _lock:
611
+ run = _runs.get(_key(home, project_id))
612
+ if run is None or not run.announced:
613
+ return None
614
+ if run.phase != "processing":
615
+ run.cancelled_by = run.cancelled_by or "user"
616
+ run.cancel.set()
617
+ return run.phase
618
+
619
+
620
+ def cancel_reason(home: Path, project_id: str) -> str | None:
621
+ """这次运行是谁取消的:"user"、"shutdown"(服务退出),没有取消时 None。"""
622
+ with _lock:
623
+ run = _runs.get(_key(home, project_id))
624
+ return None if run is None else run.cancelled_by
625
+
626
+
627
+ def stop_all(home: Path, wait: float = 20.0) -> None:
628
+ """服务退出时:取消这个数据目录的全部运行,最多等 wait 秒让它们结束进程组、记下"已取消"、放开锁。"""
629
+ prefix = str(Path(home))
630
+ with _lock:
631
+ runs = [r for (h, _), r in _runs.items() if h == prefix]
632
+ for r in runs:
633
+ r.cancelled_by = "shutdown"
634
+ r.cancel.set()
635
+ deadline = time.monotonic() + wait
636
+ for r in runs:
637
+ if r.thread is not None:
638
+ r.thread.join(max(0.0, deadline - time.monotonic()))
639
+
640
+
641
+ def keep_output(home: Path, project_id: str, lines: deque | list) -> None:
642
+ """记下这个项目最近一次运行的输出(可以是还在增长的 deque)。项目已经删了(forget)的运行不记。"""
643
+ key = _key(home, project_id)
644
+ with _lock:
645
+ run = _runs.get(key)
646
+ if run is None or not run.forgotten:
647
+ _outputs[key] = lines
648
+
649
+
650
+ def last_output(home: Path, project_id: str) -> list[str]:
651
+ """本进程里这个项目最近一次运行的输出末尾(运行中时是到现在为止的);没有时空表。"""
652
+ with _lock:
653
+ lines = _outputs.get(_key(home, project_id))
654
+ return [] if lines is None else list(lines)
655
+
656
+
657
+ def last_failure(home: Path, project_id: str) -> dict | None:
658
+ """本进程里这个项目最近一次没能存下运行记录的失败 {"title", "reason", "code", "at"};之后又开始了运行或存下了运行
659
+ 时清掉。"""
660
+ with _lock:
661
+ failure = _failures.get(_key(home, project_id))
662
+ return None if failure is None else dict(failure)
663
+
664
+
665
+ def forget(home: Path, project_id: str) -> None:
666
+ """项目删除了:丢掉它的输出和失败;还在跑的那次运行结束时也什么都不记。"""
667
+ key = _key(home, project_id)
668
+ with _lock:
669
+ _outputs.pop(key, None)
670
+ _failures.pop(key, None)
671
+ run = _runs.get(key)
672
+ if run is not None:
673
+ run.forgotten = True