From 7f88f0c96d819badea4110f4694c1607165f8e78 Mon Sep 17 00:00:00 2001 From: kicer Date: Sun, 6 Sep 2026 08:49:39 +0800 Subject: [PATCH] =?UTF-8?q?executor=20=E5=88=86=E7=BA=A7=E6=97=A5=E5=BF=97?= =?UTF-8?q?=20+=20core=20=E7=99=BB=E5=BD=95=E6=97=A5=E5=BF=97=EF=BC=9Aexec?= =?UTF-8?q?utor=20=E6=96=B0=E5=A2=9E=20EXECUTOR=5FLOG=5FLEVEL=EF=BC=88debu?= =?UTF-8?q?g|info|warn|error|none=EF=BC=8C=E9=BB=98=E8=AE=A4=20info?= =?UTF-8?q?=EF=BC=8C=E8=AF=AD=E4=B9=89=E5=AF=B9=E9=BD=90=20core=20log.js?= =?UTF-8?q?=EF=BC=89=EF=BC=8Cdebug=20=E6=97=B6=E9=80=90=E6=9D=A1=E6=89=93?= =?UTF-8?q?=E5=8D=B0=E4=B8=8E=20core=20=E7=9A=84=E5=AE=8C=E6=95=B4?= =?UTF-8?q?=E4=BA=A4=E4=BA=92=EF=BC=88=E8=AF=B7=E6=B1=82=E8=A1=8C=E3=80=81?= =?UTF-8?q?/exec=20=E8=AF=B7=E6=B1=82=E4=BD=93=E3=80=81=E6=AF=8F=E6=9D=A1?= =?UTF-8?q?=20SSE=20=E4=B8=8B=E5=8F=91=E5=B8=A7=E3=80=81JSON=20=E5=93=8D?= =?UTF-8?q?=E5=BA=94=EF=BC=8C=E8=B6=85=E9=95=BF=E6=88=AA=E6=96=AD=202000?= =?UTF-8?q?=20=E5=AD=97=E7=AC=A6=EF=BC=89=EF=BC=8Cinfo=20=E4=BF=9D?= =?UTF-8?q?=E7=95=99=20listening/start/exit=20=E7=AD=89=E5=85=B3=E9=94=AE?= =?UTF-8?q?=E5=8A=A8=E4=BD=9C=EF=BC=8C=E9=89=B4=E6=9D=83=E6=8B=92=E7=BB=9D?= =?UTF-8?q?=E5=8D=87=20warn=E3=80=81spawn=20=E9=94=99=E8=AF=AF=E4=B8=8E?= =?UTF-8?q?=E5=A4=84=E7=90=86=E5=BC=82=E5=B8=B8=E5=8D=87=20error=EF=BC=9BD?= =?UTF-8?q?ockerfile/compose=20=E6=8E=A5=E7=BA=BF=E7=8E=AF=E5=A2=83?= =?UTF-8?q?=E5=8F=98=E9=87=8F=E3=80=82core=20=E5=9C=A8=20/api/login=20?= =?UTF-8?q?=E8=A1=A5=E7=94=A8=E6=88=B7=E8=BF=9B=E5=85=A5=E6=97=A5=E5=BF=97?= =?UTF-8?q?=EF=BC=9A=E6=88=90=E5=8A=9F=20info=EF=BC=88=E5=90=AB=20ip?= =?UTF-8?q?=EF=BC=89=E3=80=81=E5=AF=86=E7=A0=81=E9=94=99=E8=AF=AF=20warn?= =?UTF-8?q?=EF=BC=9Blogin=5Frestore=20=E8=87=AA=E5=8A=A8=E6=81=A2=E5=A4=8D?= =?UTF-8?q?=E8=AE=B0=20debug=20=E9=98=B2=20APK=20=E5=86=B7=E5=90=AF?= =?UTF-8?q?=E5=8A=A8=E5=88=B7=E5=B1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/server/auth.js | 5 ++++ docker-compose.yml | 3 ++ executor/Dockerfile | 5 +++- executor/server.js | 67 ++++++++++++++++++++++++++++++++++++++------- 4 files changed, 69 insertions(+), 11 deletions(-) diff --git a/app/server/auth.js b/app/server/auth.js index 257cb53..56d9a7a 100644 --- a/app/server/auth.js +++ b/app/server/auth.js @@ -124,9 +124,12 @@ function createAuth(cfg) { const { user, password } = req.body || {}; const expect = validUsers.get(String(user || '')); if (expect == null || !timingEqual(expect, String(password == null ? '' : password))) { + log.warn('auth', '登录失败(用户名或密码错误):user=' + String(user || '-') + ' ip=' + (req.ip || '-')); return res.status(401).json({ error: '用户名或密码错误' }); } setAuthCookie(res, String(user)); + // 用户进入系统的唯一关口:记一条 info,便于对照后续该用户的会话/消息日志 + log.info('auth', '用户 ' + String(user) + ' 登录 ip=' + (req.ip || '-')); // token 一并回给前端:WebView 封装 APK 杀进程后 cookie 可能没落盘, // 前端存 localStorage,下次进登录页用 /api/login_restore 自动恢复。 res.json({ ok: true, user: String(user), token: signToken(String(user), Date.now() + ttlMs, secret) }); @@ -139,6 +142,8 @@ function createAuth(cfg) { const data = readToken(h.startsWith('Bearer ') ? h.slice(7).trim() : '', secret); if (!data || !validUsers.has(data.user)) return res.status(401).json({ error: '登录态已失效,请重新登录' }); setAuthCookie(res, data.user); // 重新签发,顺带续期 + // APK 冷启动常触发,属自动恢复而非手动登录,记 debug 避免刷屏 + log.debug('auth', '用户 ' + data.user + ' 恢复登录态(login_restore)'); res.json({ ok: true, user: data.user }); }); diff --git a/docker-compose.yml b/docker-compose.yml index 9d12485..6b48d3d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -38,6 +38,9 @@ services: - PORT=9000 # 与 agent-core 侧设成同一个值即启用调用鉴权(可选): - EXECUTOR_TOKEN=whoami + # 日志等级:debug|info|warn|error|none(默认 info); + # debug 会把与 core 的完整交互打印出来(请求、/exec 请求体、每条 SSE 帧、JSON 响应): + - EXECUTOR_LOG_LEVEL=debug cap_drop: - SYS_ADMIN - DAC_OVERRIDE diff --git a/executor/Dockerfile b/executor/Dockerfile index 5d6cfae..e8f6f0d 100644 --- a/executor/Dockerfile +++ b/executor/Dockerfile @@ -32,8 +32,11 @@ WORKDIR /app COPY server.js ./ EXPOSE 9000 +# EXECUTOR_LOG_LEVEL:日志等级 debug|info|warn|error|none(默认 info)。 +# debug 会把与 core 的完整交互逐条打印(请求行、/exec 请求体、每条 SSE 帧、JSON 响应)。 ENV PORT=9000 \ EXECUTOR_ROOTS=/workspace \ - EXECUTOR_CWD=/workspace/tasks + EXECUTOR_CWD=/workspace/tasks \ + EXECUTOR_LOG_LEVEL=info CMD ["node", "server.js"] diff --git a/executor/server.js b/executor/server.js index a65fe5a..ef7b287 100644 --- a/executor/server.js +++ b/executor/server.js @@ -17,6 +17,10 @@ // - timeout_ms 夹在 [1s, EXECUTOR_MAX_TIMEOUT_MS](默认 30 分钟); // - stdout/stderr 各自按 max_output_chars 截断(默认 EXECUTOR_MAX_OUTPUT_CHARS=200000),超限后丢弃剩余输出,exit 事件带 truncated 标记。 // +// 日志:EXECUTOR_LOG_LEVEL=debug|info|warn|error|none(默认 info,none/off 全静默),分级语义与 core 的 log.js 一致。 +// info = 关键动作(启动/进程 start/exit/取消/关闭);debug = 额外打印与 core 的完整交互: +// 每个请求行、/exec 请求体、每条 SSE 下发帧、每个 JSON 响应(超长内容截断显示)。改环境配置后重启容器生效。 +// // 约定:core 与 executor 把同一份宿主机 ./tasks、./skills 挂到相同容器路径(/workspace/*), // 所以 core 下发的任务目录 cwd 在 executor 内原样可用。 @@ -37,8 +41,42 @@ const BODY_LIMIT = 1024 * 1024; // /exec 请求体上限 1MB const runs = new Map(); // id -> { child, killedBy, started_at, cwd } -// 统一日志(ISO 时间戳 + 前缀) -function log(...args) { console.log(new Date().toISOString(), '[executor]', ...args); } +// ---------- 分级日志(格式与 core 的 log.js 对齐: [] [executor] )---------- +const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 }; +function parseLevel(l) { + const s = String(l || 'info').trim().toLowerCase(); + if (s === 'none' || s === 'off') return Infinity; + return LEVELS[s] == null ? LEVELS.info : LEVELS[s]; +} +const LOG_LEVEL = parseLevel(process.env.EXECUTOR_LOG_LEVEL); + +const pad = (n, w) => String(n).padStart(w || 2, '0'); +function stamp() { + const d = new Date(); + return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' + + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) + '.' + pad(d.getMilliseconds(), 3); +} +function emit(fn, level, args) { + if (LEVELS[level] < LOG_LEVEL) return; + const rest = Array.prototype.slice.call(args); + const head = stamp() + ' [' + level + '] [executor]'; + if (typeof rest[0] === 'string') rest[0] = head + ' ' + rest[0]; + else rest.unshift(head); + fn.apply(console, rest); +} +const log = { + debug() { emit(console.log, 'debug', arguments); }, + info() { emit(console.log, 'info', arguments); }, + warn() { emit(console.warn, 'warn', arguments); }, + error() { emit(console.error, 'error', arguments); }, +}; + +// debug 交互日志的文本截断:保留可读性,超长只留头部并标注丢弃量。 +function brief(s, n) { + s = String(s); + n = n || 2000; + return s.length > n ? s.slice(0, n) + '…(+' + (s.length - n) + ')' : s; +} // 常量时间比较,避免通过响应耗时猜 token function tokenOk(req) { @@ -51,6 +89,7 @@ function tokenOk(req) { } function send(res, status, obj) { + log.debug('resp', status, brief(JSON.stringify(obj))); const body = JSON.stringify(obj); res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); res.end(body); @@ -90,11 +129,15 @@ function killGroup(entry) { catch (_) { try { child.kill('SIGKILL'); } catch (__) { /* 已退出 */ } } } -function sseWrite(res, obj) { res.write('data: ' + JSON.stringify(obj) + '\n\n'); } +function sseWrite(res, obj) { + log.debug('sse →', brief(JSON.stringify(obj))); + res.write('data: ' + JSON.stringify(obj) + '\n\n'); +} async function handleExec(req, res) { let args; try { args = await readJsonBody(req); } catch (e) { return send(res, 400, { error: e.message }); } + log.debug('exec ←', brief(JSON.stringify(args))); const command = String(args.command || ''); if (!command.trim()) return send(res, 400, { error: 'command 必填' }); @@ -126,7 +169,7 @@ async function handleExec(req, res) { const entry = { child, killedBy: null, started_at: Date.now(), cwd, timer: null }; runs.set(id, entry); - log('start', id, 'pid=' + child.pid, 'cwd=' + cwd, 'timeout=' + timeout + 'ms', JSON.stringify(command).slice(0, 200)); + log.info('start', id, 'pid=' + child.pid, 'cwd=' + cwd, 'timeout=' + timeout + 'ms', JSON.stringify(command).slice(0, 200)); res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', @@ -166,10 +209,10 @@ async function handleExec(req, res) { type: 'exit', code, signal: child.signalCode, killed_by: entry.killedBy, stdout_chars: out.stdout, stderr_chars: out.stderr, truncated: out.truncated, }); - log('exit ', id, 'code=' + code, 'killed_by=' + entry.killedBy, 'out=' + out.stdout + 'B err=' + out.stderr + 'B'); + log.info('exit ', id, 'code=' + code, 'killed_by=' + entry.killedBy, 'out=' + out.stdout + 'B err=' + out.stderr + 'B'); res.end(); } - child.on('error', err => { entry.killedBy = entry.killedBy || 'spawn_error'; log('spawn error', id, err.message); streamChunk('err', Buffer.from('spawn 失败:' + err.message + '\n')); finish(-1); }); + child.on('error', err => { entry.killedBy = entry.killedBy || 'spawn_error'; log.error('spawn error', id, err.message); streamChunk('err', Buffer.from('spawn 失败:' + err.message + '\n')); finish(-1); }); child.on('close', (code) => finish(entry.killedBy ? -1 : (code === null ? -1 : code))); } @@ -182,17 +225,21 @@ function handleKill(req, res, id) { } const server = http.createServer(async (req, res) => { + log.debug('req ', req.method, req.url); const url = new URL(req.url, 'http://x'); const seg = url.pathname.split('/').filter(Boolean); if (url.pathname === '/health') return send(res, 200, { ok: true, time: Date.now(), running: Array.from(runs.entries()).map(([id, e]) => ({ id, pid: e.child.pid, cwd: e.cwd, started_at: e.started_at })) }); - if (!tokenOk(req)) return send(res, 401, { error: '缺少或错误的 Authorization: Bearer token' }); + if (!tokenOk(req)) { + log.warn('auth', '拒绝(token 缺失或错误)', req.method, url.pathname); + return send(res, 401, { error: '缺少或错误的 Authorization: Bearer token' }); + } try { if (req.method === 'POST' && url.pathname === '/exec') return await handleExec(req, res); if (req.method === 'DELETE' && seg.length === 2 && seg[0] === 'exec') return handleKill(req, res, seg[1]); } catch (e) { - log('处理异常:', e.message); + log.error('处理异常:', e.message); if (!res.headersSent) send(res, 500, { error: e.message }); else res.end(); return; } @@ -200,12 +247,12 @@ const server = http.createServer(async (req, res) => { }); server.listen(PORT, () => { - log('listening on ' + PORT + ' roots=' + ROOTS.join(', ') + ' default_cwd=' + DEFAULT_CWD + ' auth=' + (TOKEN ? 'token' : 'off')); + log.info('listening on ' + PORT + ' roots=' + ROOTS.join(', ') + ' default_cwd=' + DEFAULT_CWD + ' auth=' + (TOKEN ? 'token' : 'off') + ' log_level=' + (process.env.EXECUTOR_LOG_LEVEL || 'info')); }); // 退出前杀掉所有在跑的进程组,防容器停止后遗留 function shutdown(sig) { - log('收到 ' + sig + ',停止服务(杀掉 ' + runs.size + ' 个运行中任务)'); + log.info('收到 ' + sig + ',停止服务(杀掉 ' + runs.size + ' 个运行中任务)'); for (const entry of runs.values()) { entry.killedBy = 'shutdown'; killGroup(entry); } server.close(() => process.exit(0)); setTimeout(() => process.exit(0), 3000).unref();