-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathdaemonManager.js
More file actions
204 lines (176 loc) · 6.68 KB
/
daemonManager.js
File metadata and controls
204 lines (176 loc) · 6.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import {PythonShell} from 'python-shell';
import path from 'path';
import fs from 'fs';
import net from 'net';
import {promisify} from 'util';
import {exec} from 'child_process';
import {fileURLToPath} from "url";
const execAsync = promisify(exec);
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.join(__dirname, '../');
const hasWriteAccess = !process.env.VERCEL; // 非vercel环境才有write权限
function ensureDir(dir) {
if (hasWriteAccess) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, {recursive: true});
}
}
}
function log(logFile, level, msg) {
const line = `${new Date().toISOString()} [${level}] ${msg}\n`;
fs.appendFileSync(logFile, line);
if (level === 'ERROR' || level === 'CRITICAL') {
console.error(line.trim());
} else {
console.log(line.trim());
}
}
export class DaemonManager {
constructor(rootDir, daemonMode = 0) {
this.rootDir = rootDir;
this.daemonShell = null;
this.daemonFile = daemonMode ? 't4_daemon_lite.py' : 't4_daemon.py'
this.config = this.getDaemonConfig();
}
getDaemonConfig() {
const logsDir = path.join(this.rootDir, 'logs');
ensureDir(logsDir);
return {
pidFile: path.join(this.rootDir, 't4_daemon.pid'),
logFile: path.join(logsDir, 'daemon.log'),
daemonScript: path.join(this.rootDir, 'spider/py/core', this.daemonFile),
clientScript: path.join(this.rootDir, 'spider/py/core', 'bridge.py'),
host: '127.0.0.1',
port: 57570,
};
}
getPythonPath() {
if (process.env.PYTHON_PATH) return process.env.PYTHON_PATH;
if (process.env.VIRTUAL_ENV) {
return process.platform === 'win32'
? path.join(process.env.VIRTUAL_ENV, 'Scripts', 'python')
: path.join(process.env.VIRTUAL_ENV, 'bin', 'python');
}
return process.platform === 'win32' ? 'python.exe' : 'python3';
}
async isPythonAvailable() {
try {
const {stdout} = await execAsync(`${this.getPythonPath()} --version`);
return stdout.includes('Python');
} catch {
return false;
}
}
cleanupFiles() {
if (hasWriteAccess) {
try {
if (fs.existsSync(this.config.pidFile)) fs.unlinkSync(this.config.pidFile);
} catch {
}
}
}
isDaemonRunning() {
if (!fs.existsSync(this.config.pidFile)) return false;
const pid = parseInt(fs.readFileSync(this.config.pidFile, 'utf8'), 10);
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
async waitForServer(timeoutMs = 5000) {
const {host, port} = this.config;
const deadline = Date.now() + timeoutMs;
return new Promise((resolve, reject) => {
const tryConnect = () => {
const socket = net.connect({host, port}, () => {
socket.end();
resolve(true);
});
socket.on('error', () => {
if (Date.now() > deadline) {
reject(new Error('守护进程未能在超时时间内启动'));
} else {
setTimeout(tryConnect, 300);
}
});
};
tryConnect();
});
}
async startDaemon() {
if (this.isDaemonRunning()) {
log(this.config.logFile, 'INFO', 'Python 守护进程已在运行');
return;
}
if (!await this.isPythonAvailable()) {
log(this.config.logFile, 'INFO', '当前环境不支持Python,跳过启动守护进程');
return;
}
this.cleanupFiles();
const options = {
mode: 'text',
pythonPath: this.getPythonPath(),
pythonOptions: ['-u'],
scriptPath: path.dirname(this.config.daemonScript),
env: {PYTHONIOENCODING: 'utf-8'},
args: [
'--pid-file', this.config.pidFile,
'--log-file', this.config.logFile,
'--host', this.config.host,
'--port', this.config.port,
],
};
log(this.config.logFile, 'INFO', `正在启动 Python 守护进程 [${this.daemonFile}]...`);
const daemonShell = new PythonShell(path.basename(this.config.daemonScript), options);
this.daemonShell = daemonShell;
daemonShell.on('message', (m) => log(this.config.logFile, 'INFO', `[守护进程] ${m}`));
daemonShell.on('stderr', (m) => log(this.config.logFile, 'INFO', `[守护进程] ${m}`));
daemonShell.on('error', (err) => log(this.config.logFile, 'CRITICAL', `错误: ${err.message}`));
daemonShell.on('close', (code, signal) => {
if (code !== null && code !== undefined) {
log(this.config.logFile, 'INFO', `[ON CLOSE]守护进程关闭,退出码: ${code}`);
} else {
log(this.config.logFile, 'WARN', `守护进程异常退出(可能被 kill),未返回退出码`);
}
this.cleanupFiles();
this.daemonShell = null;
});
daemonShell.childProcess.on('spawn', () => {
if (hasWriteAccess) {
fs.writeFileSync(this.config.pidFile, daemonShell.childProcess.pid.toString());
}
log(this.config.logFile, 'INFO', `守护进程启动成功,PID: ${daemonShell.childProcess.pid}`);
});
await this.waitForServer();
}
async stopDaemon() {
if (!this.isDaemonRunning()) {
log(this.config.logFile, 'INFO', '没有运行的守护进程');
return;
}
log(this.config.logFile, 'INFO', '正在停止守护进程...');
const pid = parseInt(fs.readFileSync(this.config.pidFile, 'utf8'), 10);
if (process.platform === 'win32') {
exec(`taskkill /PID ${pid} /T /F`);
} else {
try {
process.kill(pid, 'SIGTERM');
} catch {
}
}
await new Promise((resolve) => setTimeout(resolve, 3000));
if (this.isDaemonRunning()) {
log(this.config.logFile, 'WARN', '守护进程未退出,强制终止...');
try {
process.kill(pid, 'SIGKILL');
} catch {
}
}
this.cleanupFiles();
this.daemonShell = null;
log(this.config.logFile, 'INFO', '守护进程已停止');
}
}
export const daemon = new DaemonManager(rootDir, Number(process.env.daemonMode) || 0);