将原 webhost 底座的后端、前端、工具等代码迁移至 electron-shell 目录,构建自包含的 Python 环境包,移除冗余的前端代码、旧的后端模块及相关依赖,更新版本号至 1.0.6,优化平台登录态预检逻辑,统一代码结构为单一真源,避免多副本维护问题。
424 lines
16 KiB
JavaScript
424 lines
16 KiB
JavaScript
// 插件执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。
|
||
// 对齐 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 fs = require("fs");
|
||
const path = require("path");
|
||
const config = require("./config");
|
||
const state = require("./state");
|
||
const scheduler = require("./scheduler");
|
||
const licensing = require("./licensing");
|
||
const runHistory = require("./run-history");
|
||
const platformAuth = require("./platform-auth");
|
||
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"}`;
|
||
}
|
||
|
||
// 平台登录态预检(HR/OA):插件执行前检测该账号的平台登录态,
|
||
// 失效时自动拉起自动登录(platform-auth.login,Python 子进程滑块自动化;
|
||
// cookies 实际有效时不会弹浏览器)。登录成功继续执行,失败则本次运行报错,
|
||
// 提示用户去个人中心手动登录(手动登录入口保留,不冲突)。
|
||
// 在(账号, 平台)命名空间锁内调用,天然避免并发双开登录浏览器。
|
||
const PLATFORM_LABELS = { hr: "HR 系统", oa: "OA 系统" };
|
||
async function ensurePlatformSession(plugin, runId, account) {
|
||
const pid = plugin.platform;
|
||
if (!pid || !PLATFORM_LABELS[pid]) return; // 无平台要求(或未知平台)直接执行
|
||
if (await platformAuth.isOnline(pid, account)) return; // 登录态有效,直接执行
|
||
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务");
|
||
const label = PLATFORM_LABELS[pid];
|
||
emitLog(runId, plugin.id, "INFO", `检测到${label}登录态失效,正在自动登录…(如需人工介入请观察弹出的浏览器窗口)`);
|
||
const r = await platformAuth.login(pid, account);
|
||
if (isUserStopped(runId)) throw new Error("用户已取消该排队任务"); // 登录期间用户点了停止
|
||
if (!r || !r.online) {
|
||
const msg = (r && r.message) || "登录未生效";
|
||
throw new Error(`${label}自动登录失败:${msg}。请在「个人中心 → 平台账号」手动登录后重试`);
|
||
}
|
||
emitLog(runId, plugin.id, "INFO", `${label}自动登录成功,开始执行插件`);
|
||
}
|
||
|
||
// 发布日志事件,并同步累积到"这一次运行"的记录里(结束后随运行历史落盘,供点击回放)
|
||
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 } —— 用于区分"谁触发的",落进运行历史
|
||
//
|
||
// 参数收口到插件侧:插件界面保存的配置(plugin_configs/<id>.json,单配置 blob)是参数权威来源。
|
||
// 插件界面手动执行会显式传全量 fields,原样使用;壳子侧入口(定时任务未选方案等)传空 fields 时
|
||
// 回退到该配置,避免"界面配置了一套、定时任务用 plugin.fields 默认值跑"的参数漂移。
|
||
function loadUiSavedFields(pluginId) {
|
||
try {
|
||
const raw = fs.readFileSync(path.join(config.PLUGIN_CONFIG_DIR, `${pluginId}.json`), "utf-8");
|
||
const v = JSON.parse(raw);
|
||
return v && typeof v === "object" && !Array.isArray(v) ? v : null;
|
||
} catch (_) {
|
||
return null; // 无保存配置/损坏:维持空 fields(插件走自身默认值)
|
||
}
|
||
}
|
||
|
||
// 环境包未就绪时的拒绝提示:环境包正在下载/解压时提示等待,云端有包但未装时引导状态栏安装
|
||
function throwEnvNotReady() {
|
||
let msg = "插件执行环境未就绪,暂时无法执行";
|
||
try {
|
||
const es = require("./env-sync").status();
|
||
if (es.dl && (es.dl.status === "downloading" || es.dl.status === "extracting")) {
|
||
msg = "环境包正在安装中(下载/解压),完成后即可执行,请稍候";
|
||
} else if (es.cloud_available) {
|
||
msg = "环境包未安装,请点击状态栏「环境」完成安装后再执行";
|
||
}
|
||
} catch (_) { /* env-sync 不可用时忽略 */ }
|
||
throw new Error(msg);
|
||
}
|
||
|
||
function submitRun(account, plugin, fields, opts) {
|
||
const o = opts && typeof opts === "object" ? opts : {};
|
||
const trigger = o.trigger === "schedule" ? "schedule" : "manual";
|
||
// 环境未就绪预防:提交前校验执行链路(入口脚本/解释器),缺失时直接拒绝并给可读提示,
|
||
// 避免子进程 spawn ENOENT 后用户只看到"执行进程异常退出(exit=-4058)且未返回结果"。
|
||
// 打包态无环境包且未显式配置解释器时也拒绝(系统 python 不可依赖)。
|
||
if (!fs.existsSync(config.runnerScript()) ||
|
||
(!process.env.PYTHON_EXE && !config.pythonEnvRoot() && config.IS_FROZEN)) {
|
||
throwEnvNotReady();
|
||
}
|
||
let effFields = fields && typeof fields === "object" && !Array.isArray(fields) ? fields : {};
|
||
if (Object.keys(effFields).length === 0) {
|
||
const saved = loadUiSavedFields(plugin.id);
|
||
if (saved) effFields = saved;
|
||
}
|
||
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, effFields, 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("用户已取消该排队任务");
|
||
}
|
||
// 平台登录态预检:HR/OA 失效时自动登录(手动登录入口保留)
|
||
await ensurePlatformSession(plugin, runId, account);
|
||
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 };
|