okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221host: ending a child that never started no longer signals the caller's own process group on macOScb73b620a

main
6.3 KiB91 linesraw
1import test from 'node:test';
2import assert from 'node:assert/strict';
3import { spawn } from 'node:child_process';
4import { readFileSync, rmSync, existsSync } from 'node:fs';
5import { tmpdir } from 'node:os';
6import { join } from 'node:path';
7import { endTree, endTreeThenKill, groupAlive, ownGroup } from '../server/process-tree.mjs';
8import { runCommand } from '../server/agent/custom-command-run.mjs';
9
10const isWin = process.platform === 'win32';
11const sleep = ms => new Promise(r => setTimeout(r, ms));
12
13// Whether the process is there. A process that has ended but whose parent has not collected it yet (a zombie: Node reaps its own children when the event
14// loop gets to it, init reaps the orphans when it gets to them) answers signal 0 and is not running: on a loaded machine that gap is long.
15function alive(pid) {
16  try { process.kill(pid, 0); } catch (error) { return error.code === 'EPERM'; }
17  if (process.platform === 'linux') {
18    try { return readFileSync(`/proc/${pid}/stat`, 'utf8').replace(/^.*\) /, '')[0] !== 'Z'; } catch { return false; }
19  }
20  return true;
21}
22// Every wait is on the real condition, with a long limit: it returns the moment the condition holds, so the limit costs nothing when the machine is fine.
23async function until(condition, ms = 30_000) { for (let waited = 0; waited < ms; waited += 50) { if (condition()) return true; await sleep(50); } return condition(); }
24const gone = (pid, ms) => until(() => !alive(pid), ms);
25
26// A program that starts a program of its own and reports its pid, the way Stop meets a job and its revision command (#4529 #4570).
27const parentScript = `const { spawn } = require('node:child_process'); const k = spawn(process.execPath, ['-e', 'setTimeout(()=>{}, 120000)'], { stdio: 'ignore' }); console.log(k.pid); setTimeout(()=>{}, 120000);`;
28
29async function tree() {
30  const child = spawn(process.execPath, ['-e', parentScript], { detached: ownGroup(), stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
31  const kid = await new Promise(resolve => child.stdout.once('data', b => resolve(Number(String(b).trim()))));
32  return { child, kid };
33}
34
35test('endTree ends the program and the program it started, and nothing else (#4529 #4570)', async () => {
36  const outsider = spawn(process.execPath, ['-e', 'setTimeout(()=>{}, 120000)'], { stdio: 'ignore', windowsHide: true });   // same program, not started by the job
37  const { child, kid } = await tree();
38  try {
39    assert.ok(alive(kid));
40    endTree(child);
41    assert.ok(await gone(child.pid), 'the job survived');
42    assert.ok(await gone(kid), 'what the job started survived');
43    assert.ok(alive(outsider.pid), 'a process of the same program that the job did not start was ended');
44  } finally { outsider.kill(); try { process.kill(kid, 'SIGKILL'); } catch { /* gone */ } child.kill('SIGKILL'); }
45});
46
47test('endTreeThenKill follows a TERM that is ignored with a KILL of the group', { skip: isWin && 'POSIX signals' }, async () => {
48  // Both programs ignore SIGTERM, and the test goes on only when both have said that the handler is in place (no fixed delay for a slow start).
49  const stubborn = `const { spawn } = require('node:child_process'); process.on('SIGTERM', () => {});
50    const k = spawn(process.execPath, ['-e', "process.on('SIGTERM',()=>{});console.log('up');setTimeout(()=>{},120000)"], { stdio: ['ignore', 'pipe', 'ignore'] });
51    k.stdout.once('data', () => { console.log(k.pid); }); setTimeout(()=>{}, 120000);`;
52  const child = spawn(process.execPath, ['-e', stubborn], { detached: true, stdio: ['ignore', 'pipe', 'ignore'] });
53  const kid = await new Promise(resolve => child.stdout.once('data', b => resolve(Number(String(b).trim()))));
54  try {
55    assert.ok(alive(kid));
56    endTreeThenKill(child, 500);
57    assert.ok(await gone(kid, 60_000), 'the group survived SIGTERM and was not killed');
58    assert.ok(await gone(child.pid, 60_000));
59    assert.ok(await until(() => !groupAlive(child), 60_000), 'a member of the group is still there');
60  } finally { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* gone */ } }
61});
62
63test('a child that leads no group of its own is still ended, alone, as before', async () => {
64  const child = spawn(process.execPath, ['-e', 'setTimeout(()=>{}, 120000)'], { stdio: 'ignore', windowsHide: true });
65  endTree(child);
66  assert.ok(await gone(child.pid));
67});
68
69test('a custom command that runs out of time takes the programs it started with it', { skip: isWin && 'POSIX shell' }, async () => {
70  const marker = join(tmpdir(), `strata-cc-${process.pid}.pid`);
71  rmSync(marker, { force: true });
72  // The limit is far above what the shell needs to start and write its marker, so a slow machine cannot end the command before it did.
73  const result = await runCommand({ command: `sleep 120 & echo $! > ${marker}; wait`, timeoutSec: 8 });
74  assert.equal(result.ok, false);
75  assert.ok(await until(() => existsSync(marker) && /^\d+/.test(readFileSync(marker, 'utf8'))), 'the command never wrote its marker');
76  const pid = Number(readFileSync(marker, 'utf8').trim());
77  rmSync(marker, { force: true });
78  assert.ok(await gone(pid), 'the command\'s own child outlived the time limit');
79});
80
81test('ending a child that never started leaves the caller and its process group alone (macOS signalled the whole group)', { skip: isWin && 'POSIX process groups' }, async () => {
82  // A program that fails to start a child and ends it before the "error" event arrives, the way a Stop can meet a job whose Python is missing.
83  // It leads a group of its own, so if the signal reaches its group it dies by SIGTERM and the test fails; this process is never in the line of fire.
84  const body = `import { spawn } from 'node:child_process'; import { endTree, endTreeThenKill } from ${JSON.stringify(new URL('../server/process-tree.mjs', import.meta.url).href)};
85    const c = spawn('strata-no-such-program-xyz', [], { stdio: 'ignore' }); c.on('error', () => {}); endTree(c); endTreeThenKill(c, 10); setTimeout(() => console.log('survived'), 300);`;
86  const child = spawn(process.execPath, ['--input-type=module', '-e', body], { detached: true, stdio: ['ignore', 'pipe', 'ignore'] });
87  let out = ''; child.stdout.on('data', b => { out += b; });
88  const code = await new Promise(resolve => child.on('close', (c, s) => resolve(s ?? c)));
89  assert.equal(code, 0, `the caller was signalled (${code})`);
90  assert.match(out, /survived/);
91});