@maiyunnet/kebab 9.22.4 → 9.23.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/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 +186 -162
- package/index.d.ts +7 -2
- package/index.js +1 -1
- package/lib/text.d.ts +6 -4
- package/lib/text.js +11 -34
- package/lib/undici/response.d.ts +1 -1
- package/lib/undici.d.ts +5 -5
- package/lib/undici.js +7 -6
- package/package.json +3 -2
- package/sys/master.js +185 -279
- 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,7 +339,7 @@ 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;
|
|
319
344
|
const npmDeadline = Date.now() + npmTimeout;
|
|
320
345
|
let rtn = await lCore.exec('npm i --omit=dev', {
|
|
@@ -458,7 +483,7 @@ function createRpcListener() {
|
|
|
458
483
|
return;
|
|
459
484
|
}
|
|
460
485
|
const rawList = await zip.getList();
|
|
461
|
-
/** ---
|
|
486
|
+
/** --- 通过路径检查的 ZIP 文件,路径都以 / 开头 --- */
|
|
462
487
|
const ls = {};
|
|
463
488
|
for (const archivePath in rawList) {
|
|
464
489
|
const normalizedPath = normalizeArchivePath(archivePath);
|
|
@@ -477,14 +502,12 @@ function createRpcListener() {
|
|
|
477
502
|
/** --- 本次部署涉及到的目录路径集合(不含开头/,含尾部/,根目录为空字符串) --- */
|
|
478
503
|
const touchedDirs = new Set();
|
|
479
504
|
for (const scanPath in ls) {
|
|
480
|
-
/** --- 带 / 开头的 zip 中文件完整路径,例如 "/www/pika/stc/index.ts" --- */
|
|
481
|
-
const scanFpath = scanPath.startsWith('/') ? scanPath : '/' + scanPath;
|
|
482
505
|
/** --- 纯路径中最后一个 / 的位置索引 --- */
|
|
483
|
-
const scanLio =
|
|
506
|
+
const scanLio = scanPath.lastIndexOf('/');
|
|
484
507
|
/** --- 纯路径,不以 / 开头,以 / 结尾,若是根路径就是空字符串,例如 "www/pika/" --- */
|
|
485
|
-
const scanPat =
|
|
508
|
+
const scanPat = scanPath.slice(1, scanLio + 1);
|
|
486
509
|
/** --- 纯文件名,例如 "index.ts" 或 "pika.cga" --- */
|
|
487
|
-
const scanFname =
|
|
510
|
+
const scanFname = scanPath.slice(scanLio + 1);
|
|
488
511
|
touchedDirs.add(scanPat);
|
|
489
512
|
if (scanFname.endsWith('.cga')) {
|
|
490
513
|
// --- 记录 .cga 锁定的同级目录(去掉 .cga 后缀的名字即为被锁定的目录名)---
|
|
@@ -497,7 +520,7 @@ function createRpcListener() {
|
|
|
497
520
|
}
|
|
498
521
|
// --- 补充扫描目标目录中现存的 kebab.json,兼容压缩包未携带 kebab.json 的情况 ---
|
|
499
522
|
for (const dir of touchedDirs) {
|
|
500
|
-
/** ---
|
|
523
|
+
/** --- 把目录拆成各级目录名,先检查当前目录,再一层层往上找 --- */
|
|
501
524
|
const dirs = dir ? dir.split('/').filter(Boolean) : [];
|
|
502
525
|
for (let i = dirs.length; i >= 0; --i) {
|
|
503
526
|
/** --- 当前要检查的目录路径,不含开头/,含尾部/,根目录为空字符串 --- */
|
|
@@ -535,15 +558,13 @@ function createRpcListener() {
|
|
|
535
558
|
'temp',
|
|
536
559
|
]);
|
|
537
560
|
for (const archivePath in ls) {
|
|
538
|
-
/** --- 带 / 开头的 zip 中文件完整路径,例如 "/www/pika/ctr/api.js" --- */
|
|
539
|
-
const fpath = archivePath.startsWith('/') ? archivePath : '/' + archivePath;
|
|
540
561
|
/** --- 纯路径中最后一个 / 的位置索引 --- */
|
|
541
|
-
const lio =
|
|
562
|
+
const lio = archivePath.lastIndexOf('/');
|
|
542
563
|
/** --- 纯路径,不以 / 开头,以 / 结尾,若是根路径就是空字符串,例如 "www/pika/ctr/" --- */
|
|
543
|
-
const pat =
|
|
564
|
+
const pat = archivePath.slice(1, lio + 1);
|
|
544
565
|
/** --- 纯文件名,例如 "api.js" --- */
|
|
545
|
-
const fname =
|
|
546
|
-
const dirs =
|
|
566
|
+
const fname = archivePath.slice(lio + 1);
|
|
567
|
+
const dirs = archivePath.slice(1).split('/').slice(0, -1);
|
|
547
568
|
if (dirs.some(seg => DEPLOY_EXCLUDE_DIRS.has(seg))) {
|
|
548
569
|
// --- 开发、依赖、缓存、构建产物目录不覆盖 ---
|
|
549
570
|
continue;
|
|
@@ -570,9 +591,9 @@ function createRpcListener() {
|
|
|
570
591
|
}
|
|
571
592
|
// --- 规则 1:若同级目录存在 xxx.cga,则 xxx 目录下所有内容不部署 ---
|
|
572
593
|
if (pat) {
|
|
573
|
-
/** ---
|
|
594
|
+
/** --- 当前目录或上级目录是否有同名 .cga 文件 --- */
|
|
574
595
|
let cgaBlocked = false;
|
|
575
|
-
/** ---
|
|
596
|
+
/** --- 逐层拼出的目录路径,如 a/、a/b/,检查是否有同名 .cga 文件 --- */
|
|
576
597
|
let accumulated = '';
|
|
577
598
|
for (const seg of pat.split('/').filter(Boolean)) {
|
|
578
599
|
accumulated += seg + '/';
|
|
@@ -586,16 +607,13 @@ function createRpcListener() {
|
|
|
586
607
|
}
|
|
587
608
|
}
|
|
588
609
|
// --- 规则 2:kebab 子项目目录中,仅允许部署 ctr/data/stc/view/lib/abox 子文件夹内的内容 ---
|
|
589
|
-
// --- 快速跳过:zip 中没有 kebab.json 时整个规则无需执行 ---
|
|
590
610
|
if (kebabProjectDirs.size > 0) {
|
|
591
|
-
// ---
|
|
592
|
-
// ---
|
|
593
|
-
|
|
594
|
-
// --- 改用 shortestMatch 则选根 "",backup 的第一段不在白名单中,正确排除 ---
|
|
595
|
-
/** --- 当前文件所属的最浅 kebab 子项目目录;无匹配则为 null --- */
|
|
611
|
+
// --- 同时属于多个 Kebab 项目时,按最外层项目的部署规则检查 ---
|
|
612
|
+
// --- 例如根项目不允许 backup/,backup/ 自带 kebab.json 也不能绕过 ---
|
|
613
|
+
/** --- 当前文件所属的最外层 Kebab 项目目录,找不到时为 null --- */
|
|
596
614
|
let shortestMatch = null;
|
|
597
615
|
for (const kdir of kebabProjectDirs) {
|
|
598
|
-
/** ---
|
|
616
|
+
/** --- kdir 是否比已选的项目目录更靠外(路径更短)--- */
|
|
599
617
|
const isShallower = shortestMatch === null || kdir.length < shortestMatch.length;
|
|
600
618
|
if (pat.startsWith(kdir) && isShallower) {
|
|
601
619
|
shortestMatch = kdir;
|
|
@@ -711,220 +729,68 @@ function createRpcListener() {
|
|
|
711
729
|
res.end('Invalid offset');
|
|
712
730
|
return;
|
|
713
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 = [];
|
|
714
740
|
let total = 0;
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
741
|
+
let skipHeader = format === 'csv';
|
|
742
|
+
/**
|
|
743
|
+
* --- 统计匹配行数并取出当前页,跳过 CSV 表头 ---
|
|
744
|
+
* @param line 不含换行符的日志行
|
|
745
|
+
* @returns 无返回值
|
|
746
|
+
*/
|
|
747
|
+
const consumeLine = (line) => {
|
|
748
|
+
if (skipHeader) {
|
|
749
|
+
skipHeader = false;
|
|
718
750
|
return;
|
|
719
751
|
}
|
|
720
|
-
|
|
721
|
-
// --- shell 单引号安全转义(防止特殊字符破坏命令)---
|
|
722
|
-
const escaped = msg.search.replace(/'/g, "'\\''");
|
|
723
|
-
// --- 获取匹配行总数(grep -c 无匹配时退出码 1,|| echo 0 兜底)---
|
|
724
|
-
const countCmd = format === 'csv'
|
|
725
|
-
? `tail -n +2 "${logPath}" | grep -F -c '${escaped}' || echo 0`
|
|
726
|
-
: `grep -F -c '${escaped}' "${logPath}" || echo 0`;
|
|
727
|
-
const countRtn = await lCore.exec(countCmd);
|
|
728
|
-
if (countRtn !== false) {
|
|
729
|
-
total = parseInt(countRtn.trim()) || 0;
|
|
730
|
-
}
|
|
731
|
-
// --- 获取分页数据:第 offset+1 到 offset+limit 条匹配行(1-indexed)---
|
|
732
|
-
const from = offset + 1;
|
|
733
|
-
const to = offset + limit;
|
|
734
|
-
const dataCmd = format === 'csv'
|
|
735
|
-
? `tail -n +2 "${logPath}" | grep -F '${escaped}' | sed -n '${from},${to}p'`
|
|
736
|
-
: `grep -F '${escaped}' "${logPath}" | sed -n '${from},${to}p'`;
|
|
737
|
-
const dataRtn = await lCore.exec(dataCmd);
|
|
738
|
-
if (dataRtn === false) {
|
|
739
|
-
res.end(lText.stringifyJson({
|
|
740
|
-
'result': 1,
|
|
741
|
-
'list': [],
|
|
742
|
-
'total': total,
|
|
743
|
-
}));
|
|
752
|
+
if (search && !search.some(pattern => line.includes(pattern))) {
|
|
744
753
|
return;
|
|
745
754
|
}
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
*/
|
|
752
|
-
const sList = [];
|
|
753
|
-
for (const rawLine of dataRtn.split('\n')) {
|
|
754
|
-
if (!rawLine) {
|
|
755
|
-
continue;
|
|
756
|
-
}
|
|
757
|
-
if (format === 'jsonl') {
|
|
758
|
-
const obj = lText.parseJson(rawLine);
|
|
759
|
-
if (obj) {
|
|
760
|
-
sList.push(obj);
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
else {
|
|
764
|
-
const result = [];
|
|
765
|
-
let currentField = '';
|
|
766
|
-
let inQuotes = false;
|
|
767
|
-
for (let i = 0; i < rawLine.length; ++i) {
|
|
768
|
-
const char = rawLine[i];
|
|
769
|
-
if (char === '"') {
|
|
770
|
-
if (inQuotes && rawLine[i + 1] === '"') {
|
|
771
|
-
currentField += '"';
|
|
772
|
-
++i;
|
|
773
|
-
}
|
|
774
|
-
else {
|
|
775
|
-
inQuotes = !inQuotes;
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
else if (char === ',' && !inQuotes) {
|
|
779
|
-
result.push(currentField);
|
|
780
|
-
currentField = '';
|
|
781
|
-
}
|
|
782
|
-
else {
|
|
783
|
-
currentField += char;
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
result.push(currentField);
|
|
787
|
-
sList.push(result);
|
|
788
|
-
}
|
|
755
|
+
const index = total++;
|
|
756
|
+
// --- 搜索时按匹配行数分页,解析失败也占一行 ---
|
|
757
|
+
// --- 不搜索时跳过无效 JSON,继续读到当前页填满 ---
|
|
758
|
+
if (index < offset || list.length >= limit || search && index >= offset + limit) {
|
|
759
|
+
return;
|
|
789
760
|
}
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
}));
|
|
795
|
-
return;
|
|
796
|
-
}
|
|
797
|
-
// === 无搜索模式:wc -l 获取总行数,grep -b '^' 定位字节偏移直接跳至 offset ===
|
|
798
|
-
const wclRtn = await lCore.exec(`wc -l "${logPath}"`);
|
|
799
|
-
if (wclRtn !== false) {
|
|
800
|
-
const wclMatch = /^\s*(\d+)/.exec(wclRtn);
|
|
801
|
-
if (wclMatch) {
|
|
802
|
-
total = parseInt(wclMatch[1]);
|
|
803
|
-
if (format === 'csv') {
|
|
804
|
-
// --- csv 有表头,数据行数减 1 ---
|
|
805
|
-
total = Math.max(0, total - 1);
|
|
761
|
+
if (format === 'jsonl') {
|
|
762
|
+
const item = lText.parseJson(line);
|
|
763
|
+
if (item) {
|
|
764
|
+
list.push(item);
|
|
806
765
|
}
|
|
807
766
|
}
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
* --- 用 grep -b '^' 获取目标行的字节偏移,直接传给 createReadStream start 跳过 offset ---
|
|
811
|
-
* --- jsonl 无表头:跳过 offset 行,从第 offset+1 行开始读 ---
|
|
812
|
-
* --- csv 有表头:跳过表头+offset 行,从第 offset+2 行开始读 ---
|
|
813
|
-
*/
|
|
814
|
-
let startByte = 0;
|
|
815
|
-
/** --- offset 定位是否成功(offset=0 直接成功;offset>0 需 grep 定位)--- */
|
|
816
|
-
let offsetLocated = offset === 0;
|
|
817
|
-
if (offset > 0) {
|
|
818
|
-
const skipLines = format === 'jsonl' ? offset : offset + 1;
|
|
819
|
-
// --- sed -n '${N}{p;q}' 找到第 N 行后立即退出,使 grep 收到 SIGPIPE 提前终止 ---
|
|
820
|
-
const grepRtn = await lCore.exec(`grep -b '^' "${logPath}" | sed -n '${skipLines + 1}{p;q}'`);
|
|
821
|
-
if (grepRtn !== false) {
|
|
822
|
-
const grepMatch = /^(\d+):/.exec(grepRtn.trim());
|
|
823
|
-
if (grepMatch) {
|
|
824
|
-
startByte = parseInt(grepMatch[1]);
|
|
825
|
-
offsetLocated = true;
|
|
826
|
-
}
|
|
767
|
+
else if (!search || line) {
|
|
768
|
+
list.push(parseCsvLine(line));
|
|
827
769
|
}
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
res.end(lText.stringifyJson({
|
|
832
|
-
'result': 1,
|
|
833
|
-
'list': [],
|
|
834
|
-
'total': total,
|
|
835
|
-
}));
|
|
836
|
-
return;
|
|
837
|
-
}
|
|
838
|
-
/**
|
|
839
|
-
* --- csv 格式:string[][] 每行是字段数组,顺序与表头一致 ---
|
|
840
|
-
* --- [['H:i:s', unix, url, cookie, session, userAgent, realIp, cfIp, xIp, osMem, procMem, message], ...] ---
|
|
841
|
-
* --- jsonl 格式:object[] 每行是解析后的 JSON 对象 ---
|
|
842
|
-
* --- [{ time, unix, url, cookie, session, userAgent, realIp, cfIp, xIp, osMem, procMem, message }, ...] ---
|
|
843
|
-
*/
|
|
844
|
-
const rtn = await new Promise(resolve => {
|
|
845
|
-
const list = [];
|
|
846
|
-
/** --- 当前行号 --- */
|
|
847
|
-
let line = 0;
|
|
848
|
-
/** --- 当前行数据 --- */
|
|
770
|
+
};
|
|
771
|
+
// --- 文件只读一遍,同时统计行数并取出当前页;读失败时返回 500 ---
|
|
772
|
+
await new Promise((resolve, reject) => {
|
|
849
773
|
let packet = '';
|
|
850
|
-
lFs.createReadStream(logPath, {
|
|
851
|
-
|
|
852
|
-
'
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
return;
|
|
856
|
-
}
|
|
857
|
-
while (true) {
|
|
858
|
-
// --- 分包 ---
|
|
859
|
-
const index = buf.indexOf('\n');
|
|
860
|
-
if (index === -1) {
|
|
861
|
-
// --- 本次包还没有结束 ---
|
|
862
|
-
packet += buf;
|
|
863
|
-
break;
|
|
864
|
-
}
|
|
865
|
-
// --- 本次行结束了 ---
|
|
866
|
-
if (limit === 0) {
|
|
867
|
-
break;
|
|
868
|
-
}
|
|
869
|
-
packet += buf.slice(0, index);
|
|
870
|
-
buf = buf.slice(index + 1);
|
|
871
|
-
++line;
|
|
872
|
-
// --- startByte > 0 时已跳过 offset(及 csv 表头),从第一行起均为数据行 ---
|
|
873
|
-
// --- startByte === 0 且 csv 时仍需跳过表头(line > 1)---
|
|
874
|
-
if (format === 'csv' && startByte === 0 ? line > 1 : line >= 1) {
|
|
875
|
-
if (format === 'jsonl') {
|
|
876
|
-
const obj = lText.parseJson(packet);
|
|
877
|
-
if (obj) {
|
|
878
|
-
list.push(obj);
|
|
879
|
-
--limit;
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
else {
|
|
883
|
-
const result = [];
|
|
884
|
-
let currentField = '';
|
|
885
|
-
let inQuotes = false;
|
|
886
|
-
for (let i = 0; i < packet.length; ++i) {
|
|
887
|
-
const char = packet[i];
|
|
888
|
-
if (char === '"') {
|
|
889
|
-
if (inQuotes && packet[i + 1] === '"') {
|
|
890
|
-
currentField += '"';
|
|
891
|
-
++i;
|
|
892
|
-
}
|
|
893
|
-
else {
|
|
894
|
-
inQuotes = !inQuotes;
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
else if (char === ',' && !inQuotes) {
|
|
898
|
-
result.push(currentField);
|
|
899
|
-
currentField = '';
|
|
900
|
-
}
|
|
901
|
-
else {
|
|
902
|
-
currentField += char;
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
result.push(currentField);
|
|
906
|
-
list.push(result);
|
|
907
|
-
--limit;
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
// --- 处理结束 ---
|
|
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));
|
|
911
779
|
packet = '';
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
// --- 没粘连包 ---
|
|
915
|
-
break;
|
|
916
|
-
}
|
|
917
|
-
// --- 有粘连包 ---
|
|
780
|
+
start = end + 1;
|
|
781
|
+
end = chunk.indexOf('\n', start);
|
|
918
782
|
}
|
|
783
|
+
packet += chunk.slice(start);
|
|
919
784
|
}).on('end', () => {
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
785
|
+
if (packet) {
|
|
786
|
+
consumeLine(packet);
|
|
787
|
+
}
|
|
788
|
+
resolve();
|
|
789
|
+
}).on('error', reject);
|
|
924
790
|
});
|
|
925
791
|
res.end(lText.stringifyJson({
|
|
926
792
|
'result': 1,
|
|
927
|
-
'list':
|
|
793
|
+
'list': list,
|
|
928
794
|
'total': total,
|
|
929
795
|
}));
|
|
930
796
|
return;
|
|
@@ -972,7 +838,7 @@ function createRpcListener() {
|
|
|
972
838
|
res.end();
|
|
973
839
|
return;
|
|
974
840
|
}
|
|
975
|
-
// ---
|
|
841
|
+
// --- 直接发送文件流,不把整个文件读入内存或压缩;客户端断开时 pipeline 会关闭文件流 ---
|
|
976
842
|
try {
|
|
977
843
|
await stream.pipeline(fs.createReadStream(file.path, { 'start': 0, 'end': file.stat.size - 1 }), res);
|
|
978
844
|
}
|
|
@@ -1007,15 +873,22 @@ function createRpcListener() {
|
|
|
1007
873
|
res.end('Done');
|
|
1008
874
|
})().catch(function (e) {
|
|
1009
875
|
lCore.display('[master] [createRpcListener]', e);
|
|
876
|
+
if (res.headersSent) {
|
|
877
|
+
res.destroy();
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
res.writeHead(500);
|
|
881
|
+
res.end('Failed');
|
|
1010
882
|
});
|
|
1011
883
|
}).listen(lCore.globalConfig.rpcPort);
|
|
1012
884
|
}
|
|
1013
885
|
/**
|
|
1014
|
-
* --- 通知 worker
|
|
886
|
+
* --- 通知 worker 停止接收新连接,等它退出 ---
|
|
1015
887
|
* @param worker 要停止的 worker
|
|
888
|
+
* @param waitForever 是否一直等现有连接结束;stop 为 true,restart 或替换失联 worker 时为 false(最多等一小时)
|
|
1016
889
|
* @returns worker 退出后完成
|
|
1017
890
|
*/
|
|
1018
|
-
function stopWorker(worker) {
|
|
891
|
+
function stopWorker(worker, waitForever = true) {
|
|
1019
892
|
if (worker.isDead()) {
|
|
1020
893
|
return Promise.resolve();
|
|
1021
894
|
}
|
|
@@ -1025,7 +898,14 @@ function stopWorker(worker) {
|
|
|
1025
898
|
if (worker.isConnected()) {
|
|
1026
899
|
worker.send({
|
|
1027
900
|
'action': 'stop',
|
|
1028
|
-
'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
|
+
}
|
|
1029
909
|
});
|
|
1030
910
|
return;
|
|
1031
911
|
}
|
|
@@ -1038,7 +918,7 @@ function stopWorker(worker) {
|
|
|
1038
918
|
});
|
|
1039
919
|
}
|
|
1040
920
|
/**
|
|
1041
|
-
* ---
|
|
921
|
+
* --- 通知所有 worker 停止,等它们退出后再退出 master ---
|
|
1042
922
|
* @returns 全部 worker 退出后完成
|
|
1043
923
|
*/
|
|
1044
924
|
async function gracefulStop() {
|
|
@@ -1048,7 +928,7 @@ async function gracefulStop() {
|
|
|
1048
928
|
stopping = true;
|
|
1049
929
|
stopPromise = (async () => {
|
|
1050
930
|
lCore.display('[master] Graceful stop started.');
|
|
1051
|
-
// ---
|
|
931
|
+
// --- 旧 worker 可能已从 workerList 移除,但还有请求没结束,也要等它退出 ---
|
|
1052
932
|
const workers = Object.values(cluster.workers ?? {}).filter((worker) => worker !== undefined);
|
|
1053
933
|
await Promise.all(workers.map(worker => stopWorker(worker)));
|
|
1054
934
|
lCore.display('[master] Graceful stop completed.');
|
|
@@ -1057,13 +937,25 @@ async function gracefulStop() {
|
|
|
1057
937
|
return stopPromise;
|
|
1058
938
|
}
|
|
1059
939
|
/**
|
|
1060
|
-
* ---
|
|
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 可能还在处理请求
|
|
1061
952
|
*/
|
|
1062
|
-
async function
|
|
953
|
+
async function restartWorkerList() {
|
|
954
|
+
await workerCheckPromise;
|
|
1063
955
|
if (stopping) {
|
|
1064
956
|
return;
|
|
1065
957
|
}
|
|
1066
|
-
// ---
|
|
958
|
+
// --- 先把旧 worker 记下来,后面创建新 worker 会改动 workerList ---
|
|
1067
959
|
const oldEntries = [];
|
|
1068
960
|
for (const pid in workerList) {
|
|
1069
961
|
oldEntries.push({
|
|
@@ -1087,33 +979,45 @@ async function restartWorkers() {
|
|
|
1087
979
|
if (stopping) {
|
|
1088
980
|
return;
|
|
1089
981
|
}
|
|
1090
|
-
entry.worker.send({
|
|
1091
|
-
'action': 'stop'
|
|
1092
|
-
});
|
|
1093
982
|
delete workerList[entry.pid];
|
|
983
|
+
stopWorker(entry.worker, false).catch((e) => {
|
|
984
|
+
lCore.display('[master] [restartWorkerList] [stopWorker]', e);
|
|
985
|
+
});
|
|
1094
986
|
}
|
|
1095
987
|
}
|
|
1096
988
|
/**
|
|
1097
|
-
* ---
|
|
989
|
+
* --- 检查失联 worker,同一时间只检查一次;重启或停止时跳过 ---
|
|
990
|
+
* @returns 本次失联检查结束后完成
|
|
1098
991
|
*/
|
|
1099
|
-
|
|
1100
|
-
if (stopping) {
|
|
1101
|
-
return;
|
|
992
|
+
function checkWorkerLost() {
|
|
993
|
+
if (stopping || restartPromise) {
|
|
994
|
+
return Promise.resolve();
|
|
1102
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() {
|
|
1103
1006
|
const now = Date.now();
|
|
1104
1007
|
for (const pid in workerList) {
|
|
1105
|
-
|
|
1008
|
+
const entry = workerList[pid];
|
|
1009
|
+
if (now - entry.hbtime < 30000) {
|
|
1106
1010
|
// --- 距离上次心跳,小于 30 秒,正常 ---
|
|
1107
1011
|
// --- 子线程 10 秒发送一次心跳 ---
|
|
1108
1012
|
continue;
|
|
1109
1013
|
}
|
|
1110
|
-
// ---
|
|
1014
|
+
// --- 超过 30 秒没收到心跳,停止旧 worker 并启动一个新的,避免旧进程恢复后继续发心跳 ---
|
|
1111
1015
|
lCore.display(`[master] Worker ${pid} lost.`);
|
|
1112
|
-
workerList[pid].worker.send({
|
|
1113
|
-
'action': 'stop'
|
|
1114
|
-
});
|
|
1115
|
-
await createChildProcess(workerList[pid].cpu);
|
|
1116
1016
|
delete workerList[pid];
|
|
1017
|
+
stopWorker(entry.worker, false).catch((e) => {
|
|
1018
|
+
lCore.display('[master] [recoverLostWorkers] [stopWorker]', e);
|
|
1019
|
+
});
|
|
1020
|
+
await createChildProcess(entry.cpu);
|
|
1117
1021
|
}
|
|
1118
1022
|
}
|
|
1119
1023
|
/**
|
|
@@ -1125,6 +1029,10 @@ async function createChildProcess(cpu) {
|
|
|
1125
1029
|
return null;
|
|
1126
1030
|
}
|
|
1127
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
|
+
});
|
|
1128
1036
|
if (!worker.process.pid) {
|
|
1129
1037
|
return null;
|
|
1130
1038
|
}
|
|
@@ -1231,10 +1139,9 @@ function startFileWatcher() {
|
|
|
1231
1139
|
/** --- 是否正在重启中 --- */
|
|
1232
1140
|
let restarting = false;
|
|
1233
1141
|
/**
|
|
1234
|
-
* ---
|
|
1235
|
-
* --- 这些目录若被监听会大量消耗系统 file watcher 配额(ENOSPC),必须跳过 ---
|
|
1142
|
+
* --- 跳过依赖、日志和临时目录,避免监听太多文件而用完系统额度(ENOSPC)---
|
|
1236
1143
|
*/
|
|
1237
|
-
const SKIP_DIRS = new Set(['
|
|
1144
|
+
const SKIP_DIRS = new Set(['node_modules', 'log', 'ftmp']);
|
|
1238
1145
|
/** --- 触发 worker 重载 --- */
|
|
1239
1146
|
const triggerReload = (formatName) => {
|
|
1240
1147
|
if (debounceTimer) {
|
|
@@ -1258,7 +1165,7 @@ function startFileWatcher() {
|
|
|
1258
1165
|
}, 500);
|
|
1259
1166
|
};
|
|
1260
1167
|
/**
|
|
1261
|
-
* ---
|
|
1168
|
+
* --- 逐层找出要监听的子目录,跳过 SKIP_DIRS 中的目录和隐藏目录 ---
|
|
1262
1169
|
* @param dir 当前目录路径
|
|
1263
1170
|
* @param result 收集结果数组
|
|
1264
1171
|
*/
|
|
@@ -1267,7 +1174,8 @@ function startFileWatcher() {
|
|
|
1267
1174
|
try {
|
|
1268
1175
|
entries = await fs.promises.readdir(dir, { 'withFileTypes': true });
|
|
1269
1176
|
}
|
|
1270
|
-
catch {
|
|
1177
|
+
catch (e) {
|
|
1178
|
+
lCore.display(`[HMR] Cannot scan directory: ${dir}`, e);
|
|
1271
1179
|
return;
|
|
1272
1180
|
}
|
|
1273
1181
|
for (const entry of entries) {
|
|
@@ -1284,7 +1192,7 @@ function startFileWatcher() {
|
|
|
1284
1192
|
}
|
|
1285
1193
|
};
|
|
1286
1194
|
/**
|
|
1287
|
-
* ---
|
|
1195
|
+
* --- 逐个监听筛选后的目录,避免连 .git 等已跳过的目录也一起监听 ---
|
|
1288
1196
|
* @param dir 要监听的根目录路径
|
|
1289
1197
|
*/
|
|
1290
1198
|
const watchDir = async (dir) => {
|
|
@@ -1319,14 +1227,12 @@ function startFileWatcher() {
|
|
|
1319
1227
|
}
|
|
1320
1228
|
lCore.display(`[HMR] Watching directory: ${dir} (${dirs.length} dirs)`);
|
|
1321
1229
|
};
|
|
1322
|
-
// ---
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
// --- 监听 mod/ 目录(用户模型)---
|
|
1329
|
-
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
|
+
}
|
|
1330
1236
|
}
|
|
1331
1237
|
run().catch(function (e) {
|
|
1332
1238
|
lCore.display('[master] ------ [Process fatal Error] ------');
|