/** * 경로: /Users/jungkibong/Projects/langfuse/claude-desktop-cli/src/utils/process-helper.js * 파일: process-helper.js * 버전: v1.1.0 * Rationale: * - Electron PTY 및 child_process의 생명주기를 안전하게 관리하고 좀비 프로세스 누출을 방지하기 위한 프로세스 트리 종료 및 유효성 검사 유틸리티. * - Unix/macOS에서 음수 PID(-pid)를 이용한 SIGKILL 시 메인 일렉트론 프로세스 그룹 전체가 즉사하는 결함을 해결합니다. * - 동기식 execSync('lsof') 호출로 인한 UI 프리징을 차단하기 위해 비동기 getProcessCwdAsync와 1초 캐싱 TTL 레이어를 추가합니다. */ const { exec, execSync } = require('child_process'); // CWD 캐시 맵 및 TTL 설정 const cwdCache = new Map(); const CACHE_TTL_MS = 1000; // 1초 캐시 만료 시간 /** * 특정 PID를 가진 프로세스가 활성화 상태인지 확인합니다. * @param {number} pid - 프로세스 ID * @returns {boolean} */ function isProcessAlive(pid) { if (!pid) return false; const numericPid = parseInt(pid, 10); if (isNaN(numericPid) || !Number.isInteger(numericPid) || numericPid <= 0) return false; try { process.kill(numericPid, 0); return true; } catch (e) { return false; } } /** * 지정된 PID를 가진 프로세스와 그 하위의 모든 자식 프로세스 트리를 강제 종료합니다. * @param {number} pid - 프로세스 ID * @param {boolean} isSync - 동기 실행 여부 */ function killProcessTree(pid, isSync = false) { if (!pid) return; const numericPid = parseInt(pid, 10); if (isNaN(numericPid) || !Number.isInteger(numericPid) || numericPid <= 0) return; const isWin = process.platform === 'win32'; if (isWin) { const cmd = `taskkill /F /T /PID ${numericPid}`; if (isSync) { try { execSync(cmd, { stdio: 'ignore', windowsHide: true }); } catch (err) { // 이미 프로세스가 종료되었거나 접근이 거부된 경우 무시 } } else { exec(cmd, { windowsHide: true }, (err) => { // 백그라운드 태스크킬 오류 무시 }); } } else { // Unix/macOS: 음수 PID(-pid)로 SIGKILL을 날리면 메인 Electron 프로세스 그룹이 동반 폭사할 위험이 있습니다. // 대신 pgrep -P를 활용해 직접 하위 자식 PIDs를 조회하고 루프를 돌려 개별 종료합니다. try { let childrenRaw = ''; try { // pgrep -P를 동기/동적 실행하여 하위 자식 목록을 수집 childrenRaw = execSync(`pgrep -P ${numericPid}`, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'], timeout: 1000 }); } catch (e) { // 자식 프로세스가 없거나 pgrep 실패 시 무시 } if (childrenRaw) { const childPids = childrenRaw.split('\n') .map(p => parseInt(p.trim(), 10)) .filter(p => !isNaN(p) && p > 0); for (const childPid of childPids) { killProcessTree(childPid, isSync); // 재귀적 자식 정리 } } // 최종적으로 자기 자신 안전하게 SIGKILL process.kill(numericPid, 'SIGKILL'); } catch (err) { // 프로세스가 이미 종료된 경우 무시 } } } /** * 특정 PID를 가진 프로세스의 현재 작업 디렉토리(CWD)를 가져옵니다 (동기식 - 하위 호환성 전용). * @param {number} pid - 프로세스 ID * @returns {string|null} */ function getProcessCwd(pid) { if (!pid) return null; const numericPid = parseInt(pid, 10); if (isNaN(numericPid) || !Number.isInteger(numericPid) || numericPid <= 0) return null; const isWin = process.platform === 'win32'; try { if (isWin) { const cmd = `powershell.exe -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\"ProcessId = ${numericPid}\\").CurrentWorkingDirectory"`; const output = execSync(cmd, { encoding: 'utf8', timeout: 2000, windowsHide: true }).trim(); return output || null; } else { // Linux 전용 최적화: 외부 프로세스 스폰 없이 /proc//cwd 링크 직접 해석 if (process.platform === 'linux') { const fs = require('fs'); const procPath = `/proc/${numericPid}/cwd`; if (fs.existsSync(procPath)) { return fs.readlinkSync(procPath); } } const cmd = `lsof -a -d cwd -p ${numericPid} -Fn`; const output = execSync(cmd, { encoding: 'utf8', timeout: 2000 }); const lines = output.split('\n'); for (const line of lines) { if (line.startsWith('n')) { return line.slice(1).trim(); } } } } catch (e) { // 에러 발생 시 무시 } return null; } /** * 특정 PID 프로세스의 CWD를 비동기식으로 가져옵니다 (비블로킹 - 권장). * @param {number} pid - 프로세스 ID * @returns {Promise} */ function getProcessCwdAsync(pid) { if (!pid) return Promise.resolve(null); const numericPid = parseInt(pid, 10); if (isNaN(numericPid) || !Number.isInteger(numericPid) || numericPid <= 0) return Promise.resolve(null); const now = Date.now(); const cached = cwdCache.get(numericPid); if (cached && (now - cached.timestamp < CACHE_TTL_MS)) { return Promise.resolve(cached.path); } const isWin = process.platform === 'win32'; return new Promise((resolve) => { if (isWin) { const cmd = `powershell.exe -NoProfile -Command "(Get-CimInstance Win32_Process -Filter \\"ProcessId = ${numericPid}\\").CurrentWorkingDirectory"`; exec(cmd, { timeout: 1500, windowsHide: true }, (err, stdout) => { if (err || !stdout) { resolve(null); } else { const resolvedPath = stdout.trim(); cwdCache.set(numericPid, { path: resolvedPath, timestamp: Date.now() }); resolve(resolvedPath); } }); } else { // Linux 전용 최적화: /proc//cwd 링크 비동기/동기 결합 해석 if (process.platform === 'linux') { const fs = require('fs'); const procPath = `/proc/${pid}/cwd`; try { if (fs.existsSync(procPath)) { const resolvedPath = fs.readlinkSync(procPath); cwdCache.set(pid, { path: resolvedPath, timestamp: Date.now() }); resolve(resolvedPath); return; } } catch (procErr) { // proc 실패 시 lsof 폴백 가동 } } const cmd = `lsof -a -d cwd -p ${pid} -Fn`; exec(cmd, { timeout: 1500 }, (err, stdout) => { if (err || !stdout) { resolve(null); } else { const lines = stdout.split('\n'); for (const line of lines) { if (line.startsWith('n')) { const resolvedPath = line.slice(1).trim(); cwdCache.set(pid, { path: resolvedPath, timestamp: Date.now() }); resolve(resolvedPath); return; } } resolve(null); } }); } }); } /** * 현재 프로젝트 디렉토리나 환경 변수, 작업 디렉토리 기준에서 파이썬 가상환경(venv)을 검색하여 * 가상환경 내의 Python 실행 파일 경로와 필수 환경변수(PATH, VIRTUAL_ENV)를 설정한 env 복사본을 반환합니다. * 가상환경이 발견되지 않으면 시스템 기본 python3 또는 python을 반환합니다. * @param {string} projectDir - 프로젝트 디렉토리 경로 (옵션) * @returns {{pythonPath: string, env: Object}} */ function getPythonEnvConfig(projectDir = null) { const fs = require('fs'); const path = require('path'); const isWin = process.platform === 'win32'; const binDir = isWin ? 'Scripts' : 'bin'; const pythonExe = isWin ? 'python.exe' : 'python3'; let detectedVenv = null; // 1. process.env.VIRTUAL_ENV 환경 변수 검사 if (process.env.VIRTUAL_ENV && fs.existsSync(path.join(process.env.VIRTUAL_ENV, binDir, pythonExe))) { detectedVenv = process.env.VIRTUAL_ENV; } // 2. 지정된 projectDir 하위 .venv 또는 venv 디렉토리 검사 if (!detectedVenv && projectDir) { const candidates = [path.join(projectDir, '.venv'), path.join(projectDir, 'venv')]; for (const cand of candidates) { if (fs.existsSync(path.join(cand, binDir, pythonExe))) { detectedVenv = cand; break; } } } // 3. 현재 작업 디렉토리(process.cwd()) 하위 .venv 또는 venv 디렉토리 검사 if (!detectedVenv) { const candidates = [path.join(process.cwd(), '.venv'), path.join(process.cwd(), 'venv')]; for (const cand of candidates) { if (fs.existsSync(path.join(cand, binDir, pythonExe))) { detectedVenv = cand; break; } } } const env = Object.assign({}, process.env); let pythonPath = isWin ? 'python' : 'python3'; // 가상환경이 감지된 경우 환경변수를 격리 및 보정 처리 if (detectedVenv) { const venvBin = path.join(detectedVenv, binDir); pythonPath = path.join(venvBin, pythonExe); env.VIRTUAL_ENV = detectedVenv; // PATH 환경변수의 가장 맨 앞에 가상환경 bin 디렉토리를 주입하여 실행 파일 우선순위를 확보 env.PATH = venvBin + (isWin ? ';' : ':') + (process.env.PATH || ''); } return { pythonPath, env }; } module.exports = { isProcessAlive, killProcessTree, getProcessCwd, getProcessCwdAsync, getPythonEnvConfig };