@maiyunnet/kebab 9.22.3 → 9.22.5
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/master-log.d.ts +1 -0
- package/abox/master-log.js +26 -0
- package/abox/text.d.ts +2 -0
- package/abox/text.js +21 -0
- package/doc/kebab-rag.md +179 -155
- package/index.d.ts +7 -2
- package/index.js +1 -1
- package/lib/core.js +69 -139
- package/lib/text.d.ts +6 -4
- package/lib/text.js +11 -34
- package/package.json +4 -2
- package/sys/master.js +193 -283
- package/sys/route.d.ts +5 -5
- package/sys/route.js +33 -20
package/sys/master.js
CHANGED
|
@@ -19,14 +19,25 @@ import * as lText from '#kebab/lib/text.js';
|
|
|
19
19
|
import * as lCrypto from '#kebab/lib/crypto.js';
|
|
20
20
|
import * as lTime from '#kebab/lib/time.js';
|
|
21
21
|
import * as lZip from '#kebab/lib/zip.js';
|
|
22
|
+
import * as masterLog from '#kebab/abox/master-log.js';
|
|
23
|
+
/**
|
|
24
|
+
* --- 解析一行 CSV,保留空字段,并处理字段里的逗号和引号 ---
|
|
25
|
+
* @param line 不含换行符的 CSV 行
|
|
26
|
+
* @returns 按原顺序排列的字段
|
|
27
|
+
*/
|
|
28
|
+
const parseCsvLine = masterLog.parseCsvLine;
|
|
22
29
|
/** --- 当前运行中的子进程列表 --- */
|
|
23
30
|
const workerList = {};
|
|
24
|
-
/** ---
|
|
31
|
+
/** --- 是否已开始停止整个服务 --- */
|
|
25
32
|
let stopping = false;
|
|
26
|
-
/** ---
|
|
33
|
+
/** --- 正在执行的停止任务,重复 stop 时继续等这个任务 --- */
|
|
27
34
|
let stopPromise = null;
|
|
35
|
+
/** --- 正在执行的重启任务,重复请求不再另起一轮 --- */
|
|
36
|
+
let restartPromise = null;
|
|
37
|
+
/** --- 正在替换失联 worker 的任务,重启时先等它结束 --- */
|
|
38
|
+
let workerCheckPromise = null;
|
|
28
39
|
/**
|
|
29
|
-
* ---
|
|
40
|
+
* --- 判断路径是否在指定目录内 ---
|
|
30
41
|
* @param rootPath 已解析的真实根目录
|
|
31
42
|
* @param candidate 候选绝对路径
|
|
32
43
|
*/
|
|
@@ -35,7 +46,7 @@ function isPathInside(rootPath, candidate) {
|
|
|
35
46
|
return (relative === '') || (!relative.startsWith(`..${path.sep}`) && (relative !== '..') && !path.isAbsolute(relative));
|
|
36
47
|
}
|
|
37
48
|
/**
|
|
38
|
-
* ---
|
|
49
|
+
* --- 把输入路径转成完整路径,防止通过 .. 或软链接访问根目录外的文件 ---
|
|
39
50
|
* @param rootPath 限定的根目录
|
|
40
51
|
* @param inputPath 用户输入的相对路径
|
|
41
52
|
*/
|
|
@@ -52,7 +63,7 @@ async function resolvePathInside(rootPath, inputPath) {
|
|
|
52
63
|
if (!isPathInside(rootReal, candidate)) {
|
|
53
64
|
return null;
|
|
54
65
|
}
|
|
55
|
-
/** ---
|
|
66
|
+
/** --- 路径还不存在时,往上找已有的部分,检查软链接是否指向根目录外 --- */
|
|
56
67
|
let existingPath = candidate;
|
|
57
68
|
const missingParts = [];
|
|
58
69
|
while (true) {
|
|
@@ -61,7 +72,11 @@ async function resolvePathInside(rootPath, inputPath) {
|
|
|
61
72
|
const resolved = path.resolve(existingReal, ...missingParts);
|
|
62
73
|
return isPathInside(rootReal, resolved) ? resolved : null;
|
|
63
74
|
}
|
|
64
|
-
catch {
|
|
75
|
+
catch (e) {
|
|
76
|
+
if (e.code !== 'ENOENT') {
|
|
77
|
+
lCore.display('[master] [resolvePathInside]', e);
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
65
80
|
const parent = path.dirname(existingPath);
|
|
66
81
|
if (parent === existingPath) {
|
|
67
82
|
return null;
|
|
@@ -72,8 +87,9 @@ async function resolvePathInside(rootPath, inputPath) {
|
|
|
72
87
|
}
|
|
73
88
|
}
|
|
74
89
|
/**
|
|
75
|
-
* ---
|
|
90
|
+
* --- 统一 ZIP 文件路径中的斜杠,并拒绝 .. 等不安全写法 ---
|
|
76
91
|
* @param archivePath ZIP 内的原始路径
|
|
92
|
+
* @returns 以 / 开头的 ZIP 内路径;路径不允许时返回 null
|
|
77
93
|
*/
|
|
78
94
|
function normalizeArchivePath(archivePath) {
|
|
79
95
|
const normalizedSlashes = archivePath.replace(/\\/g, '/').replace(/^\/+/, '');
|
|
@@ -83,14 +99,10 @@ function normalizeArchivePath(archivePath) {
|
|
|
83
99
|
normalizedSlashes.split('/').some(part => !part || (part === '.') || (part === '..'))) {
|
|
84
100
|
return null;
|
|
85
101
|
}
|
|
86
|
-
|
|
87
|
-
if (normalized.startsWith('../') || (normalized === '..') || path.posix.isAbsolute(normalized)) {
|
|
88
|
-
return null;
|
|
89
|
-
}
|
|
90
|
-
return `/${normalized}`;
|
|
102
|
+
return `/${normalizedSlashes}`;
|
|
91
103
|
}
|
|
92
104
|
/**
|
|
93
|
-
* ---
|
|
105
|
+
* --- 检查 JSON 中有没有 pwd 或 skey,嵌套对象也要检查 ---
|
|
94
106
|
* @param value 待检查的 JSON 值
|
|
95
107
|
* @returns 是否包含 pwd 或 skey 参数
|
|
96
108
|
*/
|
|
@@ -112,7 +124,7 @@ function hasSensitiveConfigKey(value) {
|
|
|
112
124
|
return false;
|
|
113
125
|
}
|
|
114
126
|
/**
|
|
115
|
-
* ---
|
|
127
|
+
* --- 检查 ZIP 中的 kebab.json 有没有 pwd 或 skey ---
|
|
116
128
|
* @param content ZIP 文件内容
|
|
117
129
|
* @returns 是否包含 pwd 或 skey 参数
|
|
118
130
|
*/
|
|
@@ -121,7 +133,7 @@ function hasSensitiveConfig(content) {
|
|
|
121
133
|
return (json !== false) && hasSensitiveConfigKey(json);
|
|
122
134
|
}
|
|
123
135
|
/**
|
|
124
|
-
* ---
|
|
136
|
+
* --- 等待 worker 开始监听端口,超时后继续执行 ---
|
|
125
137
|
* @param worker 要等待的 worker 对象
|
|
126
138
|
* @param timeout 超时时间(毫秒),默认 30 秒
|
|
127
139
|
*/
|
|
@@ -194,17 +206,30 @@ async function run() {
|
|
|
194
206
|
if (!worker.process.pid) {
|
|
195
207
|
return;
|
|
196
208
|
}
|
|
209
|
+
const entry = workerList[worker.process.pid];
|
|
210
|
+
delete workerList[worker.process.pid];
|
|
197
211
|
// --- 有子线程退出 ---
|
|
198
212
|
if (code === 0) {
|
|
199
|
-
// ---
|
|
213
|
+
// --- 正常退出,无需再启动替代进程 ---
|
|
200
214
|
lCore.display(`[master] Worker ${worker.process.pid} has been disconnected.`);
|
|
201
215
|
}
|
|
202
216
|
else {
|
|
203
|
-
// ---
|
|
217
|
+
// --- 异常退出,检查是否需要补一个 worker ---
|
|
204
218
|
lCore.display(`[master] Worker ${worker.process.pid} has collapsed.`);
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
219
|
+
if (!entry) {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
// --- 先等正在进行的重启或失联检查结束,免得重复启动 worker ---
|
|
223
|
+
await Promise.allSettled([restartPromise, workerCheckPromise]);
|
|
224
|
+
if (stopping) {
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
for (const current of Object.values(workerList)) {
|
|
228
|
+
if (current.cpu === entry.cpu && current.worker.isConnected() && !current.worker.isDead()) {
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
await createChildProcess(entry.cpu);
|
|
208
233
|
}
|
|
209
234
|
})().catch(function (e) {
|
|
210
235
|
lCore.display('[master] [cluster] [exit]', e);
|
|
@@ -212,7 +237,7 @@ async function run() {
|
|
|
212
237
|
});
|
|
213
238
|
}
|
|
214
239
|
/**
|
|
215
|
-
* ---
|
|
240
|
+
* --- 接收并执行本机命令行或其他服务器发来的 RPC 命令 ---
|
|
216
241
|
*/
|
|
217
242
|
function createRpcListener() {
|
|
218
243
|
http.createServer(function (req, res) {
|
|
@@ -291,7 +316,7 @@ function createRpcListener() {
|
|
|
291
316
|
res.end('Invalid pm2Action');
|
|
292
317
|
return;
|
|
293
318
|
}
|
|
294
|
-
// ---
|
|
319
|
+
// --- 先回复 Done 再执行 PM2,避免进程先退出,调用方收不到回复 ---
|
|
295
320
|
res.end('Done');
|
|
296
321
|
setTimeout(() => {
|
|
297
322
|
lCore.exec(`pm2 ${msg.pm2Action} ${msg.name}`).then((rtn) => {
|
|
@@ -314,18 +339,22 @@ function createRpcListener() {
|
|
|
314
339
|
res.end('Path not found');
|
|
315
340
|
return;
|
|
316
341
|
}
|
|
317
|
-
// ---
|
|
342
|
+
// --- 安装和重试合计最多 5 分钟,给 sendNpm 留 30 秒接收结果 ---
|
|
318
343
|
const npmTimeout = 300_000;
|
|
344
|
+
const npmDeadline = Date.now() + npmTimeout;
|
|
319
345
|
let rtn = await lCore.exec('npm i --omit=dev', {
|
|
320
346
|
'cwd': msg.path,
|
|
321
347
|
'timeout': npmTimeout,
|
|
322
348
|
});
|
|
323
349
|
if (rtn === false) {
|
|
324
350
|
// --- 部分项目可能存在 peerDependencies 冲突,失败后降级为 legacy-peer-deps 再试一次 ---
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
'
|
|
328
|
-
|
|
351
|
+
const remaining = npmDeadline - Date.now();
|
|
352
|
+
if (remaining > 0) {
|
|
353
|
+
rtn = await lCore.exec('npm i --omit=dev --legacy-peer-deps', {
|
|
354
|
+
'cwd': msg.path,
|
|
355
|
+
'timeout': remaining,
|
|
356
|
+
});
|
|
357
|
+
}
|
|
329
358
|
}
|
|
330
359
|
if (rtn === false) {
|
|
331
360
|
res.end('Exec failed');
|
|
@@ -454,7 +483,7 @@ function createRpcListener() {
|
|
|
454
483
|
return;
|
|
455
484
|
}
|
|
456
485
|
const rawList = await zip.getList();
|
|
457
|
-
/** ---
|
|
486
|
+
/** --- 通过路径检查的 ZIP 文件,路径都以 / 开头 --- */
|
|
458
487
|
const ls = {};
|
|
459
488
|
for (const archivePath in rawList) {
|
|
460
489
|
const normalizedPath = normalizeArchivePath(archivePath);
|
|
@@ -473,14 +502,12 @@ function createRpcListener() {
|
|
|
473
502
|
/** --- 本次部署涉及到的目录路径集合(不含开头/,含尾部/,根目录为空字符串) --- */
|
|
474
503
|
const touchedDirs = new Set();
|
|
475
504
|
for (const scanPath in ls) {
|
|
476
|
-
/** --- 带 / 开头的 zip 中文件完整路径,例如 "/www/pika/stc/index.ts" --- */
|
|
477
|
-
const scanFpath = scanPath.startsWith('/') ? scanPath : '/' + scanPath;
|
|
478
505
|
/** --- 纯路径中最后一个 / 的位置索引 --- */
|
|
479
|
-
const scanLio =
|
|
506
|
+
const scanLio = scanPath.lastIndexOf('/');
|
|
480
507
|
/** --- 纯路径,不以 / 开头,以 / 结尾,若是根路径就是空字符串,例如 "www/pika/" --- */
|
|
481
|
-
const scanPat =
|
|
508
|
+
const scanPat = scanPath.slice(1, scanLio + 1);
|
|
482
509
|
/** --- 纯文件名,例如 "index.ts" 或 "pika.cga" --- */
|
|
483
|
-
const scanFname =
|
|
510
|
+
const scanFname = scanPath.slice(scanLio + 1);
|
|
484
511
|
touchedDirs.add(scanPat);
|
|
485
512
|
if (scanFname.endsWith('.cga')) {
|
|
486
513
|
// --- 记录 .cga 锁定的同级目录(去掉 .cga 后缀的名字即为被锁定的目录名)---
|
|
@@ -493,7 +520,7 @@ function createRpcListener() {
|
|
|
493
520
|
}
|
|
494
521
|
// --- 补充扫描目标目录中现存的 kebab.json,兼容压缩包未携带 kebab.json 的情况 ---
|
|
495
522
|
for (const dir of touchedDirs) {
|
|
496
|
-
/** ---
|
|
523
|
+
/** --- 把目录拆成各级目录名,先检查当前目录,再一层层往上找 --- */
|
|
497
524
|
const dirs = dir ? dir.split('/').filter(Boolean) : [];
|
|
498
525
|
for (let i = dirs.length; i >= 0; --i) {
|
|
499
526
|
/** --- 当前要检查的目录路径,不含开头/,含尾部/,根目录为空字符串 --- */
|
|
@@ -531,15 +558,13 @@ function createRpcListener() {
|
|
|
531
558
|
'temp',
|
|
532
559
|
]);
|
|
533
560
|
for (const archivePath in ls) {
|
|
534
|
-
/** --- 带 / 开头的 zip 中文件完整路径,例如 "/www/pika/ctr/api.js" --- */
|
|
535
|
-
const fpath = archivePath.startsWith('/') ? archivePath : '/' + archivePath;
|
|
536
561
|
/** --- 纯路径中最后一个 / 的位置索引 --- */
|
|
537
|
-
const lio =
|
|
562
|
+
const lio = archivePath.lastIndexOf('/');
|
|
538
563
|
/** --- 纯路径,不以 / 开头,以 / 结尾,若是根路径就是空字符串,例如 "www/pika/ctr/" --- */
|
|
539
|
-
const pat =
|
|
564
|
+
const pat = archivePath.slice(1, lio + 1);
|
|
540
565
|
/** --- 纯文件名,例如 "api.js" --- */
|
|
541
|
-
const fname =
|
|
542
|
-
const dirs =
|
|
566
|
+
const fname = archivePath.slice(lio + 1);
|
|
567
|
+
const dirs = archivePath.slice(1).split('/').slice(0, -1);
|
|
543
568
|
if (dirs.some(seg => DEPLOY_EXCLUDE_DIRS.has(seg))) {
|
|
544
569
|
// --- 开发、依赖、缓存、构建产物目录不覆盖 ---
|
|
545
570
|
continue;
|
|
@@ -566,9 +591,9 @@ function createRpcListener() {
|
|
|
566
591
|
}
|
|
567
592
|
// --- 规则 1:若同级目录存在 xxx.cga,则 xxx 目录下所有内容不部署 ---
|
|
568
593
|
if (pat) {
|
|
569
|
-
/** ---
|
|
594
|
+
/** --- 当前目录或上级目录是否有同名 .cga 文件 --- */
|
|
570
595
|
let cgaBlocked = false;
|
|
571
|
-
/** ---
|
|
596
|
+
/** --- 逐层拼出的目录路径,如 a/、a/b/,检查是否有同名 .cga 文件 --- */
|
|
572
597
|
let accumulated = '';
|
|
573
598
|
for (const seg of pat.split('/').filter(Boolean)) {
|
|
574
599
|
accumulated += seg + '/';
|
|
@@ -582,16 +607,13 @@ function createRpcListener() {
|
|
|
582
607
|
}
|
|
583
608
|
}
|
|
584
609
|
// --- 规则 2:kebab 子项目目录中,仅允许部署 ctr/data/stc/view/lib/abox 子文件夹内的内容 ---
|
|
585
|
-
// --- 快速跳过:zip 中没有 kebab.json 时整个规则无需执行 ---
|
|
586
610
|
if (kebabProjectDirs.size > 0) {
|
|
587
|
-
// ---
|
|
588
|
-
// ---
|
|
589
|
-
|
|
590
|
-
// --- 改用 shortestMatch 则选根 "",backup 的第一段不在白名单中,正确排除 ---
|
|
591
|
-
/** --- 当前文件所属的最浅 kebab 子项目目录;无匹配则为 null --- */
|
|
611
|
+
// --- 同时属于多个 Kebab 项目时,按最外层项目的部署规则检查 ---
|
|
612
|
+
// --- 例如根项目不允许 backup/,backup/ 自带 kebab.json 也不能绕过 ---
|
|
613
|
+
/** --- 当前文件所属的最外层 Kebab 项目目录,找不到时为 null --- */
|
|
592
614
|
let shortestMatch = null;
|
|
593
615
|
for (const kdir of kebabProjectDirs) {
|
|
594
|
-
/** ---
|
|
616
|
+
/** --- kdir 是否比已选的项目目录更靠外(路径更短)--- */
|
|
595
617
|
const isShallower = shortestMatch === null || kdir.length < shortestMatch.length;
|
|
596
618
|
if (pat.startsWith(kdir) && isShallower) {
|
|
597
619
|
shortestMatch = kdir;
|
|
@@ -707,220 +729,68 @@ function createRpcListener() {
|
|
|
707
729
|
res.end('Invalid offset');
|
|
708
730
|
return;
|
|
709
731
|
}
|
|
732
|
+
if (msg.search && ((typeof msg.search !== 'string') || (msg.search.length > 500) || msg.search.includes('\0'))) {
|
|
733
|
+
res.end('Invalid search');
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
/** --- 搜索词用换行分隔,命中其中一个就算匹配 --- */
|
|
737
|
+
const search = msg.search ? msg.search.split('\n') : null;
|
|
738
|
+
/** --- CSV 返回字段数组,JSONL 返回解析后的对象 --- */
|
|
739
|
+
const list = [];
|
|
710
740
|
let total = 0;
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
741
|
+
let skipHeader = format === 'csv';
|
|
742
|
+
/**
|
|
743
|
+
* --- 统计匹配行数并取出当前页,跳过 CSV 表头 ---
|
|
744
|
+
* @param line 不含换行符的日志行
|
|
745
|
+
* @returns 无返回值
|
|
746
|
+
*/
|
|
747
|
+
const consumeLine = (line) => {
|
|
748
|
+
if (skipHeader) {
|
|
749
|
+
skipHeader = false;
|
|
714
750
|
return;
|
|
715
751
|
}
|
|
716
|
-
|
|
717
|
-
// --- shell 单引号安全转义(防止特殊字符破坏命令)---
|
|
718
|
-
const escaped = msg.search.replace(/'/g, "'\\''");
|
|
719
|
-
// --- 获取匹配行总数(grep -c 无匹配时退出码 1,|| echo 0 兜底)---
|
|
720
|
-
const countCmd = format === 'csv'
|
|
721
|
-
? `tail -n +2 "${logPath}" | grep -F -c '${escaped}' || echo 0`
|
|
722
|
-
: `grep -F -c '${escaped}' "${logPath}" || echo 0`;
|
|
723
|
-
const countRtn = await lCore.exec(countCmd);
|
|
724
|
-
if (countRtn !== false) {
|
|
725
|
-
total = parseInt(countRtn.trim()) || 0;
|
|
726
|
-
}
|
|
727
|
-
// --- 获取分页数据:第 offset+1 到 offset+limit 条匹配行(1-indexed)---
|
|
728
|
-
const from = offset + 1;
|
|
729
|
-
const to = offset + limit;
|
|
730
|
-
const dataCmd = format === 'csv'
|
|
731
|
-
? `tail -n +2 "${logPath}" | grep -F '${escaped}' | sed -n '${from},${to}p'`
|
|
732
|
-
: `grep -F '${escaped}' "${logPath}" | sed -n '${from},${to}p'`;
|
|
733
|
-
const dataRtn = await lCore.exec(dataCmd);
|
|
734
|
-
if (dataRtn === false) {
|
|
735
|
-
res.end(lText.stringifyJson({
|
|
736
|
-
'result': 1,
|
|
737
|
-
'list': [],
|
|
738
|
-
'total': total,
|
|
739
|
-
}));
|
|
752
|
+
if (search && !search.some(pattern => line.includes(pattern))) {
|
|
740
753
|
return;
|
|
741
754
|
}
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
*/
|
|
748
|
-
const sList = [];
|
|
749
|
-
for (const rawLine of dataRtn.split('\n')) {
|
|
750
|
-
if (!rawLine) {
|
|
751
|
-
continue;
|
|
752
|
-
}
|
|
753
|
-
if (format === 'jsonl') {
|
|
754
|
-
const obj = lText.parseJson(rawLine);
|
|
755
|
-
if (obj) {
|
|
756
|
-
sList.push(obj);
|
|
757
|
-
}
|
|
758
|
-
}
|
|
759
|
-
else {
|
|
760
|
-
const result = [];
|
|
761
|
-
let currentField = '';
|
|
762
|
-
let inQuotes = false;
|
|
763
|
-
for (let i = 0; i < rawLine.length; ++i) {
|
|
764
|
-
const char = rawLine[i];
|
|
765
|
-
if (char === '"') {
|
|
766
|
-
if (inQuotes && rawLine[i + 1] === '"') {
|
|
767
|
-
currentField += '"';
|
|
768
|
-
++i;
|
|
769
|
-
}
|
|
770
|
-
else {
|
|
771
|
-
inQuotes = !inQuotes;
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
else if (char === ',' && !inQuotes) {
|
|
775
|
-
result.push(currentField);
|
|
776
|
-
currentField = '';
|
|
777
|
-
}
|
|
778
|
-
else {
|
|
779
|
-
currentField += char;
|
|
780
|
-
}
|
|
781
|
-
}
|
|
782
|
-
result.push(currentField);
|
|
783
|
-
sList.push(result);
|
|
784
|
-
}
|
|
755
|
+
const index = total++;
|
|
756
|
+
// --- 搜索时按匹配行数分页,解析失败也占一行 ---
|
|
757
|
+
// --- 不搜索时跳过无效 JSON,继续读到当前页填满 ---
|
|
758
|
+
if (index < offset || list.length >= limit || search && index >= offset + limit) {
|
|
759
|
+
return;
|
|
785
760
|
}
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
}));
|
|
791
|
-
return;
|
|
792
|
-
}
|
|
793
|
-
// === 无搜索模式:wc -l 获取总行数,grep -b '^' 定位字节偏移直接跳至 offset ===
|
|
794
|
-
const wclRtn = await lCore.exec(`wc -l "${logPath}"`);
|
|
795
|
-
if (wclRtn !== false) {
|
|
796
|
-
const wclMatch = /^\s*(\d+)/.exec(wclRtn);
|
|
797
|
-
if (wclMatch) {
|
|
798
|
-
total = parseInt(wclMatch[1]);
|
|
799
|
-
if (format === 'csv') {
|
|
800
|
-
// --- csv 有表头,数据行数减 1 ---
|
|
801
|
-
total = Math.max(0, total - 1);
|
|
761
|
+
if (format === 'jsonl') {
|
|
762
|
+
const item = lText.parseJson(line);
|
|
763
|
+
if (item) {
|
|
764
|
+
list.push(item);
|
|
802
765
|
}
|
|
803
766
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
* --- 用 grep -b '^' 获取目标行的字节偏移,直接传给 createReadStream start 跳过 offset ---
|
|
807
|
-
* --- jsonl 无表头:跳过 offset 行,从第 offset+1 行开始读 ---
|
|
808
|
-
* --- csv 有表头:跳过表头+offset 行,从第 offset+2 行开始读 ---
|
|
809
|
-
*/
|
|
810
|
-
let startByte = 0;
|
|
811
|
-
/** --- offset 定位是否成功(offset=0 直接成功;offset>0 需 grep 定位)--- */
|
|
812
|
-
let offsetLocated = offset === 0;
|
|
813
|
-
if (offset > 0) {
|
|
814
|
-
const skipLines = format === 'jsonl' ? offset : offset + 1;
|
|
815
|
-
// --- sed -n '${N}{p;q}' 找到第 N 行后立即退出,使 grep 收到 SIGPIPE 提前终止 ---
|
|
816
|
-
const grepRtn = await lCore.exec(`grep -b '^' "${logPath}" | sed -n '${skipLines + 1}{p;q}'`);
|
|
817
|
-
if (grepRtn !== false) {
|
|
818
|
-
const grepMatch = /^(\d+):/.exec(grepRtn.trim());
|
|
819
|
-
if (grepMatch) {
|
|
820
|
-
startByte = parseInt(grepMatch[1]);
|
|
821
|
-
offsetLocated = true;
|
|
822
|
-
}
|
|
767
|
+
else if (!search || line) {
|
|
768
|
+
list.push(parseCsvLine(line));
|
|
823
769
|
}
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
res.end(lText.stringifyJson({
|
|
828
|
-
'result': 1,
|
|
829
|
-
'list': [],
|
|
830
|
-
'total': total,
|
|
831
|
-
}));
|
|
832
|
-
return;
|
|
833
|
-
}
|
|
834
|
-
/**
|
|
835
|
-
* --- csv 格式:string[][] 每行是字段数组,顺序与表头一致 ---
|
|
836
|
-
* --- [['H:i:s', unix, url, cookie, session, userAgent, realIp, cfIp, xIp, osMem, procMem, message], ...] ---
|
|
837
|
-
* --- jsonl 格式:object[] 每行是解析后的 JSON 对象 ---
|
|
838
|
-
* --- [{ time, unix, url, cookie, session, userAgent, realIp, cfIp, xIp, osMem, procMem, message }, ...] ---
|
|
839
|
-
*/
|
|
840
|
-
const rtn = await new Promise(resolve => {
|
|
841
|
-
const list = [];
|
|
842
|
-
/** --- 当前行号 --- */
|
|
843
|
-
let line = 0;
|
|
844
|
-
/** --- 当前行数据 --- */
|
|
770
|
+
};
|
|
771
|
+
// --- 文件只读一遍,同时统计行数并取出当前页;读失败时返回 500 ---
|
|
772
|
+
await new Promise((resolve, reject) => {
|
|
845
773
|
let packet = '';
|
|
846
|
-
lFs.createReadStream(logPath, {
|
|
847
|
-
|
|
848
|
-
'
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
return;
|
|
852
|
-
}
|
|
853
|
-
while (true) {
|
|
854
|
-
// --- 分包 ---
|
|
855
|
-
const index = buf.indexOf('\n');
|
|
856
|
-
if (index === -1) {
|
|
857
|
-
// --- 本次包还没有结束 ---
|
|
858
|
-
packet += buf;
|
|
859
|
-
break;
|
|
860
|
-
}
|
|
861
|
-
// --- 本次行结束了 ---
|
|
862
|
-
if (limit === 0) {
|
|
863
|
-
break;
|
|
864
|
-
}
|
|
865
|
-
packet += buf.slice(0, index);
|
|
866
|
-
buf = buf.slice(index + 1);
|
|
867
|
-
++line;
|
|
868
|
-
// --- startByte > 0 时已跳过 offset(及 csv 表头),从第一行起均为数据行 ---
|
|
869
|
-
// --- startByte === 0 且 csv 时仍需跳过表头(line > 1)---
|
|
870
|
-
if (format === 'csv' && startByte === 0 ? line > 1 : line >= 1) {
|
|
871
|
-
if (format === 'jsonl') {
|
|
872
|
-
const obj = lText.parseJson(packet);
|
|
873
|
-
if (obj) {
|
|
874
|
-
list.push(obj);
|
|
875
|
-
--limit;
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
else {
|
|
879
|
-
const result = [];
|
|
880
|
-
let currentField = '';
|
|
881
|
-
let inQuotes = false;
|
|
882
|
-
for (let i = 0; i < packet.length; ++i) {
|
|
883
|
-
const char = packet[i];
|
|
884
|
-
if (char === '"') {
|
|
885
|
-
if (inQuotes && packet[i + 1] === '"') {
|
|
886
|
-
currentField += '"';
|
|
887
|
-
++i;
|
|
888
|
-
}
|
|
889
|
-
else {
|
|
890
|
-
inQuotes = !inQuotes;
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
else if (char === ',' && !inQuotes) {
|
|
894
|
-
result.push(currentField);
|
|
895
|
-
currentField = '';
|
|
896
|
-
}
|
|
897
|
-
else {
|
|
898
|
-
currentField += char;
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
result.push(currentField);
|
|
902
|
-
list.push(result);
|
|
903
|
-
--limit;
|
|
904
|
-
}
|
|
905
|
-
}
|
|
906
|
-
// --- 处理结束 ---
|
|
774
|
+
lFs.createReadStream(logPath, { 'encoding': 'utf8' }).on('data', (chunk) => {
|
|
775
|
+
let start = 0;
|
|
776
|
+
let end = chunk.indexOf('\n');
|
|
777
|
+
while (end !== -1) {
|
|
778
|
+
consumeLine(packet + chunk.slice(start, end));
|
|
907
779
|
packet = '';
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
// --- 没粘连包 ---
|
|
911
|
-
break;
|
|
912
|
-
}
|
|
913
|
-
// --- 有粘连包 ---
|
|
780
|
+
start = end + 1;
|
|
781
|
+
end = chunk.indexOf('\n', start);
|
|
914
782
|
}
|
|
783
|
+
packet += chunk.slice(start);
|
|
915
784
|
}).on('end', () => {
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
785
|
+
if (packet) {
|
|
786
|
+
consumeLine(packet);
|
|
787
|
+
}
|
|
788
|
+
resolve();
|
|
789
|
+
}).on('error', reject);
|
|
920
790
|
});
|
|
921
791
|
res.end(lText.stringifyJson({
|
|
922
792
|
'result': 1,
|
|
923
|
-
'list':
|
|
793
|
+
'list': list,
|
|
924
794
|
'total': total,
|
|
925
795
|
}));
|
|
926
796
|
return;
|
|
@@ -968,7 +838,7 @@ function createRpcListener() {
|
|
|
968
838
|
res.end();
|
|
969
839
|
return;
|
|
970
840
|
}
|
|
971
|
-
// ---
|
|
841
|
+
// --- 直接发送文件流,不把整个文件读入内存或压缩;客户端断开时 pipeline 会关闭文件流 ---
|
|
972
842
|
try {
|
|
973
843
|
await stream.pipeline(fs.createReadStream(file.path, { 'start': 0, 'end': file.stat.size - 1 }), res);
|
|
974
844
|
}
|
|
@@ -1003,15 +873,22 @@ function createRpcListener() {
|
|
|
1003
873
|
res.end('Done');
|
|
1004
874
|
})().catch(function (e) {
|
|
1005
875
|
lCore.display('[master] [createRpcListener]', e);
|
|
876
|
+
if (res.headersSent) {
|
|
877
|
+
res.destroy();
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
res.writeHead(500);
|
|
881
|
+
res.end('Failed');
|
|
1006
882
|
});
|
|
1007
883
|
}).listen(lCore.globalConfig.rpcPort);
|
|
1008
884
|
}
|
|
1009
885
|
/**
|
|
1010
|
-
* --- 通知 worker
|
|
886
|
+
* --- 通知 worker 停止接收新连接,等它退出 ---
|
|
1011
887
|
* @param worker 要停止的 worker
|
|
888
|
+
* @param waitForever 是否一直等现有连接结束;stop 为 true,restart 或替换失联 worker 时为 false(最多等一小时)
|
|
1012
889
|
* @returns worker 退出后完成
|
|
1013
890
|
*/
|
|
1014
|
-
function stopWorker(worker) {
|
|
891
|
+
function stopWorker(worker, waitForever = true) {
|
|
1015
892
|
if (worker.isDead()) {
|
|
1016
893
|
return Promise.resolve();
|
|
1017
894
|
}
|
|
@@ -1021,7 +898,14 @@ function stopWorker(worker) {
|
|
|
1021
898
|
if (worker.isConnected()) {
|
|
1022
899
|
worker.send({
|
|
1023
900
|
'action': 'stop',
|
|
1024
|
-
'waitForever':
|
|
901
|
+
'waitForever': waitForever,
|
|
902
|
+
}, (e) => {
|
|
903
|
+
if (e) {
|
|
904
|
+
lCore.display(`[master] Failed to notify worker ${worker.process.pid ?? 'undefined'} to stop, using SIGTERM.`, e);
|
|
905
|
+
if (!worker.isDead()) {
|
|
906
|
+
worker.process.kill('SIGTERM');
|
|
907
|
+
}
|
|
908
|
+
}
|
|
1025
909
|
});
|
|
1026
910
|
return;
|
|
1027
911
|
}
|
|
@@ -1034,7 +918,7 @@ function stopWorker(worker) {
|
|
|
1034
918
|
});
|
|
1035
919
|
}
|
|
1036
920
|
/**
|
|
1037
|
-
* ---
|
|
921
|
+
* --- 通知所有 worker 停止,等它们退出后再退出 master ---
|
|
1038
922
|
* @returns 全部 worker 退出后完成
|
|
1039
923
|
*/
|
|
1040
924
|
async function gracefulStop() {
|
|
@@ -1044,7 +928,7 @@ async function gracefulStop() {
|
|
|
1044
928
|
stopping = true;
|
|
1045
929
|
stopPromise = (async () => {
|
|
1046
930
|
lCore.display('[master] Graceful stop started.');
|
|
1047
|
-
// ---
|
|
931
|
+
// --- 旧 worker 可能已从 workerList 移除,但还有请求没结束,也要等它退出 ---
|
|
1048
932
|
const workers = Object.values(cluster.workers ?? {}).filter((worker) => worker !== undefined);
|
|
1049
933
|
await Promise.all(workers.map(worker => stopWorker(worker)));
|
|
1050
934
|
lCore.display('[master] Graceful stop completed.');
|
|
@@ -1053,13 +937,25 @@ async function gracefulStop() {
|
|
|
1053
937
|
return stopPromise;
|
|
1054
938
|
}
|
|
1055
939
|
/**
|
|
1056
|
-
* ---
|
|
940
|
+
* --- 同时收到多次重启请求时,只执行一次重启 ---
|
|
941
|
+
* @returns 本次重启完成后结束,旧 worker 可能还在处理请求
|
|
942
|
+
*/
|
|
943
|
+
function restartWorkers() {
|
|
944
|
+
restartPromise ??= restartWorkerList().finally(() => {
|
|
945
|
+
restartPromise = null;
|
|
946
|
+
});
|
|
947
|
+
return restartPromise;
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* --- 重启所有 worker:先启动新进程,等它监听端口后再停止旧进程 ---
|
|
951
|
+
* @returns 本次重启完成后结束,旧 worker 可能还在处理请求
|
|
1057
952
|
*/
|
|
1058
|
-
async function
|
|
953
|
+
async function restartWorkerList() {
|
|
954
|
+
await workerCheckPromise;
|
|
1059
955
|
if (stopping) {
|
|
1060
956
|
return;
|
|
1061
957
|
}
|
|
1062
|
-
// ---
|
|
958
|
+
// --- 先把旧 worker 记下来,后面创建新 worker 会改动 workerList ---
|
|
1063
959
|
const oldEntries = [];
|
|
1064
960
|
for (const pid in workerList) {
|
|
1065
961
|
oldEntries.push({
|
|
@@ -1083,33 +979,45 @@ async function restartWorkers() {
|
|
|
1083
979
|
if (stopping) {
|
|
1084
980
|
return;
|
|
1085
981
|
}
|
|
1086
|
-
entry.worker.send({
|
|
1087
|
-
'action': 'stop'
|
|
1088
|
-
});
|
|
1089
982
|
delete workerList[entry.pid];
|
|
983
|
+
stopWorker(entry.worker, false).catch((e) => {
|
|
984
|
+
lCore.display('[master] [restartWorkerList] [stopWorker]', e);
|
|
985
|
+
});
|
|
1090
986
|
}
|
|
1091
987
|
}
|
|
1092
988
|
/**
|
|
1093
|
-
* ---
|
|
989
|
+
* --- 检查失联 worker,同一时间只检查一次;重启或停止时跳过 ---
|
|
990
|
+
* @returns 本次失联检查结束后完成
|
|
1094
991
|
*/
|
|
1095
|
-
|
|
1096
|
-
if (stopping) {
|
|
1097
|
-
return;
|
|
992
|
+
function checkWorkerLost() {
|
|
993
|
+
if (stopping || restartPromise) {
|
|
994
|
+
return Promise.resolve();
|
|
1098
995
|
}
|
|
996
|
+
workerCheckPromise ??= recoverLostWorkers().finally(() => {
|
|
997
|
+
workerCheckPromise = null;
|
|
998
|
+
});
|
|
999
|
+
return workerCheckPromise;
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* --- 替换超过 30 秒没发心跳的 worker ---
|
|
1003
|
+
* @returns 完成失联 worker 的替换
|
|
1004
|
+
*/
|
|
1005
|
+
async function recoverLostWorkers() {
|
|
1099
1006
|
const now = Date.now();
|
|
1100
1007
|
for (const pid in workerList) {
|
|
1101
|
-
|
|
1008
|
+
const entry = workerList[pid];
|
|
1009
|
+
if (now - entry.hbtime < 30000) {
|
|
1102
1010
|
// --- 距离上次心跳,小于 30 秒,正常 ---
|
|
1103
1011
|
// --- 子线程 10 秒发送一次心跳 ---
|
|
1104
1012
|
continue;
|
|
1105
1013
|
}
|
|
1106
|
-
// ---
|
|
1014
|
+
// --- 超过 30 秒没收到心跳,停止旧 worker 并启动一个新的,避免旧进程恢复后继续发心跳 ---
|
|
1107
1015
|
lCore.display(`[master] Worker ${pid} lost.`);
|
|
1108
|
-
workerList[pid].worker.send({
|
|
1109
|
-
'action': 'stop'
|
|
1110
|
-
});
|
|
1111
|
-
await createChildProcess(workerList[pid].cpu);
|
|
1112
1016
|
delete workerList[pid];
|
|
1017
|
+
stopWorker(entry.worker, false).catch((e) => {
|
|
1018
|
+
lCore.display('[master] [recoverLostWorkers] [stopWorker]', e);
|
|
1019
|
+
});
|
|
1020
|
+
await createChildProcess(entry.cpu);
|
|
1113
1021
|
}
|
|
1114
1022
|
}
|
|
1115
1023
|
/**
|
|
@@ -1121,6 +1029,10 @@ async function createChildProcess(cpu) {
|
|
|
1121
1029
|
return null;
|
|
1122
1030
|
}
|
|
1123
1031
|
const worker = cluster.fork();
|
|
1032
|
+
// --- 先监听 error 再做异步操作,避免 IPC 发送失败时导致 master 退出 ---
|
|
1033
|
+
worker.on('error', (e) => {
|
|
1034
|
+
lCore.display(`[master] Worker ${worker.process.pid ?? 'undefined'} error.`, e);
|
|
1035
|
+
});
|
|
1124
1036
|
if (!worker.process.pid) {
|
|
1125
1037
|
return null;
|
|
1126
1038
|
}
|
|
@@ -1227,10 +1139,9 @@ function startFileWatcher() {
|
|
|
1227
1139
|
/** --- 是否正在重启中 --- */
|
|
1228
1140
|
let restarting = false;
|
|
1229
1141
|
/**
|
|
1230
|
-
* ---
|
|
1231
|
-
* --- 这些目录若被监听会大量消耗系统 file watcher 配额(ENOSPC),必须跳过 ---
|
|
1142
|
+
* --- 跳过依赖、日志和临时目录,避免监听太多文件而用完系统额度(ENOSPC)---
|
|
1232
1143
|
*/
|
|
1233
|
-
const SKIP_DIRS = new Set(['
|
|
1144
|
+
const SKIP_DIRS = new Set(['node_modules', 'log', 'ftmp']);
|
|
1234
1145
|
/** --- 触发 worker 重载 --- */
|
|
1235
1146
|
const triggerReload = (formatName) => {
|
|
1236
1147
|
if (debounceTimer) {
|
|
@@ -1254,7 +1165,7 @@ function startFileWatcher() {
|
|
|
1254
1165
|
}, 500);
|
|
1255
1166
|
};
|
|
1256
1167
|
/**
|
|
1257
|
-
* ---
|
|
1168
|
+
* --- 逐层找出要监听的子目录,跳过 SKIP_DIRS 中的目录和隐藏目录 ---
|
|
1258
1169
|
* @param dir 当前目录路径
|
|
1259
1170
|
* @param result 收集结果数组
|
|
1260
1171
|
*/
|
|
@@ -1263,7 +1174,8 @@ function startFileWatcher() {
|
|
|
1263
1174
|
try {
|
|
1264
1175
|
entries = await fs.promises.readdir(dir, { 'withFileTypes': true });
|
|
1265
1176
|
}
|
|
1266
|
-
catch {
|
|
1177
|
+
catch (e) {
|
|
1178
|
+
lCore.display(`[HMR] Cannot scan directory: ${dir}`, e);
|
|
1267
1179
|
return;
|
|
1268
1180
|
}
|
|
1269
1181
|
for (const entry of entries) {
|
|
@@ -1280,7 +1192,7 @@ function startFileWatcher() {
|
|
|
1280
1192
|
}
|
|
1281
1193
|
};
|
|
1282
1194
|
/**
|
|
1283
|
-
* ---
|
|
1195
|
+
* --- 逐个监听筛选后的目录,避免连 .git 等已跳过的目录也一起监听 ---
|
|
1284
1196
|
* @param dir 要监听的根目录路径
|
|
1285
1197
|
*/
|
|
1286
1198
|
const watchDir = async (dir) => {
|
|
@@ -1315,14 +1227,12 @@ function startFileWatcher() {
|
|
|
1315
1227
|
}
|
|
1316
1228
|
lCore.display(`[HMR] Watching directory: ${dir} (${dirs.length} dirs)`);
|
|
1317
1229
|
};
|
|
1318
|
-
// ---
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
// --- 监听 mod/ 目录(用户模型)---
|
|
1325
|
-
watchDir(kebab.MOD_CWD).catch(() => { });
|
|
1230
|
+
// --- 监听用户项目、独立任务、自定义库及模型目录 ---
|
|
1231
|
+
for (const dir of [kebab.WWW_CWD, kebab.IND_CWD, kebab.LIB_CWD, kebab.MOD_CWD]) {
|
|
1232
|
+
watchDir(dir).catch((e) => {
|
|
1233
|
+
lCore.display(`[HMR] Cannot watch directory: ${dir}`, e);
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1326
1236
|
}
|
|
1327
1237
|
run().catch(function (e) {
|
|
1328
1238
|
lCore.display('[master] ------ [Process fatal Error] ------');
|