e2e-process-cleanup.ts 12 KB

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