fix(core): only manage PID files in daemon mode (#421)

This commit is contained in:
Yiling-J
2026-09-22 20:31:38 +08:00
committed by GitHub
parent 75bf9b3b88
commit 53c9485f10
3 changed files with 56 additions and 32 deletions
+1
View File
@@ -11,6 +11,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Fixed
- **docker**: Fix an issue where the bundled PostgreSQL container published port 5432 on the host, causing deployment to fail on machines where that port was already in use; the database is now only reachable by Shumai itself
- **cli**: Only manage and check PID files in daemon mode, preventing stale PID files, crash-loop conflicts, or spurious process checks during normal foreground and Docker execution
### Changed
+36 -3
View File
@@ -67,15 +67,26 @@ describe('handleDaemonCommands', () => {
}
})
it('runs the runFn on normal startup', async () => {
it('runs the runFn on normal foreground startup without creating a PID file', async () => {
process.argv = ['node', 'script.js']
const runFn = vi.fn().mockResolvedValue(undefined)
await handleDaemonCommands(appName, runFn)
expect(runFn).toHaveBeenCalled()
expect(existsSync(pidFile)).toBe(true)
expect(readFileSync(pidFile, 'utf8').trim()).toBe(process.pid.toString())
expect(existsSync(pidFile)).toBe(false)
})
it('runs foreground startup even if a stale or conflicting PID file exists', async () => {
process.argv = ['node', 'script.js']
const runFn = vi.fn().mockResolvedValue(undefined)
mkdirSync(join(mockTempDir, '.shumai', 'pids'), { recursive: true })
writeFileSync(pidFile, '12345')
await handleDaemonCommands(appName, runFn)
expect(runFn).toHaveBeenCalled()
})
it('stops the process if stop command is passed', async () => {
@@ -122,4 +133,26 @@ describe('handleDaemonCommands', () => {
expect(spawn).toHaveBeenCalled()
expect(mockExit).toHaveBeenCalledWith(0)
})
it('runs and manages PID file when running as a daemonized child', async () => {
process.argv = ['node', 'script.js']
const originalEnv = process.env.SHUMAI_DAEMONIZED
process.env.SHUMAI_DAEMONIZED = 'true'
try {
const runFn = vi.fn().mockResolvedValue(undefined)
await handleDaemonCommands(appName, runFn)
expect(runFn).toHaveBeenCalled()
expect(existsSync(pidFile)).toBe(true)
expect(readFileSync(pidFile, 'utf8').trim()).toBe(process.pid.toString())
} finally {
if (originalEnv !== undefined) {
process.env.SHUMAI_DAEMONIZED = originalEnv
} else {
delete process.env.SHUMAI_DAEMONIZED
}
}
})
})
+19 -29
View File
@@ -17,6 +17,9 @@ const PID_DIR = join(SHUMAI_DIR, 'pids')
const LOG_DIR = join(SHUMAI_DIR, 'logs')
function isProcessRunning(pid: number): boolean {
if (pid <= 1) {
return false
}
try {
process.kill(pid, 0)
return true
@@ -35,7 +38,7 @@ async function stopProcess(appName: string, pidFile: string): Promise<boolean> {
}
const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10)
if (isNaN(pid)) {
if (isNaN(pid) || pid <= 1) {
console.log(`Invalid PID found in ${pidFile}. Cleaning up file.`)
try {
unlinkSync(pidFile)
@@ -180,18 +183,25 @@ export async function handleDaemonCommands(
appName: string,
runFn: () => Promise<void>,
): Promise<void> {
const pidFile = join(PID_DIR, `${appName}.pid`)
const logFile = join(LOG_DIR, `${appName}.log`)
// Ensure directories exist
mkdirSync(PID_DIR, { recursive: true })
mkdirSync(LOG_DIR, { recursive: true })
const args = process.argv.slice(2)
const isStop = args.includes('stop')
const isRestart = args.includes('restart')
const isLogs = args.includes('logs')
const isDaemon = args.includes('-d') && process.env.SHUMAI_DAEMONIZED !== 'true'
const isDaemonizedChild = process.env.SHUMAI_DAEMONIZED === 'true'
// Normal foreground startup: do not create, check, or track PID files
if (!isStop && !isRestart && !isLogs && !isDaemon && !isDaemonizedChild) {
await runFn()
return
}
const pidFile = join(PID_DIR, `${appName}.pid`)
const logFile = join(LOG_DIR, `${appName}.log`)
// Ensure directories exist for daemon commands
mkdirSync(PID_DIR, { recursive: true })
mkdirSync(LOG_DIR, { recursive: true })
if (isStop) {
await stopProcess(appName, pidFile)
@@ -216,27 +226,7 @@ export async function handleDaemonCommands(
process.exit(0)
}
// Normal Startup logic: check if already running
if (existsSync(pidFile)) {
const pid = parseInt(readFileSync(pidFile, 'utf8').trim(), 10)
if (!isNaN(pid) && pid !== process.pid) {
if (isProcessRunning(pid)) {
console.error(
`${appName} is already running (PID: ${pid}). Use '${appName} stop' or '${appName} restart'.`,
)
process.exit(1)
} else {
// Process is dead, clean up PID file
try {
unlinkSync(pidFile)
} catch {
// Ignore
}
}
}
}
// Write the PID file
// Daemonized child startup (SHUMAI_DAEMONIZED === 'true')
writeFileSync(pidFile, process.pid.toString(), 'utf8')
const cleanPidFile = () => {