Files
37duAutomation/desktop/electron-shell/electron/runner.js
T

357 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 插件执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。
// 对齐 Python runner.py 完整执行链:spawn python plugin_runner(★ 逐字节协议)
// → stdin 单行 JSON fields → stdout JSON 事件行 → 超时整树强杀(taskkill /T /F)。
"use strict";
const { spawn } = require("child_process");
const readline = require("readline");
const crypto = require("crypto");
const config = require("./config");
const state = require("./state");
const scheduler = require("./scheduler");
const licensing = require("./licensing");
const runHistory = require("./run-history");
const { HUB } = require("./hub");
const { makeLogger } = require("./logger");
const logger = makeLogger("runner");
// 手动停止登记:run_id → 停止标记
const _USER_STOPPED = new Set();
// run_id → kill 函数(执行中,供整树强杀)
const _ACTIVE = new Map();
function isUserStopped(runId) {
return _USER_STOPPED.has(runId);
}
function treeKill(pid) {
// Windows 整树强杀(含 DrissionPage 浏览器等孙进程);非 Windows 直接 kill 子进程组
try {
if (process.platform === "win32") {
const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
windowsHide: true,
stdio: "ignore",
detached: true,
});
killer.unref();
} else {
try {
process.kill(-pid, "SIGKILL");
} catch (e) {
process.kill(pid, "SIGKILL");
}
}
} catch (e) {
logger.warning(`整树强杀失败 pid=${pid}: ${e.message}`);
}
}
function terminateRun(runId) {
_USER_STOPPED.add(runId);
const kill = _ACTIVE.get(runId);
if (!kill) return false; // 尚未拉起执行子进程(排队中)或已结束
try {
kill();
} catch (e) {
/* 忽略 */
}
return true;
}
// 平台命名空间并发闸键:按(账号, 平台)隔离,保护该账号各自的平台登录态 cookies
function nsKey(account, platform) {
return `${account || "anon"}:${platform || "local"}`;
}
// 发布日志事件,并同步累积到"这一次运行"的记录里(结束后随运行历史落盘,供点击回放)
function emitLog(runId, pluginId, level, msg) {
const text = String(msg === undefined || msg === null ? "" : msg);
state.appendRunLog(runId, {
t: new Date().toLocaleTimeString("zh-CN", { hour12: false }),
level: level || "INFO",
msg: text,
});
HUB.publish({ t: "log", run_id: runId, plugin_id: pluginId, level: level || "INFO", msg: text });
}
// 结束一次运行:写终态 → 落盘运行历史 → 广播 run_done。
// 所有结束路径(队列拒绝 / 队列异常 / 子进程收尾)共用,避免漏记历史。
function finishRun(runId, plugin, status, error, summary) {
const ok = status === "done";
const finished = Date.now() / 1000;
const run = state.RUNS.get(runId) || {};
const durationSec = run.started ? Math.max(0, Math.round(finished - run.started)) : 0;
state.setRun(runId, {
status,
error: ok ? "" : error || "",
summary: summary || "",
finished,
duration_sec: durationSec,
});
runHistory.append({
run_id: runId,
account: run.account || "",
plugin_id: plugin.id,
name: run.name || plugin.name || plugin.id,
version: run.version || plugin.version || "0",
trigger: run.trigger || "manual",
schedule_id: run.schedule_id || "",
status,
ok,
error: ok ? "" : error || "",
summary: summary || "",
started: run.started || 0,
finished,
duration_sec: durationSec,
logs: Array.isArray(run.logs) ? run.logs : [],
});
HUB.publish({
t: "run_done",
run_id: runId,
plugin_id: plugin.id,
name: run.name || plugin.name || plugin.id,
trigger: run.trigger || "manual",
ok,
error: ok ? "" : error || "",
duration_sec: durationSec,
summary: summary || "",
});
}
// 提交一次插件运行(手动 POST /api/runs 与定时任务共用入口);立即返回 run_id。
// opts: { trigger: "manual" | "schedule", schedule_id } —— 用于区分"谁触发的",落进运行历史
function submitRun(account, plugin, fields, opts) {
const o = opts && typeof opts === "object" ? opts : {};
const trigger = o.trigger === "schedule" ? "schedule" : "manual";
const runId = crypto.randomBytes(16).toString("hex");
state.registerRun(runId, {
status: "running",
account,
plugin_id: plugin.id,
name: plugin.name || plugin.id,
version: plugin.version || "0",
trigger,
schedule_id: o.schedule_id || "",
started: Date.now() / 1000,
result: null,
error: null,
logs: [],
});
HUB.publish({
t: "run_start",
run_id: runId,
plugin_id: plugin.id,
name: plugin.name || plugin.id,
trigger,
at: new Date().toLocaleTimeString("zh-CN", { hour12: false }),
});
licensing.report(account, "", plugin.id, plugin.version || "0", "start");
void runQueued(plugin, fields, runId, account);
return runId;
}
async function runQueued(plugin, fields, runId, account) {
try {
// 平台命名空间并发闸:按(账号, 平台)串行(保护各账号各自的平台登录态 cookies)
if (scheduler.nsLocked(nsKey(account, plugin.platform))) {
emitLog(runId, plugin.id, "INFO", `同平台任务执行中,排队等待(命名空间 ${nsKey(account, plugin.platform)})…`);
}
await scheduler.withNsLock(nsKey(account, plugin.platform), async () => {
const startFn = async () => {
if (isUserStopped(runId)) {
// 排队期间用户已点停止:不真正拉起插件
throw new Error("用户已取消该排队任务");
}
await startChild(plugin, fields, runId, account);
return runId;
};
const r = await scheduler.requestStart(account, plugin.id, plugin.version || "0", startFn);
if (!r.ok) {
const err = isUserStopped(runId) ? "用户手动强制停止" : r.error;
if (isUserStopped(runId)) _USER_STOPPED.delete(runId);
finishRun(runId, plugin, "error", err, "");
}
});
} catch (e) {
logger.error(`运行队列异常:${e.message}`);
finishRun(runId, plugin, "error", `运行队列异常:${e.message}`, "");
}
}
// 拉起执行子进程:子进程 spawn 成功后立即 resolve(runId)(requestStart 随即标记 running);
// 执行结束(close)后异步落终态 + 上报 + 回空闲。
function startChild(plugin, fields, runId, account) {
return new Promise((resolve, reject) => {
const timeout = config.RUN_TIMEOUT;
// 执行环境解析:便携环境包(python-env)优先 → 经 job_guard(Job Object 内存上限
// + 整树托管)拉起 plugin_runner;无环境包(dev 直接 .venv)保持原直拉链路。
// 两种模式协议逐字节一致(plugin_runner stdout JSON 事件行经 stdio 原样透传)。
const python = config.pythonExe();
const envRoot = config.pythonEnvRoot();
const guard = config.jobGuardScript();
const baseArgs = ["-u", config.runnerScript(), "--plugin", plugin.id, "--run", runId];
if (state.ALLOWED !== null) {
baseArgs.push("--allowed", [...state.ALLOWED].sort().join(","));
}
let cmd;
let cwd;
if (envRoot && guard) {
// 环境包模式:python -u job_guard.py --mem <MB> --timeout <s> -- python -u plugin_runner.py ...
cmd = [
python, "-u", guard,
"--mem", String(config.RUN_MAX_MEM_MB),
"--timeout", String(timeout),
"--", python, ...baseArgs,
];
cwd = envRoot;
} else {
cmd = [python, ...baseArgs];
cwd = envRoot || config.REPO_ROOT;
}
let child;
try {
child = spawn(cmd[0], cmd.slice(1), {
cwd,
windowsHide: true,
env: {
...process.env,
PYTHONIOENCODING: "utf-8",
PYTHONUTF8: "1",
PLATFORM_ACCOUNT: account || "",
// 环境包插件加载器据此定位插件根(dev 直拉模式传了也无害)
PLUGINS_ROOT: config.pluginRoot(),
},
stdio: ["pipe", "pipe", "pipe"],
});
} catch (e) {
reject(new Error(`拉起执行子进程失败: ${e.message}`));
return;
}
let resolved = false;
const killFn = () => treeKill(child.pid);
_ACTIVE.set(runId, killFn);
const result = {};
const publish = (ev) => {
const t = ev.ev;
if (t === "log") {
emitLog(runId, plugin.id, ev.level, ev.msg);
} else if (t === "progress") {
HUB.publish({ t: "progress", run_id: runId, plugin_id: plugin.id, pct: Math.max(0, Math.min(100, parseInt(ev.pct, 10) || 0)) });
} else if (t === "result") {
Object.assign(result, ev);
}
};
const rlOut = readline.createInterface({ input: child.stdout });
rlOut.on("line", (line) => {
const s = String(line).trim();
if (!s) return;
try {
const ev = JSON.parse(s);
if (ev && typeof ev === "object" && ev.ev) publish(ev);
} catch (e) {
/* 非 JSON 行忽略 */
}
});
const rlErr = readline.createInterface({ input: child.stderr });
rlErr.on("line", (line) => {
const s = String(line).trim();
if (s) {
emitLog(runId, plugin.id, "ERROR", s);
}
});
// 写 fields(单行 JSON,UTF-8)并关闭 stdin
try {
child.stdin.write(Buffer.from(JSON.stringify(fields || {}), "utf-8"));
child.stdin.end();
} catch (e) {
/* 子进程可能已退出 */
}
let timedOut = false;
let finalized = false;
let timer = null;
const finalize = (code, spawnErr) => {
if (finalized) return;
finalized = true;
if (timer) clearTimeout(timer);
_ACTIVE.delete(runId);
const hasResult = result && Object.keys(result).length > 0;
let status;
let error;
if (hasResult) {
status = result.ok ? "done" : "error";
error = result.error || "";
} else if (spawnErr) {
status = "error";
error = spawnErr;
} else if (isUserStopped(runId)) {
status = "error";
error = "用户手动强制停止";
} else if (timedOut) {
status = "error";
error = `插件执行超时(${timeout}s)已强制终止`;
} else {
status = "error";
error = `执行进程异常退出(exit=${code})且未返回结果`;
}
state.setRun(runId, { result: hasResult ? result.result : null });
finishRun(
runId,
plugin,
status,
status === "done" ? "" : error,
hasResult ? ((result.result || {}).summary || "") : ""
);
_USER_STOPPED.delete(runId);
scheduler.markDone(plugin.id, runId); // 单活槽位回空闲并唤醒排队请求
reportRun(plugin, runId); // 运行上报(联网实时/离线暂存补报)
};
child.once("spawn", () => {
resolved = true;
timer = setTimeout(() => {
timedOut = true;
logger.warning(`插件执行超时(${timeout}s)已强制终止:${plugin.id}`);
killFn();
}, timeout * 1000);
resolve(runId);
});
child.on("error", (err) => {
if (!resolved) {
_ACTIVE.delete(runId);
reject(new Error(`拉起执行子进程失败: ${err.message}`));
return;
}
finalize(null, `执行子进程异常: ${err.message}`);
});
child.on("close", (code) => {
finalize(code, null);
});
});
}
function reportRun(plugin, runId) {
try {
const run = state.RUNS.get(runId) || {};
const account = run.account || "";
const status = run.status === "done" ? "done" : run.status === "running" ? "running" : "error";
const msg = run.error || "";
const duration = run.started ? Math.floor(Date.now() / 1000 - run.started) : 0;
licensing.report(account, "", plugin.id, run.version || "", status, msg, duration);
} catch (e) {
logger.warning(`运行上报失败:${e.message}`);
}
}
module.exports = { submitRun, terminateRun, isUserStopped };