process-probe.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import { afterEach, describe, expect, it, vi } from "vitest";
  2. import {
  3. createProcessProbe,
  4. PROCESS_PROBE_MAX_CONSECUTIVE_FAILURES,
  5. PROCESS_PROBE_SAMPLE_TIMEOUT_MS,
  6. } from "../src/device/process-probe.js";
  7. /** macOS `ps -eo pid=,ppid=,rss=,cputime=` 的典型输出:100 → 101 → 102 一棵树,200、300 各自独立。 */
  8. const DARWIN_PROCESS_TABLE = [
  9. " 100 1 50 0:01.00",
  10. " 101 100 25 0:00.50",
  11. " 102 101 10 1:02.25",
  12. " 200 1 30 0:00.00",
  13. " 300 1 15 10:00.00",
  14. ].join("\n");
  15. /** `/proc/<pid>/stat` 前 15 个字段:comm 允许含空格与括号,解析必须以最后一个 `)` 为界。 */
  16. function linuxStatLine(input: {
  17. pid: number;
  18. parentPid: number;
  19. processGroupId: number;
  20. utimeTicks: number;
  21. stimeTicks: number;
  22. }): string {
  23. return [
  24. String(input.pid),
  25. "(node (worker))",
  26. "S",
  27. String(input.parentPid),
  28. String(input.processGroupId),
  29. "0",
  30. "-1",
  31. "-1",
  32. "4194304",
  33. "1234",
  34. "0",
  35. "0",
  36. "0",
  37. String(input.utimeTicks),
  38. String(input.stimeTicks),
  39. "0",
  40. "0",
  41. ].join(" ");
  42. }
  43. function linuxStatusText(rssKb: number): string {
  44. return ["Name:\tnode", "State:\tS (sleeping)", `VmRSS:\t ${rssKb} kB`, ""].join("\n");
  45. }
  46. function commandResult(stdout: string) {
  47. return { status: 0, stderr: "", stdout };
  48. }
  49. afterEach(() => {
  50. vi.useRealTimers();
  51. });
  52. describe("通用进程探针 - macOS", () => {
  53. it("按 pid 列表一次 ps 采整棵进程树,输出每进程 RSS 与累计 CPU 时间", async () => {
  54. const execFile = vi.fn(async () => commandResult(DARWIN_PROCESS_TABLE));
  55. const probe = createProcessProbe({ execFile, platform: "darwin" });
  56. const trees = await probe.sampleProcessTrees([100, 200, 999]);
  57. expect(execFile).toHaveBeenCalledOnce();
  58. expect(execFile).toHaveBeenCalledWith(
  59. "ps",
  60. ["-eo", "pid=,ppid=,rss=,cputime="],
  61. expect.objectContaining({ encoding: "utf8", timeout: PROCESS_PROBE_SAMPLE_TIMEOUT_MS }),
  62. );
  63. expect(trees).toEqual(
  64. new Map([
  65. [
  66. 100,
  67. [
  68. { pid: 100, rssKb: 50, cpuTimeMs: 1_000 },
  69. { pid: 101, rssKb: 25, cpuTimeMs: 500 },
  70. { pid: 102, rssKb: 10, cpuTimeMs: 62_250 },
  71. ],
  72. ],
  73. [200, [{ pid: 200, rssKb: 30, cpuTimeMs: 0 }]],
  74. ]),
  75. );
  76. });
  77. it("按进程组一次 ps 采样且参数带 -g", async () => {
  78. const execFile = vi.fn(async () =>
  79. commandResult([" 400 20 0:02.00", " 401 30 1-00:00:00"].join("\n")),
  80. );
  81. const probe = createProcessProbe({ execFile, platform: "darwin" });
  82. const samples = await probe.sampleProcessGroup(4_242);
  83. expect(execFile).toHaveBeenCalledOnce();
  84. expect(execFile).toHaveBeenCalledWith(
  85. "ps",
  86. ["-o", "pid=,rss=,cputime=", "-g", "4242"],
  87. expect.objectContaining({ encoding: "utf8", timeout: PROCESS_PROBE_SAMPLE_TIMEOUT_MS }),
  88. );
  89. expect(samples).toEqual([
  90. { pid: 400, rssKb: 20, cpuTimeMs: 2_000 },
  91. { pid: 401, rssKb: 30, cpuTimeMs: 86_400_000 },
  92. ]);
  93. });
  94. it("pid 列表为空时不启动任何外部进程", async () => {
  95. const execFile = vi.fn(async () => commandResult(""));
  96. const probe = createProcessProbe({ execFile, platform: "darwin" });
  97. expect(await probe.sampleProcessTrees([])).toEqual(new Map());
  98. expect(await probe.sampleProcessTrees([0, -1, 1.5])).toEqual(new Map());
  99. expect(execFile).not.toHaveBeenCalled();
  100. });
  101. });
  102. describe("通用进程探针 - Linux", () => {
  103. function createProcFileSystem(rssByPid: ReadonlyMap<number, number | undefined>) {
  104. const statByPid = new Map<number, string>([
  105. [
  106. 100,
  107. linuxStatLine({
  108. pid: 100,
  109. parentPid: 1,
  110. processGroupId: 100,
  111. utimeTicks: 130,
  112. stimeTicks: 20,
  113. }),
  114. ],
  115. [
  116. 101,
  117. linuxStatLine({
  118. pid: 101,
  119. parentPid: 100,
  120. processGroupId: 100,
  121. utimeTicks: 5,
  122. stimeTicks: 5,
  123. }),
  124. ],
  125. [
  126. 500,
  127. linuxStatLine({
  128. pid: 500,
  129. parentPid: 1,
  130. processGroupId: 500,
  131. utimeTicks: 0,
  132. stimeTicks: 0,
  133. }),
  134. ],
  135. ]);
  136. const listProcDirectory = vi.fn(async () => ["1", "100", "101", "500", "self", "cpuinfo"]);
  137. const readProcFile = vi.fn(async (path: string) => {
  138. const match = /^\/proc\/(\d+)\/(stat|status)$/u.exec(path);
  139. if (!match) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
  140. const pid = Number(match[1]);
  141. if (match[2] === "stat") {
  142. const stat = statByPid.get(pid);
  143. if (!stat) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
  144. return stat;
  145. }
  146. const rssKb = rssByPid.get(pid);
  147. // 进程在两次读取之间退出:status 已消失,探针必须跳过该 pid 而不是抛错。
  148. if (rssKb === undefined) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
  149. return linuxStatusText(rssKb);
  150. });
  151. return { listProcDirectory, readProcFile };
  152. }
  153. it("读 /proc 的 stat 与 status,不调用任何 child_process API", async () => {
  154. const execFile = vi.fn(async () => commandResult(""));
  155. const { listProcDirectory, readProcFile } = createProcFileSystem(
  156. new Map([
  157. [100, 50],
  158. [101, 25],
  159. [500, 90],
  160. ]),
  161. );
  162. const probe = createProcessProbe({
  163. execFile,
  164. listProcDirectory,
  165. platform: "linux",
  166. readProcFile,
  167. });
  168. const trees = await probe.sampleProcessTrees([100]);
  169. expect(execFile).not.toHaveBeenCalled();
  170. expect(trees).toEqual(
  171. new Map([
  172. [
  173. 100,
  174. [
  175. { pid: 100, rssKb: 50, cpuTimeMs: 1_500 },
  176. { pid: 101, rssKb: 25, cpuTimeMs: 100 },
  177. ],
  178. ],
  179. ]),
  180. );
  181. const readPaths = readProcFile.mock.calls.map(([path]) => path);
  182. expect(readPaths).toContain("/proc/100/stat");
  183. expect(readPaths).toContain("/proc/100/status");
  184. // 只有落在目标进程树里的 pid 才需要读 status。
  185. expect(readPaths).not.toContain("/proc/500/status");
  186. });
  187. it("进程在读取期间退出时跳过该 pid 且不抛错", async () => {
  188. const { listProcDirectory, readProcFile } = createProcFileSystem(
  189. new Map([
  190. [100, 50],
  191. [101, undefined],
  192. ]),
  193. );
  194. const probe = createProcessProbe({ listProcDirectory, platform: "linux", readProcFile });
  195. expect(await probe.sampleProcessTrees([100])).toEqual(
  196. new Map([[100, [{ pid: 100, rssKb: 50, cpuTimeMs: 1_500 }]]]),
  197. );
  198. });
  199. it("按 pgid 过滤 /proc,不启动进程", async () => {
  200. const execFile = vi.fn(async () => commandResult(""));
  201. const { listProcDirectory, readProcFile } = createProcFileSystem(
  202. new Map([
  203. [100, 50],
  204. [101, 25],
  205. [500, 90],
  206. ]),
  207. );
  208. const probe = createProcessProbe({
  209. execFile,
  210. listProcDirectory,
  211. platform: "linux",
  212. readProcFile,
  213. });
  214. expect(await probe.sampleProcessGroup(100)).toEqual([
  215. { pid: 100, rssKb: 50, cpuTimeMs: 1_500 },
  216. { pid: 101, rssKb: 25, cpuTimeMs: 100 },
  217. ]);
  218. expect(execFile).not.toHaveBeenCalled();
  219. });
  220. it("/proc 不可读时本次无样本", async () => {
  221. const listProcDirectory = vi.fn(async () => {
  222. throw new Error("EACCES");
  223. });
  224. const probe = createProcessProbe({
  225. listProcDirectory,
  226. platform: "linux",
  227. readProcFile: async () => "",
  228. });
  229. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  230. });
  231. });
  232. describe("通用进程探针 - Windows", () => {
  233. const TASKLIST_OUTPUT = [
  234. '"node.exe","100","Console","1","12,345 K"',
  235. '"node.exe","200","Console","1","8,192 K"',
  236. ].join("\r\n");
  237. it("一次 tasklist 调用,样本没有 CPU 时间字段", async () => {
  238. const execFile = vi.fn(async () => commandResult(TASKLIST_OUTPUT));
  239. const probe = createProcessProbe({ execFile, platform: "win32" });
  240. const trees = await probe.sampleProcessTrees([100, 200]);
  241. expect(execFile).toHaveBeenCalledOnce();
  242. expect(execFile).toHaveBeenCalledWith(
  243. "tasklist",
  244. ["/FO", "CSV", "/NH"],
  245. expect.objectContaining({ timeout: PROCESS_PROBE_SAMPLE_TIMEOUT_MS, windowsHide: true }),
  246. );
  247. // Windows 只有直连进程内存,没有累计 CPU 时间;字段必须缺席而不是填 0。
  248. expect(trees).toEqual(
  249. new Map([
  250. [100, [{ pid: 100, rssKb: 12_345 }]],
  251. [200, [{ pid: 200, rssKb: 8_192 }]],
  252. ]),
  253. );
  254. expect(execFile.mock.calls.every(([command]) => command === "tasklist")).toBe(true);
  255. });
  256. it("Windows 没有进程组语义,直接返回无样本且不启动进程", async () => {
  257. const execFile = vi.fn(async () => commandResult(TASKLIST_OUTPUT));
  258. const probe = createProcessProbe({ execFile, platform: "win32" });
  259. expect(await probe.sampleProcessGroup(4_242)).toBeUndefined();
  260. expect(execFile).not.toHaveBeenCalled();
  261. });
  262. });
  263. describe("通用进程探针 - 超时与失败停用", () => {
  264. it("超过 1 秒返回无样本", async () => {
  265. vi.useFakeTimers();
  266. const execFile = vi.fn(() => new Promise<never>(() => undefined));
  267. const probe = createProcessProbe({ execFile, platform: "darwin" });
  268. const pending = probe.sampleProcessTrees([100]);
  269. await vi.advanceTimersByTimeAsync(PROCESS_PROBE_SAMPLE_TIMEOUT_MS);
  270. expect(await pending).toBeUndefined();
  271. });
  272. it("连续 3 次失败后不再调用外部命令,reset 后恢复", async () => {
  273. const execFile = vi.fn(async () => ({ status: 1, stderr: "boom", stdout: "" }));
  274. const probe = createProcessProbe({ execFile, platform: "darwin" });
  275. for (let attempt = 0; attempt < PROCESS_PROBE_MAX_CONSECUTIVE_FAILURES; attempt += 1) {
  276. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  277. }
  278. expect(execFile).toHaveBeenCalledTimes(PROCESS_PROBE_MAX_CONSECUTIVE_FAILURES);
  279. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  280. expect(await probe.sampleProcessGroup(4_242)).toBeUndefined();
  281. expect(execFile).toHaveBeenCalledTimes(PROCESS_PROBE_MAX_CONSECUTIVE_FAILURES);
  282. probe.reset();
  283. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  284. expect(execFile).toHaveBeenCalledTimes(PROCESS_PROBE_MAX_CONSECUTIVE_FAILURES + 1);
  285. });
  286. it("一次成功会清零连续失败计数", async () => {
  287. const stdout = [" 100 1 50 0:01.00"].join("\n");
  288. let shouldFail = true;
  289. const execFile = vi.fn(async () =>
  290. shouldFail ? { status: 1, stderr: "boom", stdout: "" } : commandResult(stdout),
  291. );
  292. const probe = createProcessProbe({ execFile, platform: "darwin" });
  293. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  294. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  295. shouldFail = false;
  296. expect(await probe.sampleProcessTrees([100])).toEqual(
  297. new Map([[100, [{ pid: 100, rssKb: 50, cpuTimeMs: 1_000 }]]]),
  298. );
  299. shouldFail = true;
  300. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  301. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  302. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  303. expect(execFile).toHaveBeenCalledTimes(6);
  304. });
  305. it("每次失败都把原因交给观测回调", async () => {
  306. const onSampleFailed = vi.fn();
  307. const probe = createProcessProbe({
  308. execFile: async () => ({ status: 1, stderr: "ps: 权限不足", stdout: "" }),
  309. onSampleFailed,
  310. platform: "darwin",
  311. });
  312. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  313. expect(onSampleFailed).toHaveBeenCalledOnce();
  314. expect(String(onSampleFailed.mock.calls[0]?.[0])).toContain("权限不足");
  315. });
  316. it("Linux /proc 扫描超时后不再发起剩余批次", async () => {
  317. const pids = Array.from({ length: 400 }, (_, index) => index + 100);
  318. let elapsedMs = 0;
  319. const nowSpy = vi.spyOn(Date, "now").mockImplementation(() => elapsedMs);
  320. const readProcFile = vi.fn(async () => {
  321. // 每次读推进 20 毫秒虚拟时间,一定会在扫完 400 个 pid 前撞上 1 秒预算。
  322. elapsedMs += 20;
  323. return "";
  324. });
  325. const probe = createProcessProbe({
  326. listProcDirectory: async () => pids.map(String),
  327. platform: "linux",
  328. readProcFile,
  329. });
  330. expect(await probe.sampleProcessTrees([100])).toBeUndefined();
  331. // 批次边界检查预算:读取次数远小于 pid 总数,超时后没有继续吃 IO。
  332. expect(readProcFile.mock.calls.length).toBeLessThan(pids.length);
  333. nowSpy.mockRestore();
  334. });
  335. it("treeScope 由探针自报,调用方不用判平台", () => {
  336. expect(createProcessProbe({ platform: "darwin" }).treeScope).toBe("process_tree");
  337. expect(createProcessProbe({ platform: "linux" }).treeScope).toBe("process_tree");
  338. expect(createProcessProbe({ platform: "win32" }).treeScope).toBe("direct_process");
  339. });
  340. });