@maiyunnet/kebab 9.29.6 → 10.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/abox/proxy.js +24 -2
- package/abox/response.js +36 -17
- package/abox/session-login.js +1 -13
- package/doc/kebab-rag.md +1522 -1034
- package/index.d.ts +12 -1
- package/index.js +1 -1
- package/lib/ai.d.ts +4 -0
- package/lib/ai.js +32 -16
- package/lib/cookie.d.ts +2 -0
- package/lib/cookie.js +47 -45
- package/lib/core.d.ts +26 -0
- package/lib/core.js +36 -13
- package/lib/cron.js +1 -8
- package/lib/crypto.js +20 -6
- package/lib/db/conn.js +1 -0
- package/lib/fs.js +78 -31
- package/lib/kv.d.ts +182 -79
- package/lib/kv.js +518 -214
- package/lib/s3.d.ts +2 -0
- package/lib/s3.js +14 -27
- package/lib/session.d.ts +7 -0
- package/lib/session.js +23 -2
- package/lib/socket.d.ts +4 -1
- package/lib/socket.js +1 -0
- package/lib/sql.d.ts +0 -5
- package/lib/sql.js +48 -12
- package/lib/text.d.ts +10 -5
- package/lib/text.js +22 -12
- package/lib/turnstile.d.ts +6 -0
- package/lib/turnstile.js +16 -9
- package/lib/undici.d.ts +7 -1
- package/lib/undici.js +72 -36
- package/lib/ws.d.ts +1 -1
- package/lib/ws.js +85 -128
- package/lib/zip.js +46 -45
- package/package.json +2 -2
- package/sys/child.js +178 -146
- package/sys/cmd.js +196 -197
- package/sys/ctr.d.ts +14 -14
- package/sys/ctr.js +145 -59
- package/sys/master.js +111 -80
- package/sys/mod.d.ts +8 -2
- package/sys/mod.js +23 -11
- package/sys/monitor/files.d.ts +2 -1
- package/sys/monitor/files.js +77 -21
- package/sys/monitor/watchdog.d.ts +7 -0
- package/sys/monitor/watchdog.js +311 -203
- package/sys/monitor.d.ts +59 -54
- package/sys/monitor.js +742 -681
- package/sys/route.d.ts +4 -4
- package/sys/route.js +93 -52
- package/www/example/ctr/test.js +8 -8
package/sys/monitor.js
CHANGED
|
@@ -1,113 +1,108 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Project: Kebab, User: JianSuoQiYue
|
|
3
3
|
* Date: 2026-02-07
|
|
4
|
-
* Last: 2026-
|
|
5
|
-
* ---
|
|
6
|
-
* ---
|
|
4
|
+
* Last: 2026-11-24
|
|
5
|
+
* --- 性能监控库,持续监测 CPU/内存/事件循环延迟,保存现场快照和诊断文件 ---
|
|
6
|
+
* --- 配套看门狗 Worker 线程,在主线程完全阻塞时独立采样并抓栈 ---
|
|
7
7
|
*/
|
|
8
|
+
// --- 系统 ---
|
|
8
9
|
import * as os from 'os';
|
|
9
10
|
import * as v8 from 'v8';
|
|
10
11
|
import * as inspector from 'inspector';
|
|
11
12
|
import * as perfHooks from 'perf_hooks';
|
|
12
13
|
import * as workerThreads from 'worker_threads';
|
|
14
|
+
// --- 库和定义 ---
|
|
13
15
|
import * as kebab from '#kebab/index.js';
|
|
14
16
|
import * as lCore from '#kebab/lib/core.js';
|
|
15
17
|
import * as lText from '#kebab/lib/text.js';
|
|
16
18
|
import * as lTime from '#kebab/lib/time.js';
|
|
17
19
|
import * as lFs from '#kebab/lib/fs.js';
|
|
20
|
+
// --- 固定参数与共享内存槽位 ---
|
|
21
|
+
/** --- 主线程采样间隔(ms) --- */
|
|
22
|
+
const INTERVAL = 1_000;
|
|
23
|
+
/** --- CPU Profile 采集时长(ms) --- */
|
|
24
|
+
const PROFILE_MS = 5_000;
|
|
25
|
+
/** --- 同一持续异常重复采集重型诊断的冷却时间(ms) --- */
|
|
26
|
+
const DIAG_COOLDOWN = 60_000;
|
|
27
|
+
/** --- 单次快照最多保留的活跃/近期请求条数 --- */
|
|
28
|
+
const MAX_REQS = 100;
|
|
29
|
+
/** --- 看门狗轮询间隔(ms) --- */
|
|
30
|
+
const WD_INTERVAL = 1_000;
|
|
31
|
+
/** --- 看门狗同一阻塞的重复告警冷却(秒) --- */
|
|
32
|
+
const WD_COOLDOWN = 30;
|
|
33
|
+
/** --- 看门狗异常退出后的重启延迟(ms) --- */
|
|
34
|
+
const WD_RETRY_MS = 5_000;
|
|
35
|
+
/** --- 共享内存槽位:0-心跳 ms, 1-调试标志, 2-Inspector 锁, 3-同步诊断中, 4-已保存阻塞现场的心跳 --- */
|
|
36
|
+
const SLOT_HB = 0;
|
|
37
|
+
const SLOT_DEBUG = 1;
|
|
38
|
+
const SLOT_LOCK = 2;
|
|
39
|
+
const SLOT_DIAG = 3;
|
|
40
|
+
const SLOT_SAVED = 4;
|
|
18
41
|
// --- 阈值配置 ---
|
|
19
42
|
/** --- CPU 使用率阈值,100 代表占满一个逻辑核心 --- */
|
|
20
|
-
let
|
|
21
|
-
/** ---
|
|
22
|
-
let
|
|
23
|
-
/** ---
|
|
24
|
-
let
|
|
25
|
-
/** ---
|
|
26
|
-
let
|
|
27
|
-
/** ---
|
|
28
|
-
|
|
29
|
-
/** ---
|
|
30
|
-
let
|
|
31
|
-
/** --- CPU Profile 采集时长,单位 ms --- */
|
|
32
|
-
const PROFILE_DURATION = 5_000;
|
|
33
|
-
/** --- 同一持续异常重复采集的间隔,单位 ms;新事件或指标复发不受此限制 --- */
|
|
34
|
-
const DIAGNOSTIC_COOLDOWN = 60_000;
|
|
35
|
-
/** --- 单次快照或日志最多输出的活跃请求详情数 --- */
|
|
36
|
-
const MAX_ACTIVE_REQUEST_DETAILS = 100;
|
|
43
|
+
let cpuLimit = 80;
|
|
44
|
+
/** --- 内存 RSS 阈值(MB),0 表示自动推算 --- */
|
|
45
|
+
let memLimit = 0;
|
|
46
|
+
/** --- 事件循环 P99 延迟阈值(ms) --- */
|
|
47
|
+
let eloopLimit = 500;
|
|
48
|
+
/** --- 同一指标持续超阈值的确认时长(ms) --- */
|
|
49
|
+
let spikeMs = 10_000;
|
|
50
|
+
/** --- 主线程心跳中断的阻塞确认时长(ms) --- */
|
|
51
|
+
let blockMs = 5_000;
|
|
52
|
+
/** --- 内存超阈值时是否自动采集堆快照 --- */
|
|
53
|
+
let heapSnap = false;
|
|
37
54
|
// --- 内部状态 ---
|
|
38
|
-
/** ---
|
|
55
|
+
/** --- 周期检查定时器 --- */
|
|
39
56
|
let timer = null;
|
|
40
|
-
/** ---
|
|
41
|
-
let
|
|
42
|
-
/** ---
|
|
43
|
-
let
|
|
44
|
-
/** --- 周期检查的上次系统各核 CPU 时间快照 --- */
|
|
45
|
-
let lastCheckOsCpus = null;
|
|
46
|
-
/** --- 对外快照的上次 CPU 累计用量 --- */
|
|
47
|
-
let lastSnapshotCpuUsage = null;
|
|
48
|
-
/** --- 对外快照的上次 CPU 采样时间戳 --- */
|
|
49
|
-
let lastSnapshotCpuTime = 0;
|
|
50
|
-
/** --- 对外快照的上次系统各核 CPU 时间快照 --- */
|
|
51
|
-
let lastSnapshotOsCpus = null;
|
|
57
|
+
/** --- 周期检查的 CPU 采样基准 --- */
|
|
58
|
+
let checkMark = null;
|
|
59
|
+
/** --- 对外 getSnapshot 的 CPU 采样基准 --- */
|
|
60
|
+
let snapMark = null;
|
|
52
61
|
/** --- 事件循环延迟直方图 --- */
|
|
53
|
-
let
|
|
54
|
-
/** ---
|
|
55
|
-
let
|
|
56
|
-
'cpu': null,
|
|
62
|
+
let eloop = null;
|
|
63
|
+
/** --- 各指标首次超阈值的单调时钟时间(ms),不能跨指标累计 --- */
|
|
64
|
+
let spikeAt = {
|
|
65
|
+
'cpu': null,
|
|
66
|
+
'mem': null,
|
|
67
|
+
'eloop': null,
|
|
57
68
|
};
|
|
58
|
-
/** ---
|
|
59
|
-
let
|
|
60
|
-
/** ---
|
|
61
|
-
let
|
|
62
|
-
/** ---
|
|
63
|
-
let
|
|
64
|
-
/** --- 同步 Report/HeapSnapshot
|
|
65
|
-
let
|
|
66
|
-
/**
|
|
67
|
-
* --- 检测当前是否处于调试模式(以 --inspect 启动或 IDE 调试器已连接) ---
|
|
68
|
-
* @returns 是否处于调试模式
|
|
69
|
-
*/
|
|
70
|
-
function isDebugMode() {
|
|
71
|
-
return !!inspector.url();
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* --- 获取单调时钟毫秒数,避免系统校时影响 CPU 比例和心跳 ---
|
|
75
|
-
* @returns 单调时钟毫秒数
|
|
76
|
-
*/
|
|
77
|
-
function clockMs() {
|
|
78
|
-
return Number(process.hrtime.bigint() / 1000000n);
|
|
79
|
-
}
|
|
80
|
-
// --- 看门狗相关 ---
|
|
69
|
+
/** --- 请求追踪自增序号 --- */
|
|
70
|
+
let reqSeq = 0;
|
|
71
|
+
/** --- 是否正在执行重型诊断采集 --- */
|
|
72
|
+
let diagBusy = false;
|
|
73
|
+
/** --- 是否正在通过看门狗采集 CPU Profile --- */
|
|
74
|
+
let profBusy = false;
|
|
75
|
+
/** --- 同步 Report/HeapSnapshot 产生的阻塞标记,下一采样周期据此跳过误判 --- */
|
|
76
|
+
let diagSkip = false;
|
|
81
77
|
/** --- 看门狗 Worker 实例 --- */
|
|
82
|
-
let
|
|
83
|
-
/** ---
|
|
84
|
-
let
|
|
78
|
+
let wd = null;
|
|
79
|
+
/** --- 心跳共享内存 --- */
|
|
80
|
+
let shmBuf = null;
|
|
85
81
|
/** --- 心跳共享内存视图 --- */
|
|
86
|
-
let
|
|
87
|
-
/** --- 主线程持续未更新心跳的确认时间,单位 ms --- */
|
|
88
|
-
let watchdogThreshold = 5_000;
|
|
89
|
-
/** --- 看门狗检测间隔,单位 ms --- */
|
|
90
|
-
const WATCHDOG_INTERVAL = 1_000;
|
|
91
|
-
/** --- 看门狗告警冷却时间,持续阻塞时不会每次都写日志,单位秒 --- */
|
|
92
|
-
const WATCHDOG_COOLDOWN = 30;
|
|
93
|
-
/** --- 看门狗异常退出后的重启延迟,单位 ms --- */
|
|
94
|
-
const WATCHDOG_RESTART_DELAY = 5_000;
|
|
82
|
+
let shm = null;
|
|
95
83
|
/** --- 看门狗重启定时器 --- */
|
|
96
|
-
let
|
|
84
|
+
let wdRetryTimer = null;
|
|
97
85
|
/** --- 活跃请求池 --- */
|
|
98
|
-
const
|
|
99
|
-
/** ---
|
|
100
|
-
const
|
|
101
|
-
/** ---
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
const watchdogIncidents = new Map();
|
|
105
|
-
/** --- 当前持续异常及其上次重型诊断时间 --- */
|
|
86
|
+
const reqs = new Map();
|
|
87
|
+
/** --- 最近一分钟完成的请求(最多 MAX_REQS 条) --- */
|
|
88
|
+
const recent = [];
|
|
89
|
+
/** --- 最近 60 秒的资源采样历史 --- */
|
|
90
|
+
const history = [];
|
|
91
|
+
/** --- 当前进行中的持续异常事件 --- */
|
|
106
92
|
let incident = null;
|
|
107
|
-
|
|
108
|
-
let
|
|
109
|
-
/** ---
|
|
110
|
-
let
|
|
93
|
+
/** --- 上次触发重型诊断的单调时钟(ms) --- */
|
|
94
|
+
let lastDiagMs = 0;
|
|
95
|
+
/** --- 上次落盘事件摘要的时间戳(ms) --- */
|
|
96
|
+
let lastSaveMs = 0;
|
|
97
|
+
/** --- 最近一次收到的看门狗诊断结果 --- */
|
|
98
|
+
let lastWdDiag = null;
|
|
99
|
+
/** --- 等待看门狗回传结果的事件表,按心跳值索引 --- */
|
|
100
|
+
const wdPending = new Map();
|
|
101
|
+
/** --- 事件摘要串行写入链,避免并发落盘互相覆盖 --- */
|
|
102
|
+
let saveChain = Promise.resolve();
|
|
103
|
+
// ================
|
|
104
|
+
// --- 公开 API ---
|
|
105
|
+
// ================
|
|
111
106
|
/**
|
|
112
107
|
* --- 启动性能监控 ---
|
|
113
108
|
* @param opt 可选的阈值配置
|
|
@@ -117,78 +112,74 @@ export function start(opt) {
|
|
|
117
112
|
if (timer) {
|
|
118
113
|
return true;
|
|
119
114
|
}
|
|
120
|
-
|
|
121
|
-
const
|
|
122
|
-
const
|
|
123
|
-
const
|
|
124
|
-
const
|
|
125
|
-
|
|
115
|
+
// --- 校验配置参数 ---
|
|
116
|
+
const cpu = opt?.cpu ?? 80;
|
|
117
|
+
const mem = opt?.mem ?? 0;
|
|
118
|
+
const lag = opt?.eloop ?? 500;
|
|
119
|
+
const dur = opt?.duration ?? 10_000;
|
|
120
|
+
const blk = opt?.blocked ?? 5_000;
|
|
121
|
+
if (!Number.isFinite(cpu) || cpu <= 0) {
|
|
126
122
|
return false;
|
|
127
123
|
}
|
|
128
|
-
if (!Number.isFinite(
|
|
124
|
+
if (!Number.isFinite(mem) || mem < 0) {
|
|
129
125
|
return false;
|
|
130
126
|
}
|
|
131
|
-
if (!Number.isFinite(
|
|
127
|
+
if (!Number.isFinite(lag) || lag <= 0) {
|
|
132
128
|
return false;
|
|
133
129
|
}
|
|
134
|
-
if (!Number.isFinite(
|
|
130
|
+
if (!Number.isFinite(dur) || dur < INTERVAL) {
|
|
135
131
|
return false;
|
|
136
132
|
}
|
|
137
|
-
if (!Number.isFinite(
|
|
133
|
+
if (!Number.isFinite(blk) || blk < INTERVAL) {
|
|
138
134
|
return false;
|
|
139
135
|
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
sampleHistory.length = 0;
|
|
166
|
-
recentRequests.length = 0;
|
|
136
|
+
// --- 应用阈值,内存为 0 时按容器上限和 V8 堆上限推算默认值 ---
|
|
137
|
+
cpuLimit = cpu;
|
|
138
|
+
memLimit = mem;
|
|
139
|
+
eloopLimit = lag;
|
|
140
|
+
spikeMs = dur;
|
|
141
|
+
blockMs = blk;
|
|
142
|
+
heapSnap = opt?.heapSnapshot ?? false;
|
|
143
|
+
if (memLimit === 0) {
|
|
144
|
+
const cgroup = process.constrainedMemory();
|
|
145
|
+
const sysMem = cgroup > 0 ? Math.min(cgroup, os.totalmem()) : os.totalmem();
|
|
146
|
+
const heapMax = v8.getHeapStatistics().heap_size_limit;
|
|
147
|
+
memLimit = Math.floor(Math.min(sysMem * 0.8, heapMax * 0.9) / 1024 / 1024);
|
|
148
|
+
}
|
|
149
|
+
// --- 重置采样基准与运行状态 ---
|
|
150
|
+
const t = nowMs();
|
|
151
|
+
const mark = {
|
|
152
|
+
'usage': process.cpuUsage(),
|
|
153
|
+
'time': t,
|
|
154
|
+
'cpus': os.cpus(),
|
|
155
|
+
};
|
|
156
|
+
checkMark = mark;
|
|
157
|
+
snapMark = { ...mark };
|
|
158
|
+
spikeAt = { 'cpu': null, 'mem': null, 'eloop': null };
|
|
159
|
+
history.length = 0;
|
|
160
|
+
recent.length = 0;
|
|
167
161
|
incident = null;
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
// ---
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
Atomics.store(
|
|
176
|
-
Atomics.store(
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
eloopHistogram.enable();
|
|
162
|
+
lastWdDiag = null;
|
|
163
|
+
wdPending.clear();
|
|
164
|
+
diagSkip = false;
|
|
165
|
+
lastDiagMs = 0;
|
|
166
|
+
// --- 初始化心跳共享内存、延迟直方图、定时器和看门狗 ---
|
|
167
|
+
shmBuf = new SharedArrayBuffer(40);
|
|
168
|
+
shm = new BigInt64Array(shmBuf);
|
|
169
|
+
Atomics.store(shm, SLOT_HB, BigInt(t));
|
|
170
|
+
Atomics.store(shm, SLOT_DEBUG, isDebug() ? 1n : 0n);
|
|
171
|
+
eloop = perfHooks.monitorEventLoopDelay({ 'resolution': 20 });
|
|
172
|
+
eloop.enable();
|
|
180
173
|
timer = setInterval(check, INTERVAL);
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
lCore.debug(`[MONITOR] [PARENT] [${process.pid}] Started, CPU Threshold: ${cpuThreshold}%, MEM Threshold: ${memThreshold}MB, ELOOP Threshold: ${eloopThreshold}ms`);
|
|
174
|
+
startWd();
|
|
175
|
+
lCore.debug(`[MONITOR] [PARENT] [${process.pid}] Started, CPU Threshold: ${cpuLimit}%, MEM Threshold: ${memLimit}MB, ELOOP Threshold: ${eloopLimit}ms`);
|
|
184
176
|
return true;
|
|
185
177
|
}
|
|
186
178
|
/**
|
|
187
179
|
* --- 停止性能监控 ---
|
|
188
|
-
* @returns 无返回值
|
|
189
180
|
*/
|
|
190
181
|
export function stop() {
|
|
191
|
-
|
|
182
|
+
wdPending.clear();
|
|
192
183
|
if (incident) {
|
|
193
184
|
incident.endedAt = Date.now();
|
|
194
185
|
incident.endReason = 'stopped';
|
|
@@ -199,109 +190,26 @@ export function stop() {
|
|
|
199
190
|
clearInterval(timer);
|
|
200
191
|
timer = null;
|
|
201
192
|
}
|
|
202
|
-
if (
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
}
|
|
206
|
-
if (
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
lastSnapshotCpuUsage = null;
|
|
223
|
-
lastSnapshotCpuTime = 0;
|
|
224
|
-
lastSnapshotOsCpus = null;
|
|
225
|
-
spikeSince = { 'cpu': null, 'mem': null, 'eloop': null };
|
|
226
|
-
heartbeatBuffer = null;
|
|
227
|
-
heartbeatView = null;
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* --- 启动看门狗 Worker 线程,独立事件循环监控主线程心跳 ---
|
|
231
|
-
* --- 实现代码见 monitor/watchdog.ts ---
|
|
232
|
-
* @returns 无返回值
|
|
233
|
-
*/
|
|
234
|
-
function startWatchdog() {
|
|
235
|
-
if (!heartbeatBuffer) {
|
|
236
|
-
return;
|
|
237
|
-
}
|
|
238
|
-
const workerUrl = new URL('./monitor/watchdog.js', import.meta.url);
|
|
239
|
-
try {
|
|
240
|
-
const worker = new workerThreads.Worker(workerUrl, {
|
|
241
|
-
'workerData': {
|
|
242
|
-
'buffer': heartbeatBuffer,
|
|
243
|
-
'logDir': kebab.LOG_CWD,
|
|
244
|
-
'logFormat': lCore.globalConfig.logFormat ?? 'jsonl',
|
|
245
|
-
'pid': process.pid,
|
|
246
|
-
'threshold': watchdogThreshold,
|
|
247
|
-
'cooldown': WATCHDOG_COOLDOWN,
|
|
248
|
-
'interval': WATCHDOG_INTERVAL,
|
|
249
|
-
'profileDuration': PROFILE_DURATION,
|
|
250
|
-
'requests': Array.from(activeRequests.entries()),
|
|
251
|
-
},
|
|
252
|
-
});
|
|
253
|
-
watchdog = worker;
|
|
254
|
-
// --- 不阻止进程退出 ---
|
|
255
|
-
worker.unref();
|
|
256
|
-
worker.on('message', (message) => {
|
|
257
|
-
if (watchdog !== worker || message.type !== 'diagnostic') {
|
|
258
|
-
return;
|
|
259
|
-
}
|
|
260
|
-
lastWatchdogDiagnostic = message;
|
|
261
|
-
const pending = watchdogIncidents.get(message.heartbeat);
|
|
262
|
-
if (pending) {
|
|
263
|
-
pending.result.status = `watchdog-${message.status}`;
|
|
264
|
-
pending.result.files = [`${message.dir}/blocked-event.json`, ...message.files];
|
|
265
|
-
pending.result.errors.push(...message.errors);
|
|
266
|
-
watchdogIncidents.delete(message.heartbeat);
|
|
267
|
-
saveIncident(pending.event);
|
|
268
|
-
}
|
|
269
|
-
});
|
|
270
|
-
worker.on('error', (err) => {
|
|
271
|
-
lCore.log({}, `WATCHDOG_ERROR ${lText.stringifyError(err)}`, '-monitor');
|
|
272
|
-
lCore.display('[MONITOR] Watchdog error', err);
|
|
273
|
-
});
|
|
274
|
-
worker.on('exit', (exitCode) => {
|
|
275
|
-
if (exitCode !== 0 && timer) {
|
|
276
|
-
lCore.debug(`[MONITOR] Watchdog exited: ${exitCode}`);
|
|
277
|
-
}
|
|
278
|
-
// --- 仅当当前 watchdog 仍是本实例时才置空,避免 stop→start 重启时竞态 ---
|
|
279
|
-
if (watchdog === worker) {
|
|
280
|
-
watchdog = null;
|
|
281
|
-
}
|
|
282
|
-
scheduleWatchdogRestart();
|
|
283
|
-
});
|
|
284
|
-
lCore.debug(`[MONITOR] [THREAD] [${process.pid}] Watchdog started`);
|
|
285
|
-
}
|
|
286
|
-
catch (e) {
|
|
287
|
-
lCore.log({}, `WATCHDOG_START_FAILED ${lText.stringifyError(e)}`, '-monitor');
|
|
288
|
-
lCore.display('[MONITOR] Failed to start watchdog', e);
|
|
289
|
-
scheduleWatchdogRestart();
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
/**
|
|
293
|
-
* --- 看门狗异常退出后延迟重启,避免失去阻塞检测能力 ---
|
|
294
|
-
* @returns 无返回值
|
|
295
|
-
*/
|
|
296
|
-
function scheduleWatchdogRestart() {
|
|
297
|
-
if (!timer || watchdog || watchdogRestartTimer) {
|
|
298
|
-
return;
|
|
299
|
-
}
|
|
300
|
-
watchdogRestartTimer = setTimeout(() => {
|
|
301
|
-
watchdogRestartTimer = null;
|
|
302
|
-
startWatchdog();
|
|
303
|
-
}, WATCHDOG_RESTART_DELAY);
|
|
304
|
-
watchdogRestartTimer.unref();
|
|
193
|
+
if (eloop) {
|
|
194
|
+
eloop.disable();
|
|
195
|
+
eloop = null;
|
|
196
|
+
}
|
|
197
|
+
if (wd) {
|
|
198
|
+
wd.terminate().catch(() => { });
|
|
199
|
+
wd = null;
|
|
200
|
+
}
|
|
201
|
+
if (wdRetryTimer) {
|
|
202
|
+
clearTimeout(wdRetryTimer);
|
|
203
|
+
wdRetryTimer = null;
|
|
204
|
+
}
|
|
205
|
+
reqs.clear();
|
|
206
|
+
recent.length = 0;
|
|
207
|
+
history.length = 0;
|
|
208
|
+
checkMark = null;
|
|
209
|
+
snapMark = null;
|
|
210
|
+
spikeAt = { 'cpu': null, 'mem': null, 'eloop': null };
|
|
211
|
+
shmBuf = null;
|
|
212
|
+
shm = null;
|
|
305
213
|
}
|
|
306
214
|
/**
|
|
307
215
|
* --- 注册一个活跃请求,返回追踪 ID ---
|
|
@@ -311,574 +219,727 @@ function scheduleWatchdogRestart() {
|
|
|
311
219
|
*/
|
|
312
220
|
export function track(url, method) {
|
|
313
221
|
const now = Date.now();
|
|
314
|
-
const id = `${++
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
// ---
|
|
318
|
-
'url':
|
|
222
|
+
const id = `${++reqSeq}-${now}`;
|
|
223
|
+
const qIdx = url.search(/[?#]/u);
|
|
224
|
+
const item = {
|
|
225
|
+
// --- 去掉查询参数,避免把凭据或隐私写入诊断文件 ---
|
|
226
|
+
'url': qIdx === -1 ? url : url.slice(0, qIdx),
|
|
319
227
|
'method': method,
|
|
320
228
|
'start': now,
|
|
321
229
|
'startCpu': process.cpuUsage(),
|
|
322
230
|
'startMem': process.memoryUsage.rss(),
|
|
231
|
+
};
|
|
232
|
+
reqs.set(id, item);
|
|
233
|
+
wd?.postMessage({
|
|
234
|
+
'type': 'request',
|
|
235
|
+
'id': id,
|
|
236
|
+
'request': item,
|
|
323
237
|
});
|
|
324
|
-
watchdog?.postMessage({ 'type': 'request', id, 'request': activeRequests.get(id) });
|
|
325
238
|
return id;
|
|
326
239
|
}
|
|
327
240
|
/**
|
|
328
241
|
* --- 移除已完成的请求追踪 ---
|
|
329
242
|
* @param id 追踪 ID
|
|
330
|
-
* @returns 无返回值
|
|
331
243
|
*/
|
|
332
244
|
export function untrack(id) {
|
|
333
|
-
const req =
|
|
245
|
+
const req = reqs.get(id);
|
|
334
246
|
if (req) {
|
|
335
247
|
const now = Date.now();
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
* --- 获取请求存续期间的进程资源增量,不能据此认定请求独占资源 ---
|
|
346
|
-
* @param req 追踪中的请求
|
|
347
|
-
* @param now 当前时间戳 ms
|
|
348
|
-
* @param cpu 当前进程 CPU 累计用量
|
|
349
|
-
* @param rss 当前进程 RSS
|
|
350
|
-
* @returns 请求快照
|
|
351
|
-
*/
|
|
352
|
-
function snapshotRequest(req, now, cpu, rss) {
|
|
353
|
-
return {
|
|
354
|
-
'url': req.url, 'method': req.method, 'duration': now - req.start,
|
|
355
|
-
'cpuUser': cpu.user - req.startCpu.user, 'cpuSystem': cpu.system - req.startCpu.system,
|
|
356
|
-
'memDelta': rss - req.startMem,
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
/**
|
|
360
|
-
* --- 限制最近请求的保留时长及条数 ---
|
|
361
|
-
* @param now 当前时间戳 ms
|
|
362
|
-
* @returns 无返回值
|
|
363
|
-
*/
|
|
364
|
-
function trimRecentRequests(now) {
|
|
365
|
-
while (recentRequests.length > MAX_ACTIVE_REQUEST_DETAILS ||
|
|
366
|
-
recentRequests.length && now - (recentRequests[0].completedAt ?? 0) > 60_000) {
|
|
367
|
-
recentRequests.shift();
|
|
248
|
+
const done = snapReq(req, now, process.cpuUsage(), process.memoryUsage.rss());
|
|
249
|
+
done.completedAt = now;
|
|
250
|
+
recent.push(done);
|
|
251
|
+
trimRecent(now);
|
|
252
|
+
wd?.postMessage({
|
|
253
|
+
'type': 'complete',
|
|
254
|
+
'id': id,
|
|
255
|
+
'request': done,
|
|
256
|
+
});
|
|
368
257
|
}
|
|
258
|
+
reqs.delete(id);
|
|
369
259
|
}
|
|
370
260
|
/**
|
|
371
261
|
* --- 获取当前资源快照 ---
|
|
372
262
|
* @returns 资源与请求快照
|
|
373
263
|
*/
|
|
374
264
|
export function getSnapshot() {
|
|
375
|
-
const
|
|
376
|
-
const
|
|
377
|
-
|
|
378
|
-
let
|
|
379
|
-
if (
|
|
380
|
-
|
|
381
|
-
const
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
}
|
|
388
|
-
lastSnapshotCpuUsage = cpuUsage;
|
|
389
|
-
lastSnapshotCpuTime = cpuTime;
|
|
390
|
-
// --- 计算系统总 CPU 使用率 ---
|
|
391
|
-
const osCpus = os.cpus();
|
|
392
|
-
const cpuOs = getOsCpuPercent(lastSnapshotOsCpus, osCpus);
|
|
393
|
-
lastSnapshotOsCpus = osCpus;
|
|
394
|
-
return createSnapshot(Math.round(cpuProcess * 100) / 100, cpuOs);
|
|
395
|
-
}
|
|
396
|
-
/**
|
|
397
|
-
* --- 组装资源与请求快照,不推进对外查询的 CPU 采样基准 ---
|
|
398
|
-
* @param cpuProcess 当前采样窗口进程 CPU 百分比
|
|
399
|
-
* @param cpuOs 当前采样窗口系统 CPU 百分比
|
|
400
|
-
* @returns 资源快照
|
|
401
|
-
*/
|
|
402
|
-
function createSnapshot(cpuProcess, cpuOs) {
|
|
403
|
-
const mem = process.memoryUsage();
|
|
404
|
-
const heapStats = v8.getHeapStatistics();
|
|
405
|
-
const cpuUsage = process.cpuUsage();
|
|
406
|
-
const now = Date.now();
|
|
407
|
-
// --- 计算事件循环延迟(P99,纳秒转毫秒) ---
|
|
408
|
-
let eloopLag = 0;
|
|
409
|
-
let eloopMax = 0;
|
|
410
|
-
if (eloopHistogram) {
|
|
411
|
-
eloopLag = Math.round(eloopHistogram.percentile(99) / 1_000_000);
|
|
412
|
-
eloopMax = Math.round(eloopHistogram.max / 1_000_000);
|
|
413
|
-
}
|
|
414
|
-
// --- 收集活跃请求 ---
|
|
415
|
-
const requests = [];
|
|
416
|
-
for (const [, req] of activeRequests) {
|
|
417
|
-
if (requests.length >= MAX_ACTIVE_REQUEST_DETAILS) {
|
|
418
|
-
break;
|
|
419
|
-
}
|
|
420
|
-
requests.push(snapshotRequest(req, now, cpuUsage, mem.rss));
|
|
421
|
-
}
|
|
422
|
-
trimRecentRequests(now);
|
|
423
|
-
return {
|
|
424
|
-
'pid': process.pid,
|
|
425
|
-
'time': now,
|
|
426
|
-
'cpuProcess': Math.round(cpuProcess * 100) / 100,
|
|
427
|
-
'cpuOs': cpuOs,
|
|
428
|
-
'mem': {
|
|
429
|
-
'rss': mem.rss,
|
|
430
|
-
'heapTotal': mem.heapTotal,
|
|
431
|
-
'heapUsed': mem.heapUsed,
|
|
432
|
-
'external': mem.external,
|
|
433
|
-
'arrayBuffers': mem.arrayBuffers,
|
|
434
|
-
},
|
|
435
|
-
'heap': {
|
|
436
|
-
'totalSize': heapStats.total_heap_size,
|
|
437
|
-
'usedSize': heapStats.used_heap_size,
|
|
438
|
-
'sizeLimit': heapStats.heap_size_limit,
|
|
439
|
-
},
|
|
440
|
-
'osMem': {
|
|
441
|
-
'total': os.totalmem(),
|
|
442
|
-
'free': os.freemem(),
|
|
443
|
-
},
|
|
444
|
-
'eloopLag': eloopLag,
|
|
445
|
-
'eloopMax': eloopMax,
|
|
446
|
-
'activeRequests': requests,
|
|
447
|
-
'activeCount': activeRequests.size,
|
|
448
|
-
'recentRequests': [...recentRequests],
|
|
449
|
-
};
|
|
265
|
+
const usage = process.cpuUsage();
|
|
266
|
+
const t = nowMs();
|
|
267
|
+
const cpus = os.cpus();
|
|
268
|
+
let cpuProc = 0;
|
|
269
|
+
if (snapMark && t > snapMark.time) {
|
|
270
|
+
const dtUs = (t - snapMark.time) * 1_000;
|
|
271
|
+
const diff = (usage.user - snapMark.usage.user) + (usage.system - snapMark.usage.system);
|
|
272
|
+
cpuProc = (diff / dtUs) * 100;
|
|
273
|
+
}
|
|
274
|
+
const cpuOs = calcOsCpu(snapMark?.cpus ?? null, cpus);
|
|
275
|
+
snapMark = { 'usage': usage, 'time': t, 'cpus': cpus };
|
|
276
|
+
return buildSnap(Math.round(cpuProc * 100) / 100, cpuOs);
|
|
450
277
|
}
|
|
278
|
+
// ==========================
|
|
279
|
+
// --- 周期检查与异常记录 ---
|
|
280
|
+
// ==========================
|
|
451
281
|
/**
|
|
452
|
-
* ---
|
|
453
|
-
* @returns 无返回值
|
|
282
|
+
* --- 每秒周期检查:采样资源、更新心跳、判定持续异常与恢复 ---
|
|
454
283
|
*/
|
|
455
284
|
function check() {
|
|
456
|
-
|
|
285
|
+
// --- 计算本周期 CPU 占比并刷新共享心跳 ---
|
|
286
|
+
const usage = process.cpuUsage();
|
|
457
287
|
const now = Date.now();
|
|
458
|
-
const
|
|
459
|
-
const
|
|
460
|
-
const
|
|
461
|
-
let
|
|
462
|
-
if (
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
288
|
+
const t = nowMs();
|
|
289
|
+
const prevT = checkMark?.time ?? 0;
|
|
290
|
+
const dt = t - prevT;
|
|
291
|
+
let cpuPct = 0;
|
|
292
|
+
if (checkMark && dt > 0) {
|
|
293
|
+
const diff = (usage.user - checkMark.usage.user) + (usage.system - checkMark.usage.system);
|
|
294
|
+
cpuPct = (diff / (dt * 1_000)) * 100;
|
|
295
|
+
}
|
|
296
|
+
const cpus = os.cpus();
|
|
297
|
+
const cpuOs = calcOsCpu(checkMark?.cpus ?? null, cpus);
|
|
298
|
+
checkMark = { 'usage': usage, 'time': t, 'cpus': cpus };
|
|
299
|
+
if (shm) {
|
|
300
|
+
Atomics.store(shm, SLOT_HB, BigInt(t));
|
|
301
|
+
Atomics.store(shm, SLOT_DEBUG, isDebug() ? 1n : 0n);
|
|
302
|
+
}
|
|
303
|
+
// --- 生成快照并同步给看门狗 ---
|
|
304
|
+
const snap = buildSnap(Math.round(cpuPct * 100) / 100, cpuOs);
|
|
305
|
+
wd?.postMessage({
|
|
306
|
+
'type': 'snapshot',
|
|
307
|
+
'snapshot': snap,
|
|
308
|
+
'logFormat': lCore.globalConfig.logFormat ?? 'jsonl',
|
|
309
|
+
});
|
|
310
|
+
eloop?.reset();
|
|
311
|
+
// --- 调试或同步诊断窗口跳过告警判定 ---
|
|
312
|
+
if (isDebug()) {
|
|
313
|
+
spikeAt = { 'cpu': null, 'mem': null, 'eloop': null };
|
|
482
314
|
return;
|
|
483
315
|
}
|
|
484
|
-
if (
|
|
485
|
-
|
|
486
|
-
// --- 已确认事件继续等待正常采样恢复,未确认的连续性重新计时 ---
|
|
316
|
+
if (diagSkip) {
|
|
317
|
+
diagSkip = false;
|
|
487
318
|
if (!incident?.reasons.includes('PROC_CPU')) {
|
|
488
|
-
|
|
319
|
+
spikeAt.cpu = null;
|
|
489
320
|
}
|
|
490
321
|
if (!incident?.reasons.includes('MEM')) {
|
|
491
|
-
|
|
322
|
+
spikeAt.mem = null;
|
|
492
323
|
}
|
|
493
324
|
if (!incident?.reasons.includes('ELOOP_LAG')) {
|
|
494
|
-
|
|
325
|
+
spikeAt.eloop = null;
|
|
495
326
|
}
|
|
496
327
|
return;
|
|
497
328
|
}
|
|
329
|
+
// --- 记录最近 60 秒采样历史 ---
|
|
498
330
|
const sample = {
|
|
499
|
-
'time': now,
|
|
500
|
-
'
|
|
501
|
-
'
|
|
502
|
-
'
|
|
331
|
+
'time': now,
|
|
332
|
+
'elapsed': dt,
|
|
333
|
+
'cpu': snap.cpuProcess,
|
|
334
|
+
'cpuOs': cpuOs,
|
|
335
|
+
'rss': snap.mem.rss,
|
|
336
|
+
'heapUsed': snap.mem.heapUsed,
|
|
337
|
+
'external': snap.mem.external,
|
|
338
|
+
'arrayBuffers': snap.mem.arrayBuffers,
|
|
339
|
+
'eloop': snap.eloopLag,
|
|
340
|
+
'eloopMax': snap.eloopMax,
|
|
503
341
|
};
|
|
504
|
-
|
|
505
|
-
while (
|
|
506
|
-
|
|
507
|
-
}
|
|
508
|
-
const alerts = [];
|
|
509
|
-
const blocked = actualElapsed - INTERVAL >= watchdogThreshold;
|
|
510
|
-
if (blocked) {
|
|
511
|
-
alerts.push('ELOOP_BLOCKED');
|
|
512
|
-
// --- 延迟检查只能证明这一窗口发生过阻塞,不能证明资源持续超阈值 ---
|
|
513
|
-
spikeSince = { 'cpu': null, 'mem': null, 'eloop': null };
|
|
514
|
-
}
|
|
515
|
-
else {
|
|
516
|
-
if (snapshot.cpuProcess >= cpuThreshold) {
|
|
517
|
-
spikeSince.cpu ??= previousTime;
|
|
518
|
-
if (cpuTime - spikeSince.cpu >= spikeDuration) {
|
|
519
|
-
alerts.push('PROC_CPU');
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
else {
|
|
523
|
-
spikeSince.cpu = null;
|
|
524
|
-
}
|
|
525
|
-
if (snapshot.mem.rss / 1024 / 1024 >= memThreshold) {
|
|
526
|
-
// --- 内存是时点值,首次超阈值之前的一个采样周期不能计入持续时间 ---
|
|
527
|
-
spikeSince.mem ??= cpuTime;
|
|
528
|
-
if (cpuTime - spikeSince.mem >= spikeDuration) {
|
|
529
|
-
alerts.push('MEM');
|
|
530
|
-
}
|
|
531
|
-
}
|
|
532
|
-
else {
|
|
533
|
-
spikeSince.mem = null;
|
|
534
|
-
}
|
|
535
|
-
if (snapshot.eloopLag >= eloopThreshold) {
|
|
536
|
-
spikeSince.eloop ??= previousTime;
|
|
537
|
-
if (cpuTime - spikeSince.eloop >= spikeDuration) {
|
|
538
|
-
alerts.push('ELOOP_LAG');
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
else {
|
|
542
|
-
spikeSince.eloop = null;
|
|
543
|
-
}
|
|
342
|
+
history.push(sample);
|
|
343
|
+
while (history.length > 60) {
|
|
344
|
+
history.shift();
|
|
544
345
|
}
|
|
346
|
+
// --- 判定阻塞及各项资源是否持续超阈值 ---
|
|
347
|
+
const blocked = dt - INTERVAL >= blockMs;
|
|
348
|
+
const alerts = detectAlerts(snap, blocked, prevT, t);
|
|
545
349
|
if (!alerts.length) {
|
|
546
350
|
if (incident) {
|
|
547
351
|
incident.endedAt = now;
|
|
548
352
|
incident.endReason = 'recovered';
|
|
549
353
|
incident.activeReasons = [];
|
|
550
|
-
incident.recoveredSnapshot =
|
|
354
|
+
incident.recoveredSnapshot = snap;
|
|
551
355
|
saveIncident(incident);
|
|
552
356
|
lCore.log({}, `RECOVERED PID:${process.pid} EVENT:${incident.dir}`, '-monitor');
|
|
553
357
|
incident = null;
|
|
554
358
|
}
|
|
555
359
|
return;
|
|
556
360
|
}
|
|
557
|
-
recordIncident(alerts,
|
|
361
|
+
recordIncident(alerts, snap, sample, blocked, prevT);
|
|
558
362
|
}
|
|
559
363
|
/**
|
|
560
|
-
* ---
|
|
561
|
-
* @param
|
|
562
|
-
* @
|
|
364
|
+
* --- 根据当前快照和持续时长判定触发的告警项 ---
|
|
365
|
+
* @param snap 当前快照
|
|
366
|
+
* @param blocked 本周期是否发生事件循环阻塞
|
|
367
|
+
* @param prevT 本周期起点单调时钟(ms)
|
|
368
|
+
* @param t 当前单调时钟(ms)
|
|
369
|
+
* @returns 已确认的告警项列表
|
|
563
370
|
*/
|
|
564
|
-
function
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
371
|
+
function detectAlerts(snap, blocked, prevT, t) {
|
|
372
|
+
if (blocked) {
|
|
373
|
+
// --- 阻塞窗口只能确认阻塞本身,不能顺带证明其他资源持续超标 ---
|
|
374
|
+
spikeAt = { 'cpu': null, 'mem': null, 'eloop': null };
|
|
375
|
+
return ['ELOOP_BLOCKED'];
|
|
376
|
+
}
|
|
377
|
+
const alerts = [];
|
|
378
|
+
if (snap.cpuProcess >= cpuLimit) {
|
|
379
|
+
spikeAt.cpu ??= prevT;
|
|
380
|
+
if (t - spikeAt.cpu >= spikeMs) {
|
|
381
|
+
alerts.push('PROC_CPU');
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
else {
|
|
385
|
+
spikeAt.cpu = null;
|
|
386
|
+
}
|
|
387
|
+
if (snap.mem.rss / 1024 / 1024 >= memLimit) {
|
|
388
|
+
// --- 内存是时点值,不把超阈值前的一个周期算入持续时间 ---
|
|
389
|
+
spikeAt.mem ??= t;
|
|
390
|
+
if (t - spikeAt.mem >= spikeMs) {
|
|
391
|
+
alerts.push('MEM');
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
else {
|
|
395
|
+
spikeAt.mem = null;
|
|
396
|
+
}
|
|
397
|
+
if (snap.eloopLag >= eloopLimit) {
|
|
398
|
+
spikeAt.eloop ??= prevT;
|
|
399
|
+
if (t - spikeAt.eloop >= spikeMs) {
|
|
400
|
+
alerts.push('ELOOP_LAG');
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
else {
|
|
404
|
+
spikeAt.eloop = null;
|
|
405
|
+
}
|
|
406
|
+
return alerts;
|
|
575
407
|
}
|
|
576
408
|
/**
|
|
577
|
-
* ---
|
|
578
|
-
* @param alerts
|
|
579
|
-
* @param
|
|
409
|
+
* --- 记录或更新持续异常事件,并按冷却条件触发重型诊断 ---
|
|
410
|
+
* @param alerts 已确认的告警项
|
|
411
|
+
* @param snap 当前快照
|
|
580
412
|
* @param sample 当前采样
|
|
581
|
-
* @param blocked
|
|
582
|
-
* @param
|
|
583
|
-
* @returns 无返回值
|
|
413
|
+
* @param blocked 是否刚从阻塞恢复
|
|
414
|
+
* @param prevT 本周期起点单调时钟(ms)
|
|
584
415
|
*/
|
|
585
|
-
function recordIncident(alerts,
|
|
586
|
-
const now =
|
|
587
|
-
const
|
|
416
|
+
function recordIncident(alerts, snap, sample, blocked, prevT) {
|
|
417
|
+
const now = snap.time;
|
|
418
|
+
const isNew = incident === null;
|
|
419
|
+
// --- 首次触发时创建异常事件对象 ---
|
|
588
420
|
if (!incident) {
|
|
589
|
-
const
|
|
590
|
-
const
|
|
421
|
+
const dir = `${kebab.LOG_CWD}monitor/${lTime.format(null, 'Y/m/d/His', new Date(now))}-pid-${process.pid}-${now}/`;
|
|
422
|
+
const earliest = Math.min(spikeAt.cpu ?? Infinity, spikeAt.mem ?? Infinity, spikeAt.eloop ?? Infinity, blocked ? prevT : Infinity);
|
|
591
423
|
incident = {
|
|
592
|
-
dir
|
|
593
|
-
'
|
|
424
|
+
'dir': dir,
|
|
425
|
+
'startedAt': now - Math.max(0, nowMs() - earliest),
|
|
426
|
+
'confirmedAt': now,
|
|
427
|
+
'endedAt': null,
|
|
428
|
+
'endReason': null,
|
|
429
|
+
'reasons': [],
|
|
430
|
+
'activeReasons': [],
|
|
431
|
+
'impact': 'resource-high',
|
|
594
432
|
'thresholds': {
|
|
595
|
-
'cpu':
|
|
596
|
-
'
|
|
433
|
+
'cpu': cpuLimit,
|
|
434
|
+
'mem': memLimit,
|
|
435
|
+
'eloop': eloopLimit,
|
|
436
|
+
'duration': spikeMs,
|
|
437
|
+
'blocked': blockMs,
|
|
597
438
|
},
|
|
598
|
-
'before': [...
|
|
439
|
+
'before': [...history],
|
|
440
|
+
'samples': [],
|
|
599
441
|
'peaks': { 'cpu': 0, 'rss': 0, 'heapUsed': 0, 'eloop': 0 },
|
|
600
|
-
snapshot
|
|
442
|
+
'snapshot': snap,
|
|
443
|
+
'diagnostics': [],
|
|
601
444
|
};
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
const
|
|
608
|
-
|
|
609
|
-
for (const
|
|
610
|
-
if (!
|
|
611
|
-
|
|
445
|
+
lastDiagMs = 0;
|
|
446
|
+
lastSaveMs = 0;
|
|
447
|
+
}
|
|
448
|
+
// --- 更新告警原因、采样序列与峰值 ---
|
|
449
|
+
const ev = incident;
|
|
450
|
+
const hasNewReason = alerts.some(a => !ev.activeReasons.includes(a));
|
|
451
|
+
ev.activeReasons = [...alerts];
|
|
452
|
+
for (const a of alerts) {
|
|
453
|
+
if (!ev.reasons.includes(a)) {
|
|
454
|
+
ev.reasons.push(a);
|
|
612
455
|
}
|
|
613
456
|
}
|
|
614
457
|
if (alerts.includes('ELOOP_BLOCKED') || alerts.includes('ELOOP_LAG')) {
|
|
615
|
-
|
|
458
|
+
ev.impact = 'event-loop-delayed';
|
|
616
459
|
}
|
|
617
|
-
|
|
618
|
-
if (
|
|
619
|
-
|
|
460
|
+
ev.samples.push(sample);
|
|
461
|
+
if (ev.samples.length > 300) {
|
|
462
|
+
ev.samples.shift();
|
|
620
463
|
}
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
if (
|
|
464
|
+
ev.peaks.cpu = Math.max(ev.peaks.cpu, sample.cpu);
|
|
465
|
+
ev.peaks.rss = Math.max(ev.peaks.rss, sample.rss);
|
|
466
|
+
ev.peaks.heapUsed = Math.max(ev.peaks.heapUsed, sample.heapUsed);
|
|
467
|
+
ev.peaks.eloop = Math.max(ev.peaks.eloop, sample.eloopMax, sample.elapsed - INTERVAL);
|
|
468
|
+
if (isNew || hasNewReason) {
|
|
626
469
|
const msg = `RESOURCE_HIGH [${alerts.join(', ')}] PID:${process.pid} ` +
|
|
627
|
-
`PROC_CPU:${
|
|
628
|
-
`ELOOP_LAG:${
|
|
470
|
+
`PROC_CPU:${snap.cpuProcess}% RSS:${lText.sizeFormat(snap.mem.rss, '')} ` +
|
|
471
|
+
`ELOOP_LAG:${snap.eloopLag}ms ACTIVE_REQ:${snap.activeCount} EVENT:${ev.dir}`;
|
|
629
472
|
lCore.log({}, msg, '-monitor');
|
|
630
473
|
lCore.display('[MONITOR]', msg);
|
|
631
474
|
}
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
475
|
+
// --- 按冷却周期触发重型诊断,或复用看门狗已采集的阻塞现场 ---
|
|
476
|
+
if (isNew || hasNewReason || nowMs() - lastDiagMs >= DIAG_COOLDOWN) {
|
|
477
|
+
triggerDiag(ev, alerts, snap, blocked, prevT);
|
|
478
|
+
}
|
|
479
|
+
// --- 定期将事件摘要落盘 ---
|
|
480
|
+
if (isNew || hasNewReason || now - lastSaveMs >= 5_000) {
|
|
481
|
+
lastSaveMs = now;
|
|
482
|
+
saveIncident(ev);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* --- 触发一次重型诊断,或在看门狗已保存阻塞现场时直接关联 ---
|
|
487
|
+
* @param ev 当前事件
|
|
488
|
+
* @param alerts 告警项
|
|
489
|
+
* @param snap 当前快照
|
|
490
|
+
* @param blocked 是否阻塞恢复
|
|
491
|
+
* @param prevT 本周期起点单调时钟(ms)
|
|
492
|
+
*/
|
|
493
|
+
function triggerDiag(ev, alerts, snap, blocked, prevT) {
|
|
494
|
+
const now = snap.time;
|
|
495
|
+
lastDiagMs = nowMs();
|
|
496
|
+
const res = {
|
|
497
|
+
'time': now,
|
|
498
|
+
'status': 'pending',
|
|
499
|
+
'files': [],
|
|
500
|
+
'errors': [],
|
|
501
|
+
'snapshot': snap,
|
|
502
|
+
};
|
|
503
|
+
ev.diagnostics.push(res);
|
|
504
|
+
if (ev.diagnostics.length > 60) {
|
|
505
|
+
ev.diagnostics.shift();
|
|
506
|
+
}
|
|
507
|
+
const view = shm;
|
|
508
|
+
const wdSaved = blocked && view !== null && Atomics.load(view, SLOT_SAVED) >= BigInt(prevT);
|
|
509
|
+
if (wdSaved) {
|
|
510
|
+
// --- 看门狗已经保存了本次阻塞现场,直接关联而不再重复采 Profile ---
|
|
511
|
+
const hb = Number(Atomics.load(view, SLOT_SAVED));
|
|
512
|
+
if (lastWdDiag?.heartbeat === hb) {
|
|
513
|
+
res.status = `watchdog-${lastWdDiag.status}`;
|
|
514
|
+
res.files = [`${lastWdDiag.dir}/blocked-event.json`, ...lastWdDiag.files];
|
|
515
|
+
res.errors.push(...lastWdDiag.errors);
|
|
657
516
|
}
|
|
658
517
|
else {
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
// --- 阻塞恢复后的 Profile 只能记录后续执行,摘要保留这个采集时机限制 ---
|
|
662
|
-
if (blocked) {
|
|
663
|
-
result.errors.push('The blocking stack was not captured; this profile starts after recovery.');
|
|
664
|
-
}
|
|
665
|
-
void collectDiagnostics(event.dir, ts, alerts.includes('PROC_CPU') || blocked, alerts.includes('MEM') && heapSnapshotEnabled, result, view).catch((error) => {
|
|
666
|
-
result.status = 'failed';
|
|
667
|
-
result.errors.push(lText.stringifyError(error));
|
|
668
|
-
}).finally(() => {
|
|
669
|
-
diagnosing = false;
|
|
670
|
-
saveIncident(event);
|
|
671
|
-
});
|
|
518
|
+
res.status = 'watchdog-captured';
|
|
519
|
+
wdPending.set(hb, { 'event': ev, 'result': res });
|
|
672
520
|
}
|
|
521
|
+
return;
|
|
673
522
|
}
|
|
674
|
-
if (
|
|
675
|
-
|
|
676
|
-
|
|
523
|
+
if (diagBusy || (view && Atomics.load(view, SLOT_LOCK) !== 0n)) {
|
|
524
|
+
res.status = 'skipped-busy';
|
|
525
|
+
lastDiagMs = nowMs() - DIAG_COOLDOWN + 5_000;
|
|
526
|
+
return;
|
|
677
527
|
}
|
|
528
|
+
diagBusy = true;
|
|
529
|
+
const ts = `${lTime.format(null, 'YmdHis', new Date(now))}-${now}`;
|
|
530
|
+
if (blocked) {
|
|
531
|
+
res.errors.push('The blocking stack was not captured; this profile starts after recovery.');
|
|
532
|
+
}
|
|
533
|
+
void runDiag(ev.dir, ts, alerts.includes('PROC_CPU') || blocked, alerts.includes('MEM') && heapSnap, res, view).catch((err) => {
|
|
534
|
+
res.status = 'failed';
|
|
535
|
+
res.errors.push(lText.stringifyError(err));
|
|
536
|
+
}).finally(() => {
|
|
537
|
+
diagBusy = false;
|
|
538
|
+
saveIncident(ev);
|
|
539
|
+
});
|
|
678
540
|
}
|
|
679
541
|
/**
|
|
680
|
-
* ---
|
|
681
|
-
* @param
|
|
682
|
-
* @param current 当前系统各核 CPU 时间快照
|
|
683
|
-
* @returns 0-100 的百分比值,和任务管理器/top 命令一致
|
|
542
|
+
* --- 串行落盘事件摘要,避免多次保存互相覆盖 ---
|
|
543
|
+
* @param ev 事件对象
|
|
684
544
|
*/
|
|
685
|
-
function
|
|
686
|
-
|
|
687
|
-
|
|
545
|
+
function saveIncident(ev) {
|
|
546
|
+
const text = lText.stringifyJson(ev, 2);
|
|
547
|
+
saveChain = saveChain.then(async () => {
|
|
548
|
+
if (!await lFs.mkdir(ev.dir, 0o700) ||
|
|
549
|
+
!await lFs.chmod(ev.dir, 0o700) ||
|
|
550
|
+
!await lFs.putContent(`${ev.dir}event.json`, text, { 'mode': 0o600 }) ||
|
|
551
|
+
!await lFs.chmod(`${ev.dir}event.json`, 0o600)) {
|
|
552
|
+
lCore.display('[MONITOR] Failed to save event:', ev.dir);
|
|
553
|
+
}
|
|
554
|
+
}).catch((err) => {
|
|
555
|
+
lCore.display('[MONITOR] Failed to save event:', err);
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
// ============================
|
|
559
|
+
// --- 诊断采集与看门狗线程 ---
|
|
560
|
+
// ============================
|
|
561
|
+
/**
|
|
562
|
+
* --- 启动看门狗 Worker 线程 ---
|
|
563
|
+
*/
|
|
564
|
+
function startWd() {
|
|
565
|
+
if (!shmBuf) {
|
|
566
|
+
return;
|
|
688
567
|
}
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
568
|
+
const workerUrl = new URL('./monitor/watchdog.js', import.meta.url);
|
|
569
|
+
try {
|
|
570
|
+
const worker = new workerThreads.Worker(workerUrl, {
|
|
571
|
+
'workerData': {
|
|
572
|
+
'buffer': shmBuf,
|
|
573
|
+
'logDir': kebab.LOG_CWD,
|
|
574
|
+
'logFormat': lCore.globalConfig.logFormat ?? 'jsonl',
|
|
575
|
+
'pid': process.pid,
|
|
576
|
+
'threshold': blockMs,
|
|
577
|
+
'cooldown': WD_COOLDOWN,
|
|
578
|
+
'interval': WD_INTERVAL,
|
|
579
|
+
'profileDuration': PROFILE_MS,
|
|
580
|
+
'requests': Array.from(reqs.entries()),
|
|
581
|
+
},
|
|
582
|
+
});
|
|
583
|
+
wd = worker;
|
|
584
|
+
worker.unref();
|
|
585
|
+
worker.on('message', (msg) => {
|
|
586
|
+
if (wd !== worker || msg.type !== 'diagnostic') {
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
lastWdDiag = msg;
|
|
590
|
+
const item = wdPending.get(msg.heartbeat);
|
|
591
|
+
if (item) {
|
|
592
|
+
item.result.status = `watchdog-${msg.status}`;
|
|
593
|
+
item.result.files = [`${msg.dir}/blocked-event.json`, ...msg.files];
|
|
594
|
+
item.result.errors.push(...msg.errors);
|
|
595
|
+
wdPending.delete(msg.heartbeat);
|
|
596
|
+
saveIncident(item.event);
|
|
597
|
+
}
|
|
598
|
+
});
|
|
599
|
+
worker.on('error', (err) => {
|
|
600
|
+
lCore.log({}, `WATCHDOG_ERROR ${lText.stringifyError(err)}`, '-monitor');
|
|
601
|
+
lCore.display('[MONITOR] Watchdog error', err);
|
|
602
|
+
});
|
|
603
|
+
worker.on('exit', (code) => {
|
|
604
|
+
if (code !== 0 && timer) {
|
|
605
|
+
lCore.debug(`[MONITOR] Watchdog exited: ${code}`);
|
|
606
|
+
}
|
|
607
|
+
if (wd === worker) {
|
|
608
|
+
wd = null;
|
|
609
|
+
}
|
|
610
|
+
retryWd();
|
|
611
|
+
});
|
|
612
|
+
lCore.debug(`[MONITOR] [THREAD] [${process.pid}] Watchdog started`);
|
|
613
|
+
}
|
|
614
|
+
catch (err) {
|
|
615
|
+
lCore.log({}, `WATCHDOG_START_FAILED ${lText.stringifyError(err)}`, '-monitor');
|
|
616
|
+
lCore.display('[MONITOR] Failed to start watchdog', err);
|
|
617
|
+
retryWd();
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* --- 看门狗异常退出后延迟重启 ---
|
|
622
|
+
*/
|
|
623
|
+
function retryWd() {
|
|
624
|
+
if (!timer || wd || wdRetryTimer) {
|
|
625
|
+
return;
|
|
705
626
|
}
|
|
706
|
-
|
|
707
|
-
|
|
627
|
+
wdRetryTimer = setTimeout(() => {
|
|
628
|
+
wdRetryTimer = null;
|
|
629
|
+
startWd();
|
|
630
|
+
}, WD_RETRY_MS);
|
|
631
|
+
wdRetryTimer.unref();
|
|
708
632
|
}
|
|
709
633
|
/**
|
|
710
|
-
* ---
|
|
634
|
+
* --- 依次执行 Report、CPU Profile 与堆快照采集,单项失败不阻塞后续项 ---
|
|
711
635
|
* @param dir 诊断目录
|
|
712
|
-
* @param ts
|
|
713
|
-
* @param
|
|
714
|
-
* @param
|
|
715
|
-
* @param
|
|
636
|
+
* @param ts 唯一时间标识
|
|
637
|
+
* @param needCpu 是否采集 CPU Profile
|
|
638
|
+
* @param needHeap 是否采集堆快照
|
|
639
|
+
* @param res 采集结果对象
|
|
716
640
|
* @param view 本次监控实例的共享内存
|
|
717
|
-
* @returns 无返回值,失败原因保留在 result 中
|
|
718
641
|
*/
|
|
719
|
-
async function
|
|
642
|
+
async function runDiag(dir, ts, needCpu, needHeap, res, view) {
|
|
720
643
|
try {
|
|
721
644
|
if (!await lFs.mkdir(dir, 0o700) || !await lFs.chmod(dir, 0o700)) {
|
|
722
|
-
|
|
723
|
-
|
|
645
|
+
res.status = 'failed';
|
|
646
|
+
res.errors.push('Failed to create or secure diagnostic directory.');
|
|
724
647
|
return;
|
|
725
648
|
}
|
|
726
|
-
if (view !==
|
|
727
|
-
|
|
649
|
+
if (view !== shm) {
|
|
650
|
+
res.status = 'cancelled';
|
|
728
651
|
return;
|
|
729
652
|
}
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
if (
|
|
735
|
-
|
|
736
|
-
}
|
|
737
|
-
const report = process.report.getReport();
|
|
738
|
-
if (report.header) {
|
|
739
|
-
report.header.commandLine = [];
|
|
740
|
-
delete report.header.networkInterfaces;
|
|
741
|
-
}
|
|
742
|
-
delete report.environmentVariables;
|
|
743
|
-
for (const handle of report.libuv ?? []) {
|
|
744
|
-
delete handle.localEndpoint;
|
|
745
|
-
delete handle.remoteEndpoint;
|
|
746
|
-
}
|
|
747
|
-
if (view) {
|
|
748
|
-
Atomics.store(view, 0, BigInt(clockMs()));
|
|
749
|
-
Atomics.store(view, 3, 0n);
|
|
750
|
-
}
|
|
751
|
-
if (await lFs.putContent(reportPath, lText.stringifyJson(report, 2), { 'mode': 0o600 }) &&
|
|
752
|
-
await lFs.chmod(reportPath, 0o600)) {
|
|
753
|
-
result.files.push(reportPath);
|
|
653
|
+
// --- 1. 采集脱敏后的诊断报告 ---
|
|
654
|
+
await writeReport(dir, ts, res, view);
|
|
655
|
+
// --- 2. 采集 CPU Profile ---
|
|
656
|
+
if (needCpu) {
|
|
657
|
+
if (await runProfile(dir, ts, res)) {
|
|
658
|
+
res.files.push(`${dir}cpu-${ts}.cpuprofile`);
|
|
754
659
|
}
|
|
755
660
|
else {
|
|
756
|
-
|
|
661
|
+
res.errors.push('CPU profile collection failed.');
|
|
757
662
|
}
|
|
758
663
|
}
|
|
759
|
-
|
|
760
|
-
|
|
664
|
+
if (view !== shm) {
|
|
665
|
+
res.status = 'cancelled';
|
|
666
|
+
return;
|
|
761
667
|
}
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
Atomics.store(view, 3, 0n);
|
|
766
|
-
}
|
|
668
|
+
// --- 3. 按可用内存条件采集堆快照 ---
|
|
669
|
+
if (needHeap) {
|
|
670
|
+
await writeHeap(dir, ts, res, view);
|
|
767
671
|
}
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
672
|
+
res.status = res.errors.length ? 'partial' : 'complete';
|
|
673
|
+
}
|
|
674
|
+
catch (err) {
|
|
675
|
+
res.status = 'failed';
|
|
676
|
+
res.errors.push(lText.stringifyError(err));
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* --- 采集脱敏后的 Node.js 诊断报告 ---
|
|
681
|
+
* @param dir 诊断目录
|
|
682
|
+
* @param ts 时间标识
|
|
683
|
+
* @param res 采集结果
|
|
684
|
+
* @param view 共享内存视图
|
|
685
|
+
*/
|
|
686
|
+
async function writeReport(dir, ts, res, view) {
|
|
687
|
+
const file = `${dir}report-${ts}.json`;
|
|
688
|
+
try {
|
|
689
|
+
diagSkip = true;
|
|
690
|
+
if (view) {
|
|
691
|
+
Atomics.store(view, SLOT_DIAG, 1n);
|
|
775
692
|
}
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
693
|
+
const report = process.report.getReport();
|
|
694
|
+
if (report.header) {
|
|
695
|
+
report.header.commandLine = [];
|
|
696
|
+
delete report.header.networkInterfaces;
|
|
779
697
|
}
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
const heapFile = v8.writeHeapSnapshot(`${dir}heap-${ts}.heapsnapshot`);
|
|
796
|
-
if (view) {
|
|
797
|
-
Atomics.store(view, 0, BigInt(clockMs()));
|
|
798
|
-
Atomics.store(view, 3, 0n);
|
|
799
|
-
}
|
|
800
|
-
if (await lFs.chmod(heapFile, 0o600)) {
|
|
801
|
-
result.files.push(heapFile);
|
|
802
|
-
}
|
|
803
|
-
else {
|
|
804
|
-
result.errors.push('Failed to secure heap snapshot.');
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
catch (error) {
|
|
808
|
-
result.errors.push(`Heap snapshot: ${lText.stringifyError(error)}`);
|
|
809
|
-
}
|
|
810
|
-
finally {
|
|
811
|
-
if (view) {
|
|
812
|
-
Atomics.store(view, 0, BigInt(clockMs()));
|
|
813
|
-
Atomics.store(view, 3, 0n);
|
|
814
|
-
}
|
|
815
|
-
}
|
|
816
|
-
}
|
|
698
|
+
delete report.environmentVariables;
|
|
699
|
+
for (const h of report.libuv ?? []) {
|
|
700
|
+
delete h.localEndpoint;
|
|
701
|
+
delete h.remoteEndpoint;
|
|
702
|
+
}
|
|
703
|
+
if (view) {
|
|
704
|
+
Atomics.store(view, SLOT_HB, BigInt(nowMs()));
|
|
705
|
+
Atomics.store(view, SLOT_DIAG, 0n);
|
|
706
|
+
}
|
|
707
|
+
if (await lFs.putContent(file, lText.stringifyJson(report, 2), { 'mode': 0o600 }) &&
|
|
708
|
+
await lFs.chmod(file, 0o600)) {
|
|
709
|
+
res.files.push(file);
|
|
710
|
+
}
|
|
711
|
+
else {
|
|
712
|
+
res.errors.push('Failed to write or secure diagnostic report.');
|
|
817
713
|
}
|
|
818
|
-
result.status = result.errors.length ? 'partial' : 'complete';
|
|
819
714
|
}
|
|
820
|
-
catch (
|
|
821
|
-
|
|
822
|
-
|
|
715
|
+
catch (err) {
|
|
716
|
+
res.errors.push(`Report: ${lText.stringifyError(err)}`);
|
|
717
|
+
}
|
|
718
|
+
finally {
|
|
719
|
+
if (view) {
|
|
720
|
+
Atomics.store(view, SLOT_HB, BigInt(nowMs()));
|
|
721
|
+
Atomics.store(view, SLOT_DIAG, 0n);
|
|
722
|
+
}
|
|
823
723
|
}
|
|
824
724
|
}
|
|
825
725
|
/**
|
|
826
|
-
* ---
|
|
726
|
+
* --- 剩余内存充足时采集 V8 堆快照 ---
|
|
827
727
|
* @param dir 诊断目录
|
|
828
|
-
* @param ts
|
|
829
|
-
* @param
|
|
830
|
-
* @
|
|
728
|
+
* @param ts 时间标识
|
|
729
|
+
* @param res 采集结果
|
|
730
|
+
* @param view 共享内存视图
|
|
831
731
|
*/
|
|
832
|
-
function
|
|
833
|
-
|
|
732
|
+
async function writeHeap(dir, ts, res, view) {
|
|
733
|
+
// --- 堆快照约需额外两倍堆内存,剩余内存不足时跳过 ---
|
|
734
|
+
const cgroup = process.constrainedMemory();
|
|
735
|
+
const free = cgroup > 0
|
|
736
|
+
? Math.min(os.freemem(), Math.max(0, cgroup - process.memoryUsage.rss()))
|
|
737
|
+
: os.freemem();
|
|
738
|
+
if (free < v8.getHeapStatistics().total_heap_size * 2) {
|
|
739
|
+
res.errors.push('Heap snapshot skipped: insufficient available memory.');
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
try {
|
|
743
|
+
diagSkip = true;
|
|
744
|
+
if (view) {
|
|
745
|
+
Atomics.store(view, SLOT_DIAG, 1n);
|
|
746
|
+
}
|
|
747
|
+
const file = v8.writeHeapSnapshot(`${dir}heap-${ts}.heapsnapshot`);
|
|
748
|
+
if (view) {
|
|
749
|
+
Atomics.store(view, SLOT_HB, BigInt(nowMs()));
|
|
750
|
+
Atomics.store(view, SLOT_DIAG, 0n);
|
|
751
|
+
}
|
|
752
|
+
if (await lFs.chmod(file, 0o600)) {
|
|
753
|
+
res.files.push(file);
|
|
754
|
+
}
|
|
755
|
+
else {
|
|
756
|
+
res.errors.push('Failed to secure heap snapshot.');
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
catch (err) {
|
|
760
|
+
res.errors.push(`Heap snapshot: ${lText.stringifyError(err)}`);
|
|
761
|
+
}
|
|
762
|
+
finally {
|
|
763
|
+
if (view) {
|
|
764
|
+
Atomics.store(view, SLOT_HB, BigInt(nowMs()));
|
|
765
|
+
Atomics.store(view, SLOT_DIAG, 0n);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
/**
|
|
770
|
+
* --- 通知看门狗采集主线程 CPU Profile 并等待完成 ---
|
|
771
|
+
* @param dir 诊断目录
|
|
772
|
+
* @param ts 时间标识
|
|
773
|
+
* @param res 采集结果
|
|
774
|
+
* @returns 是否保存成功
|
|
775
|
+
*/
|
|
776
|
+
function runProfile(dir, ts, res) {
|
|
777
|
+
if (profBusy || !wd) {
|
|
834
778
|
return Promise.resolve(false);
|
|
835
779
|
}
|
|
836
|
-
const worker =
|
|
837
|
-
|
|
780
|
+
const worker = wd;
|
|
781
|
+
profBusy = true;
|
|
838
782
|
const file = `cpu-${ts}.cpuprofile`;
|
|
839
783
|
return new Promise((resolve) => {
|
|
840
|
-
let
|
|
841
|
-
const
|
|
842
|
-
if (
|
|
843
|
-
|
|
844
|
-
if (
|
|
845
|
-
|
|
784
|
+
let done = false;
|
|
785
|
+
const onMsg = (msg) => {
|
|
786
|
+
if (msg.type === 'profile' && msg.file === file) {
|
|
787
|
+
res.errors.push(...msg.errors);
|
|
788
|
+
if (msg.recorded) {
|
|
789
|
+
res.files.push(`${dir}profile-${ts}.json`);
|
|
846
790
|
}
|
|
847
|
-
finish(
|
|
791
|
+
finish(msg.saved);
|
|
848
792
|
}
|
|
849
793
|
};
|
|
850
794
|
const onExit = () => {
|
|
851
|
-
|
|
795
|
+
res.errors.push('Profile aborted because the watchdog exited.');
|
|
852
796
|
finish(false);
|
|
853
797
|
};
|
|
854
|
-
const
|
|
855
|
-
|
|
798
|
+
const t = setTimeout(() => {
|
|
799
|
+
res.errors.push('Profile Worker response timed out.');
|
|
856
800
|
finish(false);
|
|
857
|
-
},
|
|
858
|
-
/**
|
|
859
|
-
* --- 正常响应、退出和超时共享清理,旧 Worker 不会继续持有监听器 ---
|
|
860
|
-
* @param saved 是否保存成功
|
|
861
|
-
* @returns 无返回值
|
|
862
|
-
*/
|
|
801
|
+
}, PROFILE_MS + 15_000);
|
|
802
|
+
/** --- 正常响应、退出与超时共用清理入口 --- */
|
|
863
803
|
function finish(saved) {
|
|
864
|
-
if (
|
|
804
|
+
if (done) {
|
|
865
805
|
return;
|
|
866
806
|
}
|
|
867
|
-
|
|
868
|
-
clearTimeout(
|
|
869
|
-
worker.off('message',
|
|
807
|
+
done = true;
|
|
808
|
+
clearTimeout(t);
|
|
809
|
+
worker.off('message', onMsg);
|
|
870
810
|
worker.off('exit', onExit);
|
|
871
|
-
|
|
811
|
+
profBusy = false;
|
|
872
812
|
resolve(saved);
|
|
873
813
|
}
|
|
874
|
-
worker.on('message',
|
|
814
|
+
worker.on('message', onMsg);
|
|
875
815
|
worker.once('exit', onExit);
|
|
876
816
|
try {
|
|
877
|
-
worker.postMessage({
|
|
817
|
+
worker.postMessage({
|
|
818
|
+
'type': 'profile',
|
|
819
|
+
'dir': dir,
|
|
820
|
+
'ts': ts,
|
|
821
|
+
});
|
|
878
822
|
}
|
|
879
|
-
catch (
|
|
880
|
-
lCore.display('[MONITOR] Failed to request CPU profile:',
|
|
823
|
+
catch (err) {
|
|
824
|
+
lCore.display('[MONITOR] Failed to request CPU profile:', err);
|
|
881
825
|
finish(false);
|
|
882
826
|
}
|
|
883
827
|
});
|
|
884
828
|
}
|
|
829
|
+
// ====================
|
|
830
|
+
// --- 内部工具函数 ---
|
|
831
|
+
// ====================
|
|
832
|
+
/**
|
|
833
|
+
* --- 检测当前是否处于调试模式 ---
|
|
834
|
+
*/
|
|
835
|
+
function isDebug() {
|
|
836
|
+
return !!inspector.url();
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* --- 获取单调时钟毫秒数 ---
|
|
840
|
+
*/
|
|
841
|
+
function nowMs() {
|
|
842
|
+
return Number(process.hrtime.bigint() / 1000000n);
|
|
843
|
+
}
|
|
844
|
+
/**
|
|
845
|
+
* --- 计算单个请求存续期间的进程资源增量 ---
|
|
846
|
+
* @param req 活跃请求
|
|
847
|
+
* @param now 当前时间戳(ms)
|
|
848
|
+
* @param cpu 当前进程 CPU 累计用量
|
|
849
|
+
* @param rss 当前进程 RSS
|
|
850
|
+
*/
|
|
851
|
+
function snapReq(req, now, cpu, rss) {
|
|
852
|
+
return {
|
|
853
|
+
'url': req.url,
|
|
854
|
+
'method': req.method,
|
|
855
|
+
'duration': now - req.start,
|
|
856
|
+
'cpuUser': cpu.user - req.startCpu.user,
|
|
857
|
+
'cpuSystem': cpu.system - req.startCpu.system,
|
|
858
|
+
'memDelta': rss - req.startMem,
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* --- 裁剪最近完成请求列表(最多保留 60 秒且不超过 MAX_REQS 条) ---
|
|
863
|
+
* @param now 当前时间戳(ms)
|
|
864
|
+
*/
|
|
865
|
+
function trimRecent(now) {
|
|
866
|
+
while (recent.length > MAX_REQS || (recent.length && now - (recent[0].completedAt ?? 0) > 60_000)) {
|
|
867
|
+
recent.shift();
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* --- 组装当前完整资源快照 ---
|
|
872
|
+
* @param cpuProc 本周期进程 CPU 占比
|
|
873
|
+
* @param cpuOs 本周期系统 CPU 占比
|
|
874
|
+
*/
|
|
875
|
+
function buildSnap(cpuProc, cpuOs) {
|
|
876
|
+
const mem = process.memoryUsage();
|
|
877
|
+
const heap = v8.getHeapStatistics();
|
|
878
|
+
const cpu = process.cpuUsage();
|
|
879
|
+
const now = Date.now();
|
|
880
|
+
let eloopLag = 0;
|
|
881
|
+
let eloopMax = 0;
|
|
882
|
+
if (eloop) {
|
|
883
|
+
eloopLag = Math.round(eloop.percentile(99) / 1_000_000);
|
|
884
|
+
eloopMax = Math.round(eloop.max / 1_000_000);
|
|
885
|
+
}
|
|
886
|
+
const active = [];
|
|
887
|
+
for (const req of reqs.values()) {
|
|
888
|
+
if (active.length >= MAX_REQS) {
|
|
889
|
+
break;
|
|
890
|
+
}
|
|
891
|
+
active.push(snapReq(req, now, cpu, mem.rss));
|
|
892
|
+
}
|
|
893
|
+
trimRecent(now);
|
|
894
|
+
return {
|
|
895
|
+
'pid': process.pid,
|
|
896
|
+
'time': now,
|
|
897
|
+
'cpuProcess': Math.round(cpuProc * 100) / 100,
|
|
898
|
+
'cpuOs': cpuOs,
|
|
899
|
+
'mem': {
|
|
900
|
+
'rss': mem.rss,
|
|
901
|
+
'heapTotal': mem.heapTotal,
|
|
902
|
+
'heapUsed': mem.heapUsed,
|
|
903
|
+
'external': mem.external,
|
|
904
|
+
'arrayBuffers': mem.arrayBuffers,
|
|
905
|
+
},
|
|
906
|
+
'heap': {
|
|
907
|
+
'totalSize': heap.total_heap_size,
|
|
908
|
+
'usedSize': heap.used_heap_size,
|
|
909
|
+
'sizeLimit': heap.heap_size_limit,
|
|
910
|
+
},
|
|
911
|
+
'osMem': {
|
|
912
|
+
'total': os.totalmem(),
|
|
913
|
+
'free': os.freemem(),
|
|
914
|
+
},
|
|
915
|
+
'eloopLag': eloopLag,
|
|
916
|
+
'eloopMax': eloopMax,
|
|
917
|
+
'activeRequests': active,
|
|
918
|
+
'activeCount': reqs.size,
|
|
919
|
+
'recentRequests': [...recent],
|
|
920
|
+
};
|
|
921
|
+
}
|
|
922
|
+
/**
|
|
923
|
+
* --- 通过两次 os.cpus() 采样差值计算系统总 CPU 使用率(0-100) ---
|
|
924
|
+
* @param prev 上次采样
|
|
925
|
+
* @param cur 本次采样
|
|
926
|
+
*/
|
|
927
|
+
function calcOsCpu(prev, cur) {
|
|
928
|
+
if (prev?.length !== cur.length) {
|
|
929
|
+
return 0;
|
|
930
|
+
}
|
|
931
|
+
let idle = 0;
|
|
932
|
+
let total = 0;
|
|
933
|
+
for (let i = 0; i < cur.length; ++i) {
|
|
934
|
+
const c = cur[i].times;
|
|
935
|
+
const p = prev[i].times;
|
|
936
|
+
const dIdle = c.idle - p.idle;
|
|
937
|
+
idle += dIdle;
|
|
938
|
+
total += (c.user - p.user) + (c.nice - p.nice) + (c.sys - p.sys) + (c.irq - p.irq) + dIdle;
|
|
939
|
+
}
|
|
940
|
+
if (total <= 0) {
|
|
941
|
+
return 0;
|
|
942
|
+
}
|
|
943
|
+
const pct = (1 - idle / total) * 100;
|
|
944
|
+
return Math.round(Math.max(0, Math.min(100, pct)) * 100) / 100;
|
|
945
|
+
}
|