e2e-process-cleanup.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import { execFile, execFileSync } from "node:child_process";
  2. const E2E_RUN_ID_ARG_NAME = "--zcode-e2e-run-id";
  3. const E2E_HOME_ARG_NAME = "--zcode-e2e-home";
  4. const E2E_PROCESS_SCAN_MAX_BUFFER_BYTES = 20 * 1024 * 1024;
  5. export interface E2EProcessInfo {
  6. command: string;
  7. pid: number;
  8. ppid: number;
  9. }
  10. export interface E2EProcessCleanupIdentity {
  11. chromiumProfileRootDir?: string;
  12. currentPid?: number;
  13. homeDir: string;
  14. /**
  15. * 完整 run 收尾需要回收遗留的 ChromeDriver;但单次 reload 必须让 driver 存活以复用
  16. * 同一 WDIO service。调用方可关闭该父链补齐,避免 exit barrier 误等 driver 自己退出。
  17. */
  18. includeChromeDriverAncestors?: boolean;
  19. rootPids?: number[];
  20. runId?: string | null;
  21. }
  22. export interface E2EProcessScanOptions {
  23. platform?: NodeJS.Platform;
  24. runCommand?: (command: string, args: string[]) => string;
  25. }
  26. export interface E2EAsyncProcessScanOptions {
  27. platform?: NodeJS.Platform;
  28. runCommand?: (command: string, args: string[]) => Promise<string>;
  29. }
  30. export function buildE2ERunIdArg(runId: string) {
  31. return `${E2E_RUN_ID_ARG_NAME}=${runId}`;
  32. }
  33. export function createWindowsE2EHomeMarkerArg(homeDir: string) {
  34. return `${E2E_HOME_ARG_NAME}=${homeDir}`;
  35. }
  36. export function buildWindowsTaskkillArgs(pids: number[]) {
  37. const uniquePids = [...new Set(pids)].filter((pid) => Number.isInteger(pid) && pid > 0);
  38. return [...uniquePids.flatMap((pid) => ["/PID", String(pid)]), "/T", "/F"];
  39. }
  40. export function collectWindowsE2EProcessTreePids(
  41. output: string,
  42. identity: E2EProcessCleanupIdentity,
  43. ) {
  44. return collectE2EProcessTreePids(parseWindowsProcessRows(output), identity);
  45. }
  46. export function listE2EProcessTreePids(
  47. identity: E2EProcessCleanupIdentity,
  48. options: E2EProcessScanOptions = {},
  49. ) {
  50. const platform = options.platform ?? process.platform;
  51. const runCommand = options.runCommand ?? runProcessScanCommand;
  52. if (platform === "win32") {
  53. return collectWindowsE2EProcessTreePids(runWindowsProcessScan(runCommand), identity);
  54. }
  55. return collectE2EProcessTreePids(
  56. parsePosixProcessRows(runCommand("ps", ["-axo", "pid=,ppid=,command="])),
  57. identity,
  58. );
  59. }
  60. export async function listSystemProcesses(
  61. options: E2EAsyncProcessScanOptions = {},
  62. ): Promise<E2EProcessInfo[]> {
  63. const platform = options.platform ?? process.platform;
  64. const runCommand = options.runCommand ?? runProcessScanCommandAsync;
  65. return platform === "win32"
  66. ? parseWindowsProcessRows(await runWindowsProcessScanAsync(runCommand))
  67. : parsePosixProcessRows(await runCommand("ps", ["-axo", "pid=,ppid=,command="]));
  68. }
  69. export function collectProcessTreeByRootPids(
  70. processes: E2EProcessInfo[],
  71. rootPids: number[],
  72. ): E2EProcessInfo[] {
  73. const processPids = new Set(processes.map((item) => item.pid));
  74. const targetPids = new Set(
  75. rootPids.filter((pid) => Number.isInteger(pid) && pid > 0 && processPids.has(pid)),
  76. );
  77. let changed = true;
  78. while (changed) {
  79. changed = false;
  80. for (const item of processes) {
  81. if (!targetPids.has(item.pid) && targetPids.has(item.ppid)) {
  82. targetPids.add(item.pid);
  83. changed = true;
  84. }
  85. }
  86. }
  87. return processes
  88. .filter((item) => targetPids.has(item.pid))
  89. .sort((left, right) => left.pid - right.pid);
  90. }
  91. export function collectE2EProcessTreePids(
  92. processes: E2EProcessInfo[],
  93. identity: E2EProcessCleanupIdentity,
  94. ) {
  95. const excludedPids = collectCurrentProcessAncestorPids(
  96. processes,
  97. identity.currentPid ?? process.pid,
  98. );
  99. const processPids = new Set(processes.map((item) => item.pid));
  100. // Bug 原因:macOS Electron main 的实际命令行不保证保留 appArgs identity marker;
  101. // reload 已从 main bridge 取得权威 PID,必须允许它作为显式根,再递归收集全部后代。
  102. const targetPids = new Set([
  103. ...(identity.rootPids ?? []).filter(
  104. (pid) => Number.isInteger(pid) && pid > 0 && processPids.has(pid) && !excludedPids.has(pid),
  105. ),
  106. ...processes
  107. .filter(
  108. (item) =>
  109. !excludedPids.has(item.pid) && isCurrentE2EProcessCleanupRoot(item.command, identity),
  110. )
  111. .map((item) => item.pid),
  112. ]);
  113. const processByPid = new Map(processes.map((item) => [item.pid, item]));
  114. const seedPids = Array.from(targetPids);
  115. for (const seedPid of seedPids) {
  116. let current = processByPid.get(seedPid);
  117. while (current && current.ppid > 1) {
  118. const parent = processByPid.get(current.ppid);
  119. if (
  120. !parent ||
  121. excludedPids.has(parent.pid) ||
  122. !isE2EProcessAncestorCandidate(
  123. parent.command,
  124. identity.includeChromeDriverAncestors !== false,
  125. )
  126. ) {
  127. break;
  128. }
  129. // Bug 根因:macOS 会把 Electron main 的命令行收敛成 `ZCode E2E`,
  130. // ChromeDriver 也不携带 appArgs;只有 renderer/utility 还保留当前 run 的
  131. // profile/HOME。精确命中后代后必须反向补齐父链,否则只能杀 renderer,
  132. // markerless main/ChromeDriver 会跨 worker 存活并持续重建窗口。
  133. targetPids.add(parent.pid);
  134. current = parent;
  135. }
  136. }
  137. let changed = true;
  138. while (changed) {
  139. changed = false;
  140. for (const item of processes) {
  141. if (!targetPids.has(item.pid) && targetPids.has(item.ppid) && !excludedPids.has(item.pid)) {
  142. targetPids.add(item.pid);
  143. changed = true;
  144. }
  145. }
  146. }
  147. return [...targetPids].sort((left, right) => right - left);
  148. }
  149. function isE2EProcessAncestorCandidate(command: string, includeChromeDriverAncestors: boolean) {
  150. const normalizedCommand = command.trim().replaceAll("\\", "/").toLowerCase();
  151. return (
  152. (includeChromeDriverAncestors &&
  153. /(?:^|\/)chromedriver(?:\.exe)?(?:\s|$)/u.test(normalizedCommand)) ||
  154. /(?:^|\/)electron(?:\.exe)?(?:\s|$)/u.test(normalizedCommand) ||
  155. /(?:^|\/)zcode e2e(?:\.exe)?(?:\s|$)/u.test(normalizedCommand)
  156. );
  157. }
  158. export function isCurrentE2EProcessCleanupRoot(
  159. command: string,
  160. identity: E2EProcessCleanupIdentity,
  161. ) {
  162. const normalizedCommand = command.toLowerCase();
  163. if (normalizedCommand.includes("@wdio/cli") || normalizedCommand.includes("wdio.conf.ts")) {
  164. return false;
  165. }
  166. const runId = identity.runId?.trim();
  167. if (runId && isCommandMarkerPresent(command, buildE2ERunIdArg(runId))) {
  168. return true;
  169. }
  170. // Bug 原因:main 改名后丢失启动参数,Chromium 子进程只保留 run cache 下的
  171. // profile,不包含 HOME;用当前 run 独占的 profile 路径找回父链,避免漏清 main。
  172. const chromiumProfileRootDir = identity.chromiumProfileRootDir?.trim();
  173. if (chromiumProfileRootDir && isCommandPathPresent(command, chromiumProfileRootDir)) {
  174. return true;
  175. }
  176. const homeDir = identity.homeDir.trim();
  177. if (!homeDir) {
  178. return false;
  179. }
  180. if (buildE2EHomeArgMarkers(homeDir).some((marker) => isCommandMarkerPresent(command, marker))) {
  181. return true;
  182. }
  183. return buildE2EHomePathMarkers(homeDir).some((marker) => isCommandPathPresent(command, marker));
  184. }
  185. function parseWindowsProcessRows(output: string): E2EProcessInfo[] {
  186. if (!output.trim()) {
  187. return [];
  188. }
  189. let parsed: unknown;
  190. try {
  191. parsed = JSON.parse(output) as unknown;
  192. } catch {
  193. return [];
  194. }
  195. const rows = Array.isArray(parsed) ? parsed : [parsed];
  196. return rows.flatMap((row) => {
  197. if (!row || typeof row !== "object") {
  198. return [];
  199. }
  200. const record = row as Record<string, unknown>;
  201. const pid = Number(record.ProcessId);
  202. const parentPid = Number(record.ParentProcessId);
  203. if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) {
  204. return [];
  205. }
  206. return [
  207. {
  208. command: typeof record.CommandLine === "string" ? record.CommandLine : "",
  209. pid,
  210. ppid: parentPid,
  211. },
  212. ];
  213. });
  214. }
  215. function parsePosixProcessRows(output: string): E2EProcessInfo[] {
  216. return output
  217. .split("\n")
  218. .map((line) => line.match(/^\s*(\d+)\s+(\d+)\s+(.+)$/u))
  219. .filter((match): match is RegExpMatchArray => Boolean(match))
  220. .map((match) => ({
  221. command: match[3] ?? "",
  222. pid: Number(match[1]),
  223. ppid: Number(match[2]),
  224. }))
  225. .filter((item) => Number.isInteger(item.pid) && Number.isInteger(item.ppid));
  226. }
  227. function runWindowsProcessScan(runCommand: (command: string, args: string[]) => string) {
  228. const script = [
  229. "Get-CimInstance Win32_Process |",
  230. "Select-Object ProcessId,ParentProcessId,CommandLine |",
  231. "ConvertTo-Json -Compress",
  232. ].join(" ");
  233. let latestError: unknown = null;
  234. for (const powershell of ["powershell.exe", "pwsh"]) {
  235. try {
  236. return runCommand(powershell, ["-NoProfile", "-Command", script]);
  237. } catch (error) {
  238. latestError = error;
  239. }
  240. }
  241. throw latestError;
  242. }
  243. async function runWindowsProcessScanAsync(
  244. runCommand: (command: string, args: string[]) => Promise<string>,
  245. ) {
  246. const script = [
  247. "Get-CimInstance Win32_Process |",
  248. "Select-Object ProcessId,ParentProcessId,CommandLine |",
  249. "ConvertTo-Json -Compress",
  250. ].join(" ");
  251. let latestError: unknown = null;
  252. for (const powershell of ["powershell.exe", "pwsh"]) {
  253. try {
  254. return await runCommand(powershell, ["-NoProfile", "-Command", script]);
  255. } catch (error) {
  256. latestError = error;
  257. }
  258. }
  259. throw latestError;
  260. }
  261. function runProcessScanCommand(command: string, args: string[]) {
  262. return execFileSync(command, args, {
  263. encoding: "utf-8",
  264. maxBuffer: E2E_PROCESS_SCAN_MAX_BUFFER_BYTES,
  265. windowsHide: true,
  266. });
  267. }
  268. function runProcessScanCommandAsync(command: string, args: string[]): Promise<string> {
  269. return new Promise((resolveCommand, rejectCommand) => {
  270. execFile(
  271. command,
  272. args,
  273. {
  274. encoding: "utf-8",
  275. maxBuffer: E2E_PROCESS_SCAN_MAX_BUFFER_BYTES,
  276. windowsHide: true,
  277. },
  278. (error, stdout) => {
  279. if (error) {
  280. rejectCommand(error);
  281. return;
  282. }
  283. resolveCommand(stdout);
  284. },
  285. );
  286. });
  287. }
  288. function collectCurrentProcessAncestorPids(processes: E2EProcessInfo[], currentPid: number) {
  289. const byPid = new Map(processes.map((item) => [item.pid, item]));
  290. const pids = new Set<number>([currentPid]);
  291. let current = byPid.get(currentPid);
  292. while (current && current.ppid > 0 && !pids.has(current.ppid)) {
  293. pids.add(current.ppid);
  294. current = byPid.get(current.ppid);
  295. }
  296. return pids;
  297. }
  298. function buildE2EHomeArgMarkers(homeDir: string) {
  299. return buildE2EHomePathMarkers(homeDir).map(createWindowsE2EHomeMarkerArg);
  300. }
  301. function buildE2EHomePathMarkers(homeDir: string) {
  302. return uniqueStrings([homeDir, homeDir.replaceAll("\\", "/"), homeDir.replaceAll("/", "\\")]);
  303. }
  304. function isCommandMarkerPresent(command: string, marker: string) {
  305. if (!marker) {
  306. return false;
  307. }
  308. let index = command.indexOf(marker);
  309. while (index >= 0) {
  310. if (
  311. hasCommandBoundary(command[index - 1]) &&
  312. hasCommandBoundary(command[index + marker.length])
  313. ) {
  314. return true;
  315. }
  316. index = command.indexOf(marker, index + marker.length);
  317. }
  318. return false;
  319. }
  320. function isCommandPathPresent(command: string, marker: string) {
  321. const normalizedCommand = normalizePathForComparison(command);
  322. const normalizedMarker = normalizePathForComparison(marker);
  323. let index = normalizedCommand.indexOf(normalizedMarker);
  324. while (index >= 0) {
  325. const before = normalizedCommand[index - 1];
  326. const after = normalizedCommand[index + normalizedMarker.length];
  327. // 修复原因:共享 app 路径不能作为 identity;HOME 必须按完整路径边界匹配,
  328. // 同时允许命令行继续引用 HOME 下的配置文件,避免 current 命中 current-copy。
  329. if (isHomeBoundaryBefore(before) && isHomeBoundaryAfter(after)) {
  330. return true;
  331. }
  332. index = normalizedCommand.indexOf(normalizedMarker, index + normalizedMarker.length);
  333. }
  334. return false;
  335. }
  336. function normalizePathForComparison(value: string) {
  337. return value.trim().replaceAll("\\", "/").replace(/\/+$/u, "").toLowerCase();
  338. }
  339. function isHomeBoundaryBefore(char: string | undefined) {
  340. return char === undefined || /[\s"'=]/u.test(char);
  341. }
  342. function isHomeBoundaryAfter(char: string | undefined) {
  343. return char === undefined || /[\s/"']/u.test(char);
  344. }
  345. function hasCommandBoundary(char: string | undefined) {
  346. return char === undefined || !/[A-Za-z0-9._~:/\\-]/u.test(char);
  347. }
  348. function uniqueStrings(values: string[]) {
  349. return [...new Set(values.filter(Boolean))];
  350. }
  351. /**
  352. * E2E runner 里被 await 的等待(等待残留进程退出、重试删除 HOME)。
  353. *
  354. * Bug 根因:原实现(wdio.conf.ts 的 delay)给计时器 unref。onComplete 强杀残留 Electron 时,进程里
  355. * 只剩这个计时器,事件循环为空,Node 在等待中途直接以 0 退出:summary 没写、退出看门狗没装、
  356. * WDIO 也没按失败结果退出,本机 Docker runner 因此把失败的 spec 报成 PASS。
  357. * 修法:被等待的计时器保持 ref。等待本身有界(调用方的超时循环),兜底退出仍由 onComplete 看门狗负责。
  358. */
  359. export function waitE2EDelay(ms: number): Promise<void> {
  360. return new Promise<void>((resolveDelay) => setTimeout(resolveDelay, Math.max(ms, 0)));
  361. }