Skip to content

A full-featured download manager.

fix(engine): stop managed aria2 when its host dies (#2425)

Pujitha Paladugu24c429eab08b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 6e728769..4e828a1a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -487,6 +487,7 @@ jobs:
MOTRIX_FINALIZE_FS_TEST_BIN: packages/finalize-fs/dist/${{ matrix.platform }}-${{ matrix.arch }}/${{ matrix.platform == 'win32' && 'motrix-finalize-fs.exe' || 'motrix-finalize-fs' }}
run: >-
pnpm exec vitest run
+ src/core/engine/aria2/aria2-parent-lifecycle.integration.test.ts
src/core/legacy-import/http-activation.integration.test.ts
src/core/plugin/finalize/native-artifact-operations.integration.test.ts
src/core/plugin/finalize/finalize-adversarial.integration.test.ts
diff --git a/src/core/engine/aria2/aria2-config-builder.test.ts b/src/core/engine/aria2/aria2-config-builder.test.ts
index 485d9c75..1ace1127 100644
--- a/src/core/engine/aria2/aria2-config-builder.test.ts
+++ b/src/core/engine/aria2/aria2-config-builder.test.ts
@@ -92,6 +92,41 @@ describe('Aria2ConfigBuilder', () => {
vi.restoreAllMocks()
})
+ describe('supervisorPid', () => {
+ const effective = { download: 0, upload: 0 }
+
+ it('omits --stop-with-process by default', () => {
+ const args = buildArgs(DEFAULT_ENGINE_SETTINGS, true, null, effective)
+ expect(args.some((arg) => arg.startsWith('--stop-with-process'))).toBe(
+ false
+ )
+ })
+
+ it('passes the host pid so aria2 exits when the host dies', () => {
+ const withPid = new Aria2ConfigBuilder(
+ '/t',
+ '/home/user/.config/motrix',
+ {
+ supervisorPid: 4242,
+ }
+ )
+ const args = withPid.buildArgs(
+ makeEngineSettings(DEFAULT_ENGINE_SETTINGS),
+ true,
+ null,
+ effective,
+ DEFAULT_SAVE_DIR
+ )
+ expect(args).toContain('--stop-with-process=4242')
+ })
+
+ it.each([0, -1, 1.5, Number.NaN])('rejects invalid pid %s', (pid) => {
+ expect(
+ () => new Aria2ConfigBuilder('/t', '/u', { supervisorPid: pid })
+ ).toThrow(TypeError)
+ })
+ })
+
describe('ensureUserConfig', () => {
it('excludes advanced global seeding time while preserving the original config', async () => {
mockAccess.mockResolvedValue(undefined)
diff --git a/src/core/engine/aria2/aria2-config-builder.ts b/src/core/engine/aria2/aria2-config-builder.ts
index 4c0a0e49..812d6c04 100644
--- a/src/core/engine/aria2/aria2-config-builder.ts
+++ b/src/core/engine/aria2/aria2-config-builder.ts
@@ -15,6 +15,11 @@ export interface Aria2ConfigBuilderOptions {
rpcListenAll?: boolean
/** Server HTTP and engine RPC must use the same torrent upload budget. */
rpcMaxRequestSizeBytes?: number
+ /**
+ * Host process aria2 must not outlive. aria2 exits on its own once this
+ * process disappears, covering host crashes that skip graceful shutdown.
+ */
+ supervisorPid?: number
}
export class Aria2ConfigBuilder {
@@ -25,6 +30,7 @@ export class Aria2ConfigBuilder {
private readonly dht6FilePath: string
private readonly rpcListenAll: boolean
private readonly rpcMaxRequestSizeBytes?: number
+ private readonly supervisorPid?: number
private configuredInputFile = false
private runtimeConfPath: string
@@ -44,6 +50,15 @@ export class Aria2ConfigBuilder {
options.rpcMaxRequestSizeBytes === undefined
? undefined
: torrentRpcBodyLimitSchema.parse(options.rpcMaxRequestSizeBytes)
+ if (options.supervisorPid !== undefined) {
+ if (
+ !Number.isSafeInteger(options.supervisorPid) ||
+ options.supervisorPid < 1
+ ) {
+ throw new TypeError('supervisorPid must be a positive integer')
+ }
+ this.supervisorPid = options.supervisorPid
+ }
}
async ensureUserConfig(): Promise<string> {
@@ -276,6 +291,9 @@ export class Aria2ConfigBuilder {
`--rpc-max-request-size=${this.rpcMaxRequestSizeBytes / (1024 * 1024)}M`
)
}
+ if (this.supervisorPid !== undefined) {
+ args.push(`--stop-with-process=${this.supervisorPid}`)
+ }
args.push(
'--bt-save-metadata=true',
'--bt-metadata-only=false',
diff --git a/src/core/engine/aria2/aria2-parent-lifecycle.integration.test.ts b/src/core/engine/aria2/aria2-parent-lifecycle.integration.test.ts
new file mode 100644
index 00000000..d6f37b00
--- /dev/null
+++ b/src/core/engine/aria2/aria2-parent-lifecycle.integration.test.ts
@@ -0,0 +1,227 @@
+// @vitest-environment node
+import { type ChildProcess, spawn } from 'node:child_process'
+import { once } from 'node:events'
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { createConnection, createServer } from 'node:net'
+import { tmpdir } from 'node:os'
+import path from 'node:path'
+import { setTimeout as delay } from 'node:timers/promises'
+import { DEFAULT_ENGINE_SETTINGS } from '@core/settings/validators'
+import {
+ bundledAria2Exists,
+ canBindLoopbackTcp,
+ resolveBundledAria2,
+ waitForRpc,
+} from '@test-utils/aria2'
+import { describe, expect, it } from 'vitest'
+import { Aria2ConfigBuilder } from './aria2-config-builder'
+
+// Unix uses the production pipe setup. Windows needs a detached child with
+// independent stdio to isolate aria2's watchdog from libuv's kill-on-close Job.
+// A separate Windows case covers the production, non-detached Job behavior.
+const hostSource = `
+ const { spawn } = require('node:child_process')
+ process.once('message', ({ binary, args, detached }) => {
+ const engine = spawn(binary, args, {
+ detached,
+ stdio: detached ? 'ignore' : ['ignore', 'pipe', 'pipe'],
+ })
+ engine.stdout?.on('data', () => {})
+ engine.stderr?.on('data', () => {})
+ engine.once('spawn', () => process.send({ pid: engine.pid }))
+ engine.once('error', (error) => process.send({ error: error.message }))
+ })
+ setInterval(() => {}, 1000)
+`
+
+async function availablePort(): Promise<number> {
+ const server = createServer()
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('No TCP port')
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve()))
+ )
+ return address.port
+}
+
+function portIsListening(port: number): Promise<boolean> {
+ return new Promise((resolve) => {
+ const socket = createConnection({ host: '127.0.0.1', port })
+ const finish = (listening: boolean) => {
+ socket.destroy()
+ resolve(listening)
+ }
+ socket.once('connect', () => finish(true))
+ socket.once('error', () => finish(false))
+ socket.setTimeout(500, () => finish(false))
+ })
+}
+
+async function stopHost(host: ChildProcess): Promise<void> {
+ if (host.exitCode !== null || host.signalCode !== null) return
+ const exited = once(host, 'exit', { signal: AbortSignal.timeout(5_000) })
+ host.kill('SIGKILL')
+ await exited
+}
+
+function stopEngine(pid: number): void {
+ try {
+ process.kill(pid, 'SIGKILL')
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error
+ }
+}
+
+async function engineIsRunning(pid: number): Promise<boolean> {
+ try {
+ process.kill(pid, 0)
+ if (process.platform === 'linux') {
+ // An orphan can briefly remain a zombie until its new parent reaps it.
+ // It has already exited and cannot hold sockets or write session data.
+ const stat = await readFile(`/proc/${pid}/stat`, 'utf8')
+ return !['Z', 'X'].includes(
+ stat.slice(stat.lastIndexOf(') ') + 2, stat.lastIndexOf(') ') + 3)
+ )
+ }
+ return true
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code
+ if (code === 'ESRCH' || code === 'ENOENT') return false
+ throw error
+ }
+}
+
+describe.skipIf(!bundledAria2Exists() || !canBindLoopbackTcp())(
+ 'aria2 host crash recovery',
+ () => {
+ it.each([
+ {
+ watch: false,
+ detached: process.platform === 'win32',
+ jobManaged: false,
+ },
+ {
+ watch: true,
+ detached: process.platform === 'win32',
+ jobManaged: false,
+ },
+ ...(process.platform === 'win32'
+ ? [{ watch: true, detached: false, jobManaged: true }]
+ : []),
+ ])(
+ 'host crash (watch=$watch, detached=$detached)',
+ async ({ watch, detached, jobManaged }) => {
+ const root = await mkdtemp(path.join(tmpdir(), 'motrix-parent-watch-'))
+ const port = await availablePort()
+ const secret = 'isolated-parent-watch-test'
+ const host = spawn(process.execPath, ['-e', hostSource], {
+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
+ })
+ let enginePid: number | undefined
+ try {
+ await once(host, 'spawn')
+ if (!host.pid) throw new Error('No host PID')
+ // A stale advanced config must not override the host's L1 argument.
+ await writeFile(
+ path.join(root, 'aria2.conf'),
+ watch ? `stop-with-process=${process.pid}\n` : ''
+ )
+ const builder = new Aria2ConfigBuilder('', root, {
+ supervisorPid: watch ? host.pid : undefined,
+ })
+ const args = builder.buildArgs(
+ {
+ ...DEFAULT_ENGINE_SETTINGS,
+ rpcPort: port,
+ rpcSecret: secret,
+ dhtEnabled: false,
+ },
+ false,
+ null,
+ { download: 0, upload: 0 },
+ root
+ )
+ args.push(
+ '--disable-ipv6=true',
+ '--summary-interval=0',
+ `--log=${path.join(root, 'engine.log')}`,
+ '--log-level=info'
+ )
+ const spawned = once(host, 'message', {
+ signal: AbortSignal.timeout(5_000),
+ })
+ host.send({ binary: resolveBundledAria2(), args, detached })
+ const [message] = await spawned
+ if (typeof message.pid !== 'number') throw new Error(message.error)
+ enginePid = message.pid
+ await waitForRpc(port, 5_000, secret)
+ // Cross a watcher tick before crashing the host; an incorrect PID
+ // must fail here rather than accidentally passing the exit assertion.
+ await delay(1_500)
+ await waitForRpc(port, 1_000, secret)
+ const uri = `http://127.0.0.1:${port}/paused-download.bin`
+ const response = await fetch(`http://127.0.0.1:${port}/jsonrpc`, {
+ method: 'POST',
+ signal: AbortSignal.timeout(2_000),
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'aria2.addUri',
+ params: [`token:${secret}`, [uri], { pause: 'true' }],
+ }),
+ })
+ expect(await response.json()).toMatchObject({
+ result: expect.any(String),
+ })
+ await stopHost(host)
+
+ if (jobManaged) {
+ // Node's Windows Job forcibly terminates production children.
+ // Do not mistake kernel cleanup for aria2's graceful watchdog.
+ await expect
+ .poll(() => portIsListening(port), { timeout: 8_000 })
+ .toBe(false)
+ await expect
+ .poll(() => engineIsRunning(message.pid), { timeout: 3_000 })
+ .toBe(false)
+ } else if (watch) {
+ await expect
+ .poll(() => portIsListening(port), { timeout: 8_000 })
+ .toBe(false)
+ await expect
+ .poll(
+ async () => readFile(path.join(root, 'aria2.session'), 'utf8'),
+ {
+ timeout: 3_000,
+ }
+ )
+ .toContain(uri)
+ expect(
+ await readFile(path.join(root, 'engine.log'), 'utf8')
+ ).toContain(
+ `Process ${host.pid} is not running. Commencing shutdown.`
+ )
+ await expect
+ .poll(() => engineIsRunning(message.pid), { timeout: 3_000 })
+ .toBe(false)
+ } else {
+ // The control proves that host termination / pipe closure alone
+ // does not account for the successful cleanup in the watched case.
+ await delay(2_000)
+ await waitForRpc(port, 1_000, secret)
+ }
+ } finally {
+ await stopHost(host)
+ if (enginePid !== undefined && (await engineIsRunning(enginePid))) {
+ stopEngine(enginePid)
+ await expect.poll(() => portIsListening(port)).toBe(false)
+ }
+ await rm(root, { recursive: true, force: true })
+ }
+ },
+ 25_000
+ )
+ }
+)
diff --git a/src/main/index.ts b/src/main/index.ts
index 63947ec4..fa9ae5b6 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -458,7 +458,8 @@ log.info({ extraDir: platform.extraResourceDir }, 'resolved extra directory')
const configBuilder = new Aria2ConfigBuilder(
path.join(platform.extraResourceDir, 'aria2.conf'),
- platform.userDataDir
+ platform.userDataDir,
+ { supervisorPid: process.pid }
)
const trustStore = new Aria2TrustStore(platform.userDataDir)
diff --git a/src/server/index.ts b/src/server/index.ts
index 719bc04e..3507ba87 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -477,6 +477,7 @@ async function main() {
path.join(platform.extraResourceDir, 'aria2.conf'),
platform.userDataDir,
{
+ supervisorPid: process.pid,
rpcListenAll: parseServerBoolean(
process.env.MOTRIX_ARIA2_RPC_LISTEN_ALL,
'MOTRIX_ARIA2_RPC_LISTEN_ALL'