dsh-ops-kit 0.3.8 → 0.4.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/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/client.js +1683 -141
- package/index.js +1252 -86
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -2
package/index.js
CHANGED
|
@@ -495,6 +495,14 @@ function createApiHandler({ connection } = {}) {
|
|
|
495
495
|
if (typeof body.intervalMinutes === 'number') patch.intervalMinutes = Math.max(1, Math.min(Math.round(body.intervalMinutes), 1440))
|
|
496
496
|
if (typeof body.diskWarnPercent === 'number') patch.diskWarnPercent = Math.max(50, Math.min(Math.round(body.diskWarnPercent), 99))
|
|
497
497
|
if (typeof body.metricsMinutes === 'number') patch.metricsMinutes = Math.max(1, Math.min(Math.round(body.metricsMinutes), 60))
|
|
498
|
+
if (body.uiMode === 'simple' || body.uiMode === 'pro') patch.uiMode = body.uiMode
|
|
499
|
+
if (typeof body.logKeepDays === 'number') patch.logKeepDays = Math.max(1, Math.min(Math.round(body.logKeepDays), 90))
|
|
500
|
+
if (typeof body.logJournalMb === 'number') patch.logJournalMb = Math.max(50, Math.min(Math.round(body.logJournalMb), 4096))
|
|
501
|
+
if (typeof body.logAutoEnabled === 'boolean') patch.logAutoEnabled = body.logAutoEnabled
|
|
502
|
+
if (typeof body.logAutoHour === 'number') patch.logAutoHour = Math.max(0, Math.min(Math.round(body.logAutoHour), 23))
|
|
503
|
+
if (typeof body.logAutoMinute === 'number') patch.logAutoMinute = Math.max(0, Math.min(Math.round(body.logAutoMinute), 59))
|
|
504
|
+
if (typeof body.logAutoMinDisk === 'number') patch.logAutoMinDisk = Math.max(50, Math.min(Math.round(body.logAutoMinDisk), 99))
|
|
505
|
+
if (typeof body.logGrowAlertMb === 'number') patch.logGrowAlertMb = Math.max(50, Math.min(Math.round(body.logGrowAlertMb), 10240))
|
|
498
506
|
if (typeof body.aiEnabled === 'boolean') patch.aiEnabled = body.aiEnabled
|
|
499
507
|
if (typeof body.aiProvider === 'string') patch.aiProvider = body.aiProvider.slice(0, 80)
|
|
500
508
|
if (typeof body.aiModel === 'string') patch.aiModel = body.aiModel.slice(0, 120)
|
|
@@ -550,7 +558,8 @@ function createApiHandler({ connection } = {}) {
|
|
|
550
558
|
return
|
|
551
559
|
}
|
|
552
560
|
const cfg = pickHost(await loadHosts(), body.host)
|
|
553
|
-
|
|
561
|
+
const result = await audited(cfg, `服务 ${action}`, String(body.service ?? ''), () => hostAction('service', cfg, String(body.service ?? ''), action))
|
|
562
|
+
sendJson(res, 200, result)
|
|
554
563
|
return
|
|
555
564
|
}
|
|
556
565
|
|
|
@@ -610,7 +619,10 @@ function createApiHandler({ connection } = {}) {
|
|
|
610
619
|
const body = (await readBody(req)) || {}
|
|
611
620
|
if (body.confirm !== true) { sendJson(res, 400, { error: 'cleanup needs confirm=true' }); return }
|
|
612
621
|
const cfg = pickHost(await loadHosts(), body.host)
|
|
613
|
-
|
|
622
|
+
const detail = Array.isArray(body.paths) && body.paths.length
|
|
623
|
+
? `${body.paths.length} 个选中文件${body.includeJournal === false ? '' : ' + journal'}`
|
|
624
|
+
: 'journal 保留 200MB;删除 7 天前的轮转日志'
|
|
625
|
+
sendJson(res, 200, await audited(cfg, '清理旧日志', detail, () => cleanupDisk(cfg, body)))
|
|
614
626
|
return
|
|
615
627
|
}
|
|
616
628
|
|
|
@@ -658,7 +670,11 @@ function createApiHandler({ connection } = {}) {
|
|
|
658
670
|
|
|
659
671
|
if (route === 'tail' && method === 'GET') {
|
|
660
672
|
const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
|
|
661
|
-
sendJson(res, 200, await tailLog(cfg, url.searchParams.get('source') ?? '', url.searchParams.get('lines') ?? 200
|
|
673
|
+
sendJson(res, 200, await tailLog(cfg, url.searchParams.get('source') ?? '', url.searchParams.get('lines') ?? 200, {
|
|
674
|
+
sinceMinutes: url.searchParams.get('since'),
|
|
675
|
+
grep: url.searchParams.get('grep'),
|
|
676
|
+
level: url.searchParams.get('level'),
|
|
677
|
+
}))
|
|
662
678
|
return
|
|
663
679
|
}
|
|
664
680
|
|
|
@@ -671,7 +687,11 @@ function createApiHandler({ connection } = {}) {
|
|
|
671
687
|
|
|
672
688
|
if (route === 'files' && method === 'GET') {
|
|
673
689
|
const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
|
|
674
|
-
|
|
690
|
+
const listing = await listDir(cfg, url.searchParams.get('path') ?? '/')
|
|
691
|
+
if (url.searchParams.get('dirs') === '1') {
|
|
692
|
+
listing.entries = listing.entries.filter(entry => entry.dir || entry.link)
|
|
693
|
+
}
|
|
694
|
+
sendJson(res, 200, listing)
|
|
675
695
|
return
|
|
676
696
|
}
|
|
677
697
|
|
|
@@ -691,7 +711,12 @@ function createApiHandler({ connection } = {}) {
|
|
|
691
711
|
if (route === 'fs' && method === 'POST') {
|
|
692
712
|
const body = (await readBody(req)) || {}
|
|
693
713
|
const cfg = pickHost(await loadHosts(), body.host)
|
|
694
|
-
|
|
714
|
+
const fsAct = String(body.action ?? '')
|
|
715
|
+
const fsDetail = Array.isArray(body.paths) && body.paths.length > 1
|
|
716
|
+
? `${body.paths.length} 项(${String(body.paths[0]).split('/').pop()} 等)`
|
|
717
|
+
: String(body.path || (Array.isArray(body.paths) ? body.paths[0] : '') || '')
|
|
718
|
+
const result = await audited(cfg, `文件 ${fsAct}`, fsDetail, () => fsAction(cfg, fsAct, String(body.path ?? ''), body.confirm, body))
|
|
719
|
+
sendJson(res, 200, result)
|
|
695
720
|
return
|
|
696
721
|
}
|
|
697
722
|
|
|
@@ -787,8 +812,10 @@ function createApiHandler({ connection } = {}) {
|
|
|
787
812
|
const all = await loadMonitors()
|
|
788
813
|
const list = all[cfg.name] || []
|
|
789
814
|
if (body.action === 'remove') {
|
|
815
|
+
const removed = list.find(item => item.id === body.id)
|
|
790
816
|
all[cfg.name] = list.filter(item => item.id !== body.id)
|
|
791
817
|
await saveMonitors(all)
|
|
818
|
+
await appendAudit({ host: cfg.name, action: '删除监控', detail: removed ? (removed.label || removed.target) : String(body.id ?? '') })
|
|
792
819
|
sendJson(res, 200, { host: cfg.name, monitors: all[cfg.name] })
|
|
793
820
|
return
|
|
794
821
|
}
|
|
@@ -799,6 +826,7 @@ function createApiHandler({ connection } = {}) {
|
|
|
799
826
|
if (body.target !== undefined) monitor.target = String(body.target).trim().slice(0, 200)
|
|
800
827
|
if (body.label !== undefined) monitor.label = String(body.label).trim().slice(0, 40)
|
|
801
828
|
if (body.intervalMinutes !== undefined) monitor.intervalMinutes = Math.max(1, Math.min(Number(body.intervalMinutes) || 5, 1440))
|
|
829
|
+
if (body.maxAttempts !== undefined) monitor.maxAttempts = Math.max(1, Math.min(Number(body.maxAttempts) || 3, 10))
|
|
802
830
|
if (body.language !== undefined) monitor.language = ['shell', 'python', 'js'].includes(body.language) ? body.language : monitor.language
|
|
803
831
|
if (body.script !== undefined) monitor.script = String(body.script).slice(0, 4000)
|
|
804
832
|
await saveMonitors(all)
|
|
@@ -822,6 +850,10 @@ function createApiHandler({ connection } = {}) {
|
|
|
822
850
|
})
|
|
823
851
|
return
|
|
824
852
|
}
|
|
853
|
+
if (body.action === 'bulk') {
|
|
854
|
+
sendJson(res, 200, await addMonitorsBulk(cfg, body.items || []))
|
|
855
|
+
return
|
|
856
|
+
}
|
|
825
857
|
if (body.action === 'diagnose' && body.id) {
|
|
826
858
|
const monitor = list.find(item => item.id === body.id)
|
|
827
859
|
if (!monitor) { sendJson(res, 404, { error: 'monitor not found' }); return }
|
|
@@ -834,6 +866,7 @@ function createApiHandler({ connection } = {}) {
|
|
|
834
866
|
target: String(body.target ?? '').trim().slice(0, 200),
|
|
835
867
|
label: String(body.label ?? '').trim().slice(0, 40),
|
|
836
868
|
intervalMinutes: Math.max(1, Math.min(Number(body.intervalMinutes) || 5, 1440)),
|
|
869
|
+
maxAttempts: Math.max(1, Math.min(Number(body.maxAttempts) || 3, 10)),
|
|
837
870
|
createdAt: new Date().toISOString(),
|
|
838
871
|
...(['shell', 'python', 'js'].includes(body.language) ? { language: body.language } : {}),
|
|
839
872
|
...(body.script ? { script: String(body.script).slice(0, 4000) } : {}),
|
|
@@ -861,8 +894,12 @@ function createApiHandler({ connection } = {}) {
|
|
|
861
894
|
if (route === 'backups' && method === 'POST') {
|
|
862
895
|
const body = (await readBody(req)) || {}
|
|
863
896
|
const cfg = pickHost(await loadHosts(), body.host)
|
|
864
|
-
if (body.action === 'restore') {
|
|
897
|
+
if (body.action === 'restore') {
|
|
898
|
+
sendJson(res, 200, await audited(cfg, '恢复备份', String(body.id ?? ''), () => restoreBackup(cfg, body.id)))
|
|
899
|
+
return
|
|
900
|
+
}
|
|
865
901
|
if (body.action === 'remove') {
|
|
902
|
+
await appendAudit({ host: cfg.name, action: '删除备份', detail: String(body.id ?? '') })
|
|
866
903
|
const all = await loadJsonFile('backups.json', {})
|
|
867
904
|
const list = all[cfg.name] || []
|
|
868
905
|
const record = list.find(item => item.id === body.id)
|
|
@@ -872,7 +909,7 @@ function createApiHandler({ connection } = {}) {
|
|
|
872
909
|
sendJson(res, 200, { host: cfg.name, backups: all[cfg.name] })
|
|
873
910
|
return
|
|
874
911
|
}
|
|
875
|
-
sendJson(res, 200, await runBackup(cfg, body))
|
|
912
|
+
sendJson(res, 200, await audited(cfg, '执行备份', `${body.type === 'mysql' ? (body.database || '全部数据库') : body.path || '/'}`, () => runBackup(cfg, body)))
|
|
876
913
|
return
|
|
877
914
|
}
|
|
878
915
|
|
|
@@ -950,7 +987,7 @@ function createApiHandler({ connection } = {}) {
|
|
|
950
987
|
}
|
|
951
988
|
const job = list.find(item => item.id === body.id) || body.job
|
|
952
989
|
if (!job) { sendJson(res, 404, { error: '发布任务不存在' }); return }
|
|
953
|
-
sendJson(res, 200, await runDeploy(cfg, job))
|
|
990
|
+
sendJson(res, 200, await audited(cfg, '执行发布', job.name || job.dir, () => runDeploy(cfg, job)))
|
|
954
991
|
return
|
|
955
992
|
}
|
|
956
993
|
|
|
@@ -993,6 +1030,192 @@ function createApiHandler({ connection } = {}) {
|
|
|
993
1030
|
return
|
|
994
1031
|
}
|
|
995
1032
|
|
|
1033
|
+
if (route === 'file-text' && method === 'GET') {
|
|
1034
|
+
const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
|
|
1035
|
+
sendJson(res, 200, await readTextFile(cfg, url.searchParams.get('path') ?? ''))
|
|
1036
|
+
return
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
if (route === 'file-text' && method === 'POST') {
|
|
1040
|
+
const body = (await readBody(req)) || {}
|
|
1041
|
+
const cfg = pickHost(await loadHosts(), body.host)
|
|
1042
|
+
sendJson(res, 200, await writeTextFile(cfg, String(body.path ?? ''), body.content))
|
|
1043
|
+
return
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
if (route === 'upload-status' && method === 'GET') {
|
|
1047
|
+
const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
|
|
1048
|
+
sendJson(res, 200, await uploadStatus(cfg, url.searchParams.get('path') ?? ''))
|
|
1049
|
+
return
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
if (route === 'upload-chunk' && method === 'POST') {
|
|
1053
|
+
const body = (await readBody(req)) || {}
|
|
1054
|
+
const cfg = pickHost(await loadHosts(), body.host)
|
|
1055
|
+
sendJson(res, 200, await uploadChunk(cfg, String(body.path ?? ''), body.offset, body.base64))
|
|
1056
|
+
return
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
if (route === 'upload-finish' && method === 'POST') {
|
|
1060
|
+
const body = (await readBody(req)) || {}
|
|
1061
|
+
const cfg = pickHost(await loadHosts(), body.host)
|
|
1062
|
+
sendJson(res, 200, await uploadFinish(cfg, String(body.path ?? '')))
|
|
1063
|
+
return
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
if (route === 'download-chunk' && method === 'GET') {
|
|
1067
|
+
const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
|
|
1068
|
+
sendJson(res, 200, await downloadChunk(cfg, url.searchParams.get('path') ?? '', url.searchParams.get('offset'), url.searchParams.get('length')))
|
|
1069
|
+
return
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
if (route === 'templates' && method === 'GET') {
|
|
1073
|
+
const all = await loadTemplates()
|
|
1074
|
+
sendJson(res, 200, { templates: all.templates })
|
|
1075
|
+
return
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
if (route === 'templates' && method === 'POST') {
|
|
1079
|
+
const body = (await readBody(req)) || {}
|
|
1080
|
+
const all = await loadTemplates()
|
|
1081
|
+
if (body.action === 'remove') {
|
|
1082
|
+
all.templates = all.templates.filter(item => item.id !== body.id)
|
|
1083
|
+
await saveTemplates(all)
|
|
1084
|
+
sendJson(res, 200, { templates: all.templates })
|
|
1085
|
+
return
|
|
1086
|
+
}
|
|
1087
|
+
if (body.action === 'apply') {
|
|
1088
|
+
const template = all.templates.find(item => item.id === body.id)
|
|
1089
|
+
if (!template) { sendJson(res, 404, { error: 'template not found' }); return }
|
|
1090
|
+
const hostsList = (await loadHosts()).hosts
|
|
1091
|
+
const hosts = Array.isArray(body.hosts) && body.hosts.length ? body.hosts : hostsList.map(cfg => cfg.name)
|
|
1092
|
+
sendJson(res, 200, await applyTemplate(template, hosts))
|
|
1093
|
+
return
|
|
1094
|
+
}
|
|
1095
|
+
const items = (body.items || []).map(sanitizeMonitorItem).filter(Boolean)
|
|
1096
|
+
if (items.length === 0) { sendJson(res, 400, { error: 'template has no monitors' }); return }
|
|
1097
|
+
const template = { id: body.id || `t${Date.now().toString(36)}`, name: String(body.name || '模板').slice(0, 40), items, createdAt: new Date().toISOString() }
|
|
1098
|
+
all.templates = body.id ? all.templates.map(item => item.id === body.id ? { ...item, ...template } : item) : [...all.templates, template]
|
|
1099
|
+
await saveTemplates(all)
|
|
1100
|
+
sendJson(res, 200, { templates: all.templates, template })
|
|
1101
|
+
return
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
if (route === 'services' && method === 'GET') {
|
|
1105
|
+
const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
|
|
1106
|
+
sendJson(res, 200, { host: cfg.name, services: await servicesFor(cfg.name) })
|
|
1107
|
+
return
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
if (route === 'services' && method === 'POST') {
|
|
1111
|
+
const body = (await readBody(req)) || {}
|
|
1112
|
+
const cfg = pickHost(await loadHosts(), body.host)
|
|
1113
|
+
const all = await loadServices()
|
|
1114
|
+
if (body.action === 'remove') {
|
|
1115
|
+
all.services = all.services.filter(item => item.id !== body.id)
|
|
1116
|
+
await saveServices(all)
|
|
1117
|
+
sendJson(res, 200, { host: cfg.name, services: await servicesFor(cfg.name) })
|
|
1118
|
+
return
|
|
1119
|
+
}
|
|
1120
|
+
const ids = Array.isArray(body.ids) ? body.ids.filter(Boolean) : []
|
|
1121
|
+
if (ids.length === 0) { sendJson(res, 400, { error: 'select at least one monitor' }); return }
|
|
1122
|
+
const service = { id: body.id || `s${Date.now().toString(36)}`, host: cfg.name, name: String(body.name || '业务服务').slice(0, 40), ids }
|
|
1123
|
+
all.services = body.id ? all.services.map(item => item.id === body.id ? { ...item, ...service } : item) : [...all.services, service]
|
|
1124
|
+
await saveServices(all)
|
|
1125
|
+
sendJson(res, 200, { host: cfg.name, services: await servicesFor(cfg.name) })
|
|
1126
|
+
return
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
if (route === 'maintenance' && method === 'GET') {
|
|
1130
|
+
const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
|
|
1131
|
+
const state = await loadState()
|
|
1132
|
+
sendJson(res, 200, { host: cfg.name, until: state.maintenance?.[cfg.name] ?? null })
|
|
1133
|
+
return
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
if (route === 'maintenance' && method === 'POST') {
|
|
1137
|
+
const body = (await readBody(req)) || {}
|
|
1138
|
+
const cfg = pickHost(await loadHosts(), body.host)
|
|
1139
|
+
const state = await loadState()
|
|
1140
|
+
const maintenance = { ...(state.maintenance ?? {}) }
|
|
1141
|
+
const minutes = Number(body.minutes) || 0
|
|
1142
|
+
if (minutes > 0) maintenance[cfg.name] = new Date(Date.now() + minutes * 60_000).toISOString()
|
|
1143
|
+
else delete maintenance[cfg.name]
|
|
1144
|
+
await patchState({ maintenance })
|
|
1145
|
+
sendJson(res, 200, { host: cfg.name, until: maintenance[cfg.name] ?? null })
|
|
1146
|
+
return
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
if (route === 'ack' && method === 'POST') {
|
|
1150
|
+
const body = (await readBody(req)) || {}
|
|
1151
|
+
const cfg = pickHost(await loadHosts(), body.host)
|
|
1152
|
+
const all = await loadMonitors()
|
|
1153
|
+
const monitor = (all[cfg.name] || []).find(item => item.id === body.id)
|
|
1154
|
+
if (!monitor) { sendJson(res, 404, { error: 'monitor not found' }); return }
|
|
1155
|
+
if (body.ack === false) { delete monitor.acked; delete monitor.mutedUntil }
|
|
1156
|
+
else if (body.minutes) monitor.mutedUntil = new Date(Date.now() + Number(body.minutes) * 60_000).toISOString()
|
|
1157
|
+
else monitor.acked = true
|
|
1158
|
+
await saveMonitors(all)
|
|
1159
|
+
sendJson(res, 200, { host: cfg.name, id: monitor.id, acked: monitor.acked === true, mutedUntil: monitor.mutedUntil ?? null })
|
|
1160
|
+
return
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
if (route === 'log-sources' && method === 'GET') {
|
|
1164
|
+
const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
|
|
1165
|
+
sendJson(res, 200, await logSources(cfg))
|
|
1166
|
+
return
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
if (route === 'audit' && method === 'GET') {
|
|
1170
|
+
const all = await loadAudit()
|
|
1171
|
+
const limit = Math.max(1, Math.min(Number(url.searchParams.get('limit')) || 50, 200))
|
|
1172
|
+
sendJson(res, 200, { entries: all.entries.slice(0, limit) })
|
|
1173
|
+
return
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
if (route === 'alerts' && method === 'POST') {
|
|
1177
|
+
const body = (await readBody(req)) || {}
|
|
1178
|
+
const all = await loadAlerts()
|
|
1179
|
+
const target = all.find(entry => entry.at === body.at && entry.message === body.message)
|
|
1180
|
+
if (target) {
|
|
1181
|
+
target.acked = true
|
|
1182
|
+
target.ackedAt = new Date().toISOString()
|
|
1183
|
+
await mkdir(kitDir(), { recursive: true })
|
|
1184
|
+
await writeFile(alertsFile(), JSON.stringify({ entries: all }, null, 2) + '\n', 'utf8')
|
|
1185
|
+
await appendAudit({ host: target.host, action: '告警知悉', detail: target.message })
|
|
1186
|
+
}
|
|
1187
|
+
sendJson(res, 200, { ok: Boolean(target) })
|
|
1188
|
+
return
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
if (route === 'info' && method === 'GET') {
|
|
1192
|
+
let version = '0.0.0'
|
|
1193
|
+
try {
|
|
1194
|
+
version = JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8')).version
|
|
1195
|
+
} catch { /* keep fallback */ }
|
|
1196
|
+
sendJson(res, 200, { name: 'dsh-ops-kit', version, hosts: (await loadHosts()).hosts.length })
|
|
1197
|
+
return
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
if (route === 'log-usage' && method === 'GET') {
|
|
1201
|
+
const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
|
|
1202
|
+
sendJson(res, 200, await logUsage(cfg))
|
|
1203
|
+
return
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
if (route === 'cleanup-preview' && method === 'GET') {
|
|
1207
|
+
const cfg = pickHost(await loadHosts(), url.searchParams.get('host') ?? undefined)
|
|
1208
|
+
sendJson(res, 200, await cleanupPreview(cfg))
|
|
1209
|
+
return
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
if (route === 'log-backup' && method === 'POST') {
|
|
1213
|
+
const body = (await readBody(req)) || {}
|
|
1214
|
+
const cfg = pickHost(await loadHosts(), body.host)
|
|
1215
|
+
sendJson(res, 200, await audited(cfg, '备份日志', `${(body.paths || []).length} 个文件`, () => backupLogs(cfg, body.paths)))
|
|
1216
|
+
return
|
|
1217
|
+
}
|
|
1218
|
+
|
|
996
1219
|
sendJson(res, 404, { error: 'not found' })
|
|
997
1220
|
} catch (error) {
|
|
998
1221
|
sendJson(res, 500, { error: error?.message ?? String(error) })
|
|
@@ -1014,6 +1237,14 @@ const DEFAULT_CONFIG = {
|
|
|
1014
1237
|
aiEnabled: true,
|
|
1015
1238
|
aiProvider: '',
|
|
1016
1239
|
aiModel: '',
|
|
1240
|
+
uiMode: 'pro',
|
|
1241
|
+
logKeepDays: 7,
|
|
1242
|
+
logJournalMb: 200,
|
|
1243
|
+
logAutoEnabled: false,
|
|
1244
|
+
logAutoHour: 3,
|
|
1245
|
+
logAutoMinute: 0,
|
|
1246
|
+
logAutoMinDisk: 80,
|
|
1247
|
+
logGrowAlertMb: 200,
|
|
1017
1248
|
}
|
|
1018
1249
|
const ALERT_LIMIT = 200
|
|
1019
1250
|
|
|
@@ -1423,14 +1654,31 @@ async function loadInventory(host) {
|
|
|
1423
1654
|
|
|
1424
1655
|
|
|
1425
1656
|
/** Safe disk cleanup: rotate-capped logs, old compressed logs, journal vacuum. */
|
|
1426
|
-
|
|
1657
|
+
/** Only allow deleting log-like paths (never /etc, /usr, business data). */
|
|
1658
|
+
function logSafePath(path) {
|
|
1659
|
+
const p = String(path || '').trim()
|
|
1660
|
+
if (!p.startsWith('/') || p.includes('..') || /\s/.test(p)) return false
|
|
1661
|
+
if (!/^\/(var\/log|www\/wwwlogs|opt|home|usr\/local|data)\/.+\/(logs?|wwwlogs)\//.test(p) && !p.startsWith('/var/log/')) return false
|
|
1662
|
+
return /\.(log|out|gz|old|1|txt)$|\/logs?\//.test(p)
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
async function cleanupDisk(cfg, options = {}) {
|
|
1666
|
+
const config = await loadConfig()
|
|
1667
|
+
const keepDays = Math.max(1, Math.min(Number(config.logKeepDays) || 7, 90))
|
|
1668
|
+
const journalMb = Math.max(50, Math.min(Number(config.logJournalMb) || 200, 4096))
|
|
1427
1669
|
const command = [
|
|
1428
1670
|
'before=$(df -P / | awk \'NR==2{gsub("%","",$5);print $5}\')',
|
|
1429
|
-
'
|
|
1430
|
-
|
|
1431
|
-
|
|
1671
|
+
'used_before=$(df -P / | awk \'NR==2{print $3}\')',
|
|
1672
|
+
options.includeJournal === false ? 'true' : `journalctl --vacuum-size=${journalMb}M >/dev/null 2>&1 || true`,
|
|
1673
|
+
// Only rotated files older than a week; never truncate a live or recent log.
|
|
1674
|
+
Array.isArray(options.paths) && options.paths.length
|
|
1675
|
+
? options.paths.filter(item => logSafePath(item)).map(item => `rm -f ${JSON.stringify(item)}`).join('; ') || true
|
|
1676
|
+
: `find /var/log -maxdepth 1 -type f \\( -name "*.gz" -o -name "*.old" -o -name "*.1" -o -name "messages-*" -o -name "secure-*" -o -name "maillog-*" -o -name "cron-*" \\) -mtime +${keepDays} -delete 2>/dev/null || true`,
|
|
1432
1677
|
'after=$(df -P / | awk \'NR==2{gsub("%","",$5);print $5}\')',
|
|
1433
|
-
'
|
|
1678
|
+
'used_after=$(df -P / | awk \'NR==2{print $3}\')',
|
|
1679
|
+
'echo "DISK_BEFORE $before"; echo "DISK_AFTER $after"',
|
|
1680
|
+
'echo "USED_BEFORE $used_before"; echo "USED_AFTER $used_after"',
|
|
1681
|
+
'df -h / | tail -1',
|
|
1434
1682
|
].join('; ')
|
|
1435
1683
|
const result = await ssh(cfg, command, 60_000)
|
|
1436
1684
|
const read = (key) => {
|
|
@@ -1442,6 +1690,9 @@ async function cleanupDisk(cfg) {
|
|
|
1442
1690
|
ok: result.ok,
|
|
1443
1691
|
before: read('DISK_BEFORE'),
|
|
1444
1692
|
after: read('DISK_AFTER'),
|
|
1693
|
+
freedMb: Math.max(0, Math.round(((read('USED_BEFORE') || 0) - (read('USED_AFTER') || 0)) / 1024)),
|
|
1694
|
+
keepDays,
|
|
1695
|
+
journalMb,
|
|
1445
1696
|
detail: clip(result.stdout, 2_000),
|
|
1446
1697
|
error: result.ok ? '' : cleanStderr(result.stderr),
|
|
1447
1698
|
}
|
|
@@ -1676,21 +1927,72 @@ async function killProcess(cfg, pid, signal = 'TERM') {
|
|
|
1676
1927
|
}
|
|
1677
1928
|
|
|
1678
1929
|
/** Last N lines from a journal unit or a log file. */
|
|
1679
|
-
async function tailLog(cfg, source, lines = 200) {
|
|
1680
|
-
const n = Math.min(Math.max(Number(lines) || 200, 20),
|
|
1930
|
+
async function tailLog(cfg, source, lines = 200, filters = {}) {
|
|
1931
|
+
const n = Math.min(Math.max(Number(lines) || 200, 20), 2000)
|
|
1681
1932
|
const raw = String(source || '')
|
|
1682
|
-
|
|
1933
|
+
const since = Math.max(0, Math.min(Number(filters.sinceMinutes) || 0, 7 * 24 * 60))
|
|
1934
|
+
const grep = String(filters.grep || '').trim().slice(0, 120).replace(/[^\p{L}\p{N} ._@:/=#-]/gu, '')
|
|
1935
|
+
const level = ['error', 'warn'].includes(filters.level) ? filters.level : ''
|
|
1936
|
+
const filters_chain = []
|
|
1937
|
+
if (grep) filters_chain.push(`grep -i -- ${JSON.stringify(grep)}`)
|
|
1938
|
+
if (level === 'error') filters_chain.push(`grep -iE 'ERROR|CRITICAL|FATAL|Exception|Traceback'`)
|
|
1939
|
+
if (level === 'warn') filters_chain.push(`grep -iE 'WARN|WARNING'`)
|
|
1940
|
+
const pipeline = filters_chain.length ? ` | ${filters_chain.join(' | ')}` : ''
|
|
1941
|
+
|
|
1942
|
+
if (raw.startsWith('pid:') || raw.startsWith('jar:')) {
|
|
1943
|
+
const result = await tailProcessLog(cfg, raw, n)
|
|
1944
|
+
const matcher = new RegExp(grep ? grep.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : '.', 'i')
|
|
1945
|
+
const levelRe = level === 'error' ? /error|critical|fatal|exception|traceback/i
|
|
1946
|
+
: level === 'warn' ? /warn/i
|
|
1947
|
+
: null
|
|
1948
|
+
const kept = String(result.lines || '').split('\n').filter(line => line && matcher.test(line) && (!levelRe || levelRe.test(line)))
|
|
1949
|
+
return {
|
|
1950
|
+
...result,
|
|
1951
|
+
lines: kept.join('\n').slice(0, 120_000),
|
|
1952
|
+
count: kept.length,
|
|
1953
|
+
filtered: Boolean(grep || level),
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1683
1957
|
let command
|
|
1684
1958
|
if (raw.startsWith('file:')) {
|
|
1685
1959
|
const path = raw.slice(5)
|
|
1686
1960
|
if (!/^\/[A-Za-z0-9._\/-]+$/.test(path)) throw new Error('bad log path')
|
|
1687
|
-
command = `tail -n ${n} ${JSON.stringify(path)} 2>&1`
|
|
1961
|
+
command = `tail -n ${n} ${JSON.stringify(path)} 2>&1${pipeline} | tail -n ${n}`
|
|
1688
1962
|
} else {
|
|
1689
1963
|
const unit = raw.replace(/[^A-Za-z0-9@._:-]/g, '')
|
|
1690
|
-
|
|
1964
|
+
const sinceArg = since > 0 ? ` --since "-${since} min"` : ''
|
|
1965
|
+
command = `journalctl -u ${unit} -n ${n}${sinceArg} --no-pager 2>&1${pipeline} | tail -n ${n}`
|
|
1966
|
+
}
|
|
1967
|
+
const result = await ssh(cfg, command, 30_000)
|
|
1968
|
+
const text = String(result.stdout || '')
|
|
1969
|
+
return {
|
|
1970
|
+
host: cfg.name,
|
|
1971
|
+
source: raw,
|
|
1972
|
+
ok: result.ok,
|
|
1973
|
+
lines: text.slice(0, 120_000),
|
|
1974
|
+
count: text ? text.split('\n').filter(Boolean).length : 0,
|
|
1975
|
+
filtered: Boolean(grep || level),
|
|
1976
|
+
error: result.ok ? '' : cleanStderr(result.stderr),
|
|
1691
1977
|
}
|
|
1692
|
-
|
|
1693
|
-
|
|
1978
|
+
}
|
|
1979
|
+
|
|
1980
|
+
/** Candidate log sources: units, nginx logs, java apps, common files. */
|
|
1981
|
+
async function logSources(cfg) {
|
|
1982
|
+
const groups = []
|
|
1983
|
+
const units = await ssh(cfg, "systemctl list-units --type=service --state=running --no-legend --no-pager 2>/dev/null | awk '{print $1}' | head -80; true", 25_000)
|
|
1984
|
+
const unitList = String(units.stdout || '').split('\n').map(line => line.trim()).filter(Boolean)
|
|
1985
|
+
if (unitList.length) groups.push({ label: '系统服务(journalctl)', items: unitList.map(unit => ({ value: unit, label: unit })) })
|
|
1986
|
+
|
|
1987
|
+
const files = await ssh(cfg, "ls -1 /var/log/nginx/*.log /var/log/messages /var/log/syslog /var/log/*.log 2>/dev/null | sort -u | head -40; true", 25_000)
|
|
1988
|
+
const fileList = String(files.stdout || '').split('\n').map(line => line.trim()).filter(Boolean)
|
|
1989
|
+
if (fileList.length) groups.push({ label: '日志文件', items: fileList.map(path => ({ value: `file:${path}`, label: path })) })
|
|
1990
|
+
|
|
1991
|
+
const jars = await ssh(cfg, "pgrep -af java 2>/dev/null | grep -o '[^ ]*\.jar' | sort -u | head -10; true", 20_000)
|
|
1992
|
+
const jarList = String(jars.stdout || '').split('\n').map(line => line.trim()).filter(Boolean)
|
|
1993
|
+
if (jarList.length) groups.push({ label: 'Java 应用(跨重启跟踪)', items: jarList.map(jar => ({ value: `jar:${jar}`, label: jar })) })
|
|
1994
|
+
|
|
1995
|
+
return { host: cfg.name, groups }
|
|
1694
1996
|
}
|
|
1695
1997
|
|
|
1696
1998
|
/**
|
|
@@ -1810,10 +2112,12 @@ async function listDir(cfg, path) {
|
|
|
1810
2112
|
name,
|
|
1811
2113
|
dir: m[1] === 'd',
|
|
1812
2114
|
link: m[1] === 'l',
|
|
2115
|
+
type: m[1] === 'd' ? '文件夹' : m[1] === 'l' ? '链接' : '文件',
|
|
2116
|
+
perm: `${m[1]}${m[2]}`,
|
|
1813
2117
|
size: Number(m[6]),
|
|
1814
2118
|
owner: m[4],
|
|
1815
2119
|
group: m[5],
|
|
1816
|
-
mtime: m[7],
|
|
2120
|
+
mtime: m[7].replace('T', ' '),
|
|
1817
2121
|
path: dir === '/' ? `/${name}` : `${dir}/${name}`,
|
|
1818
2122
|
}
|
|
1819
2123
|
}).filter(Boolean).sort((a, b) => (b.dir - a.dir) || a.name.localeCompare(b.name))
|
|
@@ -1849,16 +2153,92 @@ async function uploadFile(cfg, path, base64, limitMb = 8) {
|
|
|
1849
2153
|
}
|
|
1850
2154
|
|
|
1851
2155
|
/** mkdir / delete inside a safe path. Delete needs confirm. */
|
|
1852
|
-
|
|
2156
|
+
|
|
2157
|
+
/** Read a text file for the editor (bounded, binary-safe). */
|
|
2158
|
+
async function readTextFile(cfg, path) {
|
|
1853
2159
|
const target = fsSafePath(path)
|
|
2160
|
+
const sizeResult = await ssh(cfg, `stat -c%s ${JSON.stringify(target)} 2>/dev/null || echo 0`, 10_000)
|
|
2161
|
+
const size = Number(String(sizeResult.stdout || '0').trim()) || 0
|
|
2162
|
+
if (size > 512 * 1024) throw new Error(`文件有 ${Math.round(size / 1024)} KB,超过 512 KB,面板不展开编辑`)
|
|
2163
|
+
const result = await ssh(cfg, `base64 -w0 ${JSON.stringify(target)} 2>/dev/null || base64 ${JSON.stringify(target)} 2>/dev/null`, 25_000)
|
|
2164
|
+
if (!result.ok) throw new Error(cleanStderr(result.stderr) || '无法读取文件')
|
|
2165
|
+
const buffer = Buffer.from(String(result.stdout).replace(/\s+/g, ''), 'base64')
|
|
2166
|
+
if (buffer.includes(0)) return { host: cfg.name, path: target, size, binary: true, content: '' }
|
|
2167
|
+
return { host: cfg.name, path: target, size, binary: false, content: buffer.toString('utf8').slice(0, 400_000) }
|
|
2168
|
+
}
|
|
2169
|
+
|
|
2170
|
+
/** Write a text file after backing the old one up. */
|
|
2171
|
+
async function writeTextFile(cfg, path, content) {
|
|
2172
|
+
const target = fsSafePath(path)
|
|
2173
|
+
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
|
|
2174
|
+
const backup = `${target}.bak.${stamp}`
|
|
2175
|
+
const encoded = Buffer.from(String(content ?? ''), 'utf8').toString('base64')
|
|
2176
|
+
const command = [
|
|
2177
|
+
`cp -a ${JSON.stringify(target)} ${JSON.stringify(backup)} 2>/dev/null || true`,
|
|
2178
|
+
`printf %s ${JSON.stringify(encoded)} | base64 -d > ${JSON.stringify(target)}`,
|
|
2179
|
+
`echo BACKUP ${backup}`,
|
|
2180
|
+
`wc -c < ${JSON.stringify(target)}`,
|
|
2181
|
+
].join('\n')
|
|
2182
|
+
const result = await ssh(cfg, command, 60_000)
|
|
2183
|
+
return {
|
|
2184
|
+
host: cfg.name,
|
|
2185
|
+
path: target,
|
|
2186
|
+
ok: result.ok,
|
|
2187
|
+
backup,
|
|
2188
|
+
bytes: Number(String(result.stdout || '').trim().split('\n').pop()) || null,
|
|
2189
|
+
error: result.ok ? '' : cleanStderr(result.stderr),
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
async function fsAction(cfg, action, path, confirm, extra = {}) {
|
|
2194
|
+
const primary = (Array.isArray(extra.paths) && extra.paths.length ? extra.paths[0] : path) || ''
|
|
2195
|
+
const target = primary ? fsSafePath(primary) : ''
|
|
1854
2196
|
if (action === 'mkdir') {
|
|
1855
2197
|
const result = await ssh(cfg, `mkdir -p ${JSON.stringify(target)} && echo OK`, 20_000)
|
|
1856
2198
|
return { host: cfg.name, action, path: target, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
1857
2199
|
}
|
|
2200
|
+
if (action === 'chmod') {
|
|
2201
|
+
const mode = String(extra.mode || '').trim()
|
|
2202
|
+
if (!/^[0-7]{3,4}$/.test(mode) && !/^[ugoa]{1,3}[+-][rwxXst]{1,3}$/.test(mode)) {
|
|
2203
|
+
throw new Error('权限格式应为 644 这样的数字,或 u+x 这样的符号')
|
|
2204
|
+
}
|
|
2205
|
+
const targets = (Array.isArray(extra.paths) && extra.paths.length ? extra.paths : [path]).map(item => fsSafePath(item))
|
|
2206
|
+
const result = await ssh(cfg, targets.map(item => `chmod ${mode} ${JSON.stringify(item)}`).join(' && ') + ' && echo OK', 30_000)
|
|
2207
|
+
return { host: cfg.name, action, paths: targets, mode, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2208
|
+
}
|
|
2209
|
+
if (action === 'compress') {
|
|
2210
|
+
const paths = (Array.isArray(extra.paths) ? extra.paths : [path]).map(item => fsSafePath(item))
|
|
2211
|
+
if (paths.length === 0) throw new Error('先选中要压缩的文件')
|
|
2212
|
+
const format = extra.format === 'zip' ? 'zip' : 'tar.gz'
|
|
2213
|
+
const archive = fsSafePath(extra.archive || `${paths[0]}.tar.gz`)
|
|
2214
|
+
const base = archive.replace(/\/[^/]+$/, '') || '/'
|
|
2215
|
+
const names = paths.map(item => JSON.stringify(item.slice(item.lastIndexOf('/') + 1))).join(' ')
|
|
2216
|
+
const command = format === 'zip'
|
|
2217
|
+
? `cd ${JSON.stringify(base)} && zip -qr ${JSON.stringify(archive.slice(archive.lastIndexOf('/') + 1))} ${names} && echo OK`
|
|
2218
|
+
: `tar -czf ${JSON.stringify(archive)} -C ${JSON.stringify(paths[0].replace(/\/[^/]+$/, '') || '/')} ${names} && echo OK`
|
|
2219
|
+
const result = await ssh(cfg, command, 300_000)
|
|
2220
|
+
return { host: cfg.name, action, archive, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2221
|
+
}
|
|
2222
|
+
if (action === 'extract') {
|
|
2223
|
+
const archive = fsSafePath(path)
|
|
2224
|
+
const target = fsSafePath(extra.target || archive.replace(/\/[^/]+$/, '') || '/')
|
|
2225
|
+
const isZip = /\.zip$/i.test(archive)
|
|
2226
|
+
const command = isZip
|
|
2227
|
+
? `mkdir -p ${JSON.stringify(target)} && unzip -o ${JSON.stringify(archive)} -d ${JSON.stringify(target)} 2>&1 | tail -3`
|
|
2228
|
+
: `mkdir -p ${JSON.stringify(target)} && tar -xzf ${JSON.stringify(archive)} -C ${JSON.stringify(target)} 2>&1 | tail -3 && echo OK`
|
|
2229
|
+
const result = await ssh(cfg, command, 300_000)
|
|
2230
|
+
return { host: cfg.name, action, archive, target, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2231
|
+
}
|
|
2232
|
+
if (action === 'rename') {
|
|
2233
|
+
const to = fsSafePath(path)
|
|
2234
|
+
const result = await ssh(cfg, `mv ${JSON.stringify(target)} ${JSON.stringify(to)} && echo OK`, 20_000)
|
|
2235
|
+
return { host: cfg.name, action, path: to, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2236
|
+
}
|
|
1858
2237
|
if (action === 'delete') {
|
|
1859
2238
|
if (confirm !== true) throw new Error('deleting needs confirm=true')
|
|
1860
|
-
const
|
|
1861
|
-
|
|
2239
|
+
const targets = (Array.isArray(extra.paths) && extra.paths.length ? extra.paths : [path]).map(item => fsSafePath(item))
|
|
2240
|
+
const result = await ssh(cfg, targets.map(item => `rm -rf ${JSON.stringify(item)}`).join(' && ') + ' && echo OK', 120_000)
|
|
2241
|
+
return { host: cfg.name, action, paths: targets, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
1862
2242
|
}
|
|
1863
2243
|
throw new Error(`unknown action ${action}`)
|
|
1864
2244
|
}
|
|
@@ -1960,6 +2340,12 @@ async function openTerminal(cfg, cols = 120, rows = 30) {
|
|
|
1960
2340
|
'-o', 'StrictHostKeyChecking=accept-new',
|
|
1961
2341
|
'-o', 'ServerAliveInterval=15',
|
|
1962
2342
|
'-o', 'ServerAliveCountMax=3',
|
|
2343
|
+
// A terminal must own its connection: sharing the ControlMaster socket with
|
|
2344
|
+
// the panel's short commands means the session dies when that master closes
|
|
2345
|
+
// ("Shared connection to ... closed").
|
|
2346
|
+
'-o', 'ControlMaster=no',
|
|
2347
|
+
'-o', 'ControlPath=none',
|
|
2348
|
+
'-o', 'TCPKeepAlive=yes',
|
|
1963
2349
|
]
|
|
1964
2350
|
if (cfg.port) args.push('-p', String(cfg.port))
|
|
1965
2351
|
if (cfg.key) args.push('-i', cfg.key)
|
|
@@ -2055,6 +2441,547 @@ function terminalClose(id) {
|
|
|
2055
2441
|
return { ok: true }
|
|
2056
2442
|
}
|
|
2057
2443
|
|
|
2444
|
+
|
|
2445
|
+
|
|
2446
|
+
/** Run a remote command with a binary stdin payload (large data never goes in argv). */
|
|
2447
|
+
async function sshStdin(cfg, command, buffer, timeoutMs = 180_000) {
|
|
2448
|
+
const secrets = await loadSecrets()
|
|
2449
|
+
const secret = secrets[cfg.name]
|
|
2450
|
+
if (secret?.password) {
|
|
2451
|
+
const ssh2 = loadSsh2()
|
|
2452
|
+
if (!ssh2) throw new Error('ssh2 is not available in this profile')
|
|
2453
|
+
const conn = new ssh2.Client()
|
|
2454
|
+
const password = Buffer.from(secret.password, 'base64').toString('utf8')
|
|
2455
|
+
return await new Promise((resolve, reject) => {
|
|
2456
|
+
const timer = setTimeout(() => { try { conn.end() } catch {} ; reject(new Error('command timeout')) }, timeoutMs)
|
|
2457
|
+
conn.on('ready', () => {
|
|
2458
|
+
conn.exec(command, (error, stream) => {
|
|
2459
|
+
if (error) { clearTimeout(timer); reject(error); return }
|
|
2460
|
+
let stdout = ''
|
|
2461
|
+
let stderr = ''
|
|
2462
|
+
stream.on('data', chunk => { stdout += chunk.toString('utf8') })
|
|
2463
|
+
stream.stderr.on('data', chunk => { stderr += chunk.toString('utf8') })
|
|
2464
|
+
stream.on('close', (code) => {
|
|
2465
|
+
clearTimeout(timer)
|
|
2466
|
+
try { conn.end() } catch {}
|
|
2467
|
+
resolve({ ok: code === 0, code: code ?? 0, stdout, stderr })
|
|
2468
|
+
})
|
|
2469
|
+
stream.end(buffer)
|
|
2470
|
+
})
|
|
2471
|
+
})
|
|
2472
|
+
conn.on('error', (error) => { clearTimeout(timer); reject(error) })
|
|
2473
|
+
conn.connect({
|
|
2474
|
+
host: cfg.host,
|
|
2475
|
+
port: Number(cfg.port || 22),
|
|
2476
|
+
username: cfg.user || process.env.USER,
|
|
2477
|
+
password,
|
|
2478
|
+
readyTimeout: 15_000,
|
|
2479
|
+
})
|
|
2480
|
+
})
|
|
2481
|
+
}
|
|
2482
|
+
|
|
2483
|
+
const args = [
|
|
2484
|
+
'-o', 'BatchMode=yes',
|
|
2485
|
+
'-o', 'ConnectTimeout=8',
|
|
2486
|
+
'-o', 'StrictHostKeyChecking=accept-new',
|
|
2487
|
+
'-o', 'ServerAliveInterval=15',
|
|
2488
|
+
]
|
|
2489
|
+
if (cfg.port) args.push('-p', String(cfg.port))
|
|
2490
|
+
if (cfg.key) args.push('-i', cfg.key)
|
|
2491
|
+
args.push(`${cfg.user ? cfg.user + '@' : ''}${cfg.host}`, command)
|
|
2492
|
+
|
|
2493
|
+
return await new Promise((resolve, reject) => {
|
|
2494
|
+
const child = spawn('ssh', args, { env: { ...process.env } })
|
|
2495
|
+
let stdout = ''
|
|
2496
|
+
let stderr = ''
|
|
2497
|
+
const timer = setTimeout(() => { try { child.kill() } catch {} ; reject(new Error('command timeout')) }, timeoutMs)
|
|
2498
|
+
child.stdout.on('data', chunk => { stdout += chunk.toString('utf8') })
|
|
2499
|
+
child.stderr.on('data', chunk => { stderr += chunk.toString('utf8') })
|
|
2500
|
+
child.on('error', (error) => { clearTimeout(timer); reject(error) })
|
|
2501
|
+
child.on('close', (code) => { clearTimeout(timer); resolve({ ok: code === 0, code: code ?? 0, stdout, stderr }) })
|
|
2502
|
+
child.stdin.on('error', () => { /* remote may close early */ })
|
|
2503
|
+
child.stdin.end(buffer)
|
|
2504
|
+
})
|
|
2505
|
+
}
|
|
2506
|
+
|
|
2507
|
+
/* ---------- chunked upload / download for progress and resume ---------- */
|
|
2508
|
+
|
|
2509
|
+
const CHUNK_MAX = 8 * 1024 * 1024
|
|
2510
|
+
|
|
2511
|
+
/** Bytes already written to <path>.part, for resumable uploads. */
|
|
2512
|
+
async function uploadStatus(cfg, path) {
|
|
2513
|
+
const target = fsSafePath(path)
|
|
2514
|
+
const result = await ssh(cfg, `stat -c%s ${JSON.stringify(target + '.part')} 2>/dev/null || echo 0`, 10_000)
|
|
2515
|
+
return { host: cfg.name, path: target, bytes: Number(String(result.stdout || '0').trim()) || 0 }
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
/** Append one base64 chunk at the given offset of <path>.part. */
|
|
2519
|
+
async function uploadChunk(cfg, path, offset, base64) {
|
|
2520
|
+
const target = fsSafePath(path)
|
|
2521
|
+
const part = `${target}.part`
|
|
2522
|
+
const expected = Number(offset) || 0
|
|
2523
|
+
const buffer = Buffer.from(String(base64 || ''), 'base64')
|
|
2524
|
+
if (buffer.length === 0) return { host: cfg.name, ok: true, bytes: expected }
|
|
2525
|
+
if (buffer.length > CHUNK_MAX) throw new Error('chunk too large')
|
|
2526
|
+
const command = [
|
|
2527
|
+
`size=$(stat -c%s ${JSON.stringify(part)} 2>/dev/null || echo 0)`,
|
|
2528
|
+
`if [ "$size" -ne ${expected} ]; then echo "OFFSET_MISMATCH $size"; exit 3; fi`,
|
|
2529
|
+
`cat >> ${JSON.stringify(part)}`,
|
|
2530
|
+
`stat -c%s ${JSON.stringify(part)}`,
|
|
2531
|
+
].join('\n')
|
|
2532
|
+
const result = await sshStdin(cfg, command, buffer, 180_000)
|
|
2533
|
+
if (result.code === 3) {
|
|
2534
|
+
return { host: cfg.name, ok: false, offsetMismatch: true, error: cleanStderr(result.stderr).trim() || 'offset mismatch' }
|
|
2535
|
+
}
|
|
2536
|
+
return {
|
|
2537
|
+
host: cfg.name,
|
|
2538
|
+
ok: result.ok,
|
|
2539
|
+
bytes: Number(String(result.stdout || '').trim().split('\n').pop()) || 0,
|
|
2540
|
+
error: result.ok ? '' : cleanStderr(result.stderr),
|
|
2541
|
+
}
|
|
2542
|
+
}
|
|
2543
|
+
|
|
2544
|
+
/** Move <path>.part into place, backing up the previous file first. */
|
|
2545
|
+
async function uploadFinish(cfg, path) {
|
|
2546
|
+
const target = fsSafePath(path)
|
|
2547
|
+
const part = `${target}.part`
|
|
2548
|
+
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
|
|
2549
|
+
const command = [
|
|
2550
|
+
`test -f ${JSON.stringify(part)} || { echo MISSING_PART; exit 4; }`,
|
|
2551
|
+
`cp -a ${JSON.stringify(target)} ${JSON.stringify(`${target}.bak.${stamp}`)} 2>/dev/null || true`,
|
|
2552
|
+
`mv -f ${JSON.stringify(part)} ${JSON.stringify(target)} && echo OK`,
|
|
2553
|
+
`stat -c%s ${JSON.stringify(target)}`,
|
|
2554
|
+
].join('\n')
|
|
2555
|
+
const result = await ssh(cfg, command, 60_000)
|
|
2556
|
+
return {
|
|
2557
|
+
host: cfg.name,
|
|
2558
|
+
ok: result.ok && Number(String(result.stdout || '').trim().split('\n').pop()) >= 0,
|
|
2559
|
+
bytes: Number(String(result.stdout || '').trim().split('\n').pop()) || 0,
|
|
2560
|
+
error: result.ok ? '' : cleanStderr(result.stderr),
|
|
2561
|
+
}
|
|
2562
|
+
}
|
|
2563
|
+
|
|
2564
|
+
/** A byte range of a file as base64, so the browser can show progress. */
|
|
2565
|
+
async function downloadChunk(cfg, path, offset, length) {
|
|
2566
|
+
const target = fsSafePath(path)
|
|
2567
|
+
const start = Math.max(0, Number(offset) || 0)
|
|
2568
|
+
const count = Math.min(CHUNK_MAX, Math.max(1, Number(length) || CHUNK_MAX))
|
|
2569
|
+
const sizeResult = await ssh(cfg, `stat -c%s ${JSON.stringify(target)} 2>/dev/null || echo 0`, 10_000)
|
|
2570
|
+
const size = Number(String(sizeResult.stdout || '0').trim()) || 0
|
|
2571
|
+
const result = await ssh(cfg, `dd if=${JSON.stringify(target)} bs=1 skip=${start} count=${count} 2>/dev/null | base64 -w0`, 180_000)
|
|
2572
|
+
if (!result.ok) throw new Error(cleanStderr(result.stderr) || 'cannot read file')
|
|
2573
|
+
return { host: cfg.name, path: target, size, offset: start, base64: String(result.stdout || '').replace(/\s+/g, '') }
|
|
2574
|
+
}
|
|
2575
|
+
|
|
2576
|
+
|
|
2577
|
+
/* ---------- monitor templates and bulk onboarding ---------- */
|
|
2578
|
+
|
|
2579
|
+
function templatesFile() { return join(kitDir(), 'templates.json') }
|
|
2580
|
+
|
|
2581
|
+
async function loadTemplates() {
|
|
2582
|
+
const data = await loadJsonFile('templates.json', { templates: [] })
|
|
2583
|
+
return Array.isArray(data.templates) ? data : { templates: [] }
|
|
2584
|
+
}
|
|
2585
|
+
|
|
2586
|
+
async function saveTemplates(all) {
|
|
2587
|
+
await saveJsonFile('templates.json', all)
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
/** Normalise one monitor-ish item, dropping anything unusable. */
|
|
2591
|
+
function sanitizeMonitorItem(item) {
|
|
2592
|
+
if (!item) return null
|
|
2593
|
+
const type = ['http', 'port', 'process', 'service', 'script'].includes(item.type) ? item.type : null
|
|
2594
|
+
if (!type) return null
|
|
2595
|
+
const target = String(item.target ?? '').trim().slice(0, 200)
|
|
2596
|
+
const script = item.script ? String(item.script).slice(0, 4000) : ''
|
|
2597
|
+
if (type === 'script' ? !script : !target) return null
|
|
2598
|
+
return {
|
|
2599
|
+
type,
|
|
2600
|
+
target,
|
|
2601
|
+
label: String(item.label ?? '').trim().slice(0, 40),
|
|
2602
|
+
intervalMinutes: Math.max(1, Math.min(Number(item.intervalMinutes) || 5, 1440)),
|
|
2603
|
+
maxAttempts: Math.max(1, Math.min(Number(item.maxAttempts) || 3, 10)),
|
|
2604
|
+
...(script ? { script, language: ['shell', 'python', 'js'].includes(item.language) ? item.language : 'shell' } : {}),
|
|
2605
|
+
}
|
|
2606
|
+
}
|
|
2607
|
+
|
|
2608
|
+
/**
|
|
2609
|
+
* Add several monitors at once, skipping ones that already watch the same
|
|
2610
|
+
* type+target, then run each new monitor once so the panel has a result.
|
|
2611
|
+
*/
|
|
2612
|
+
async function addMonitorsBulk(cfg, items) {
|
|
2613
|
+
const all = await loadMonitors()
|
|
2614
|
+
const list = all[cfg.name] || []
|
|
2615
|
+
const seen = new Set(list.map(item => `${item.type}|${item.target}`))
|
|
2616
|
+
const created = []
|
|
2617
|
+
const skipped = []
|
|
2618
|
+
|
|
2619
|
+
for (const raw of items || []) {
|
|
2620
|
+
const item = sanitizeMonitorItem(raw)
|
|
2621
|
+
if (!item) continue
|
|
2622
|
+
const key = `${item.type}|${item.target}`
|
|
2623
|
+
if (seen.has(key)) { skipped.push(item); continue }
|
|
2624
|
+
seen.add(key)
|
|
2625
|
+
const monitor = { id: `m${Date.now().toString(36)}${created.length}`, createdAt: new Date().toISOString(), ...item }
|
|
2626
|
+
try {
|
|
2627
|
+
const result = await runMonitor(cfg, monitor)
|
|
2628
|
+
monitor.last = result
|
|
2629
|
+
monitor.lastOk = result.ok
|
|
2630
|
+
monitor.attempts = 0
|
|
2631
|
+
} catch (error) {
|
|
2632
|
+
monitor.last = { at: new Date().toISOString(), ok: false, level: 'unknown', ms: 0, detail: String(error?.message || error) }
|
|
2633
|
+
monitor.lastOk = false
|
|
2634
|
+
}
|
|
2635
|
+
created.push(monitor)
|
|
2636
|
+
}
|
|
2637
|
+
|
|
2638
|
+
all[cfg.name] = [...list, ...created]
|
|
2639
|
+
await saveMonitors(all)
|
|
2640
|
+
return { host: cfg.name, created, skipped, monitors: all[cfg.name] }
|
|
2641
|
+
}
|
|
2642
|
+
|
|
2643
|
+
/** Apply one template to one or more hosts. */
|
|
2644
|
+
async function applyTemplate(template, hosts) {
|
|
2645
|
+
const results = []
|
|
2646
|
+
const configs = (await loadHosts()).hosts.filter(cfg => hosts.includes(cfg.name))
|
|
2647
|
+
for (const cfg of configs) {
|
|
2648
|
+
try {
|
|
2649
|
+
results.push(await addMonitorsBulk(cfg, template.items))
|
|
2650
|
+
} catch (error) {
|
|
2651
|
+
results.push({ host: cfg.name, created: [], skipped: [], error: String(error?.message || error) })
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
return { template: template.name, results }
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
|
|
2658
|
+
/* ---------- business services (a few checks presented as one) ---------- */
|
|
2659
|
+
|
|
2660
|
+
async function loadServices() {
|
|
2661
|
+
const data = await loadJsonFile('services.json', { services: [] })
|
|
2662
|
+
return Array.isArray(data.services) ? data : { services: [] }
|
|
2663
|
+
}
|
|
2664
|
+
|
|
2665
|
+
async function saveServices(all) {
|
|
2666
|
+
await saveJsonFile('services.json', all)
|
|
2667
|
+
}
|
|
2668
|
+
|
|
2669
|
+
const LEVEL_RANK = { ok: 0, unknown: 1, warn: 2, crit: 3 }
|
|
2670
|
+
|
|
2671
|
+
function monitorLevelFor(monitor) {
|
|
2672
|
+
if (!monitor?.last) return 'unknown'
|
|
2673
|
+
const interval = Math.max(1, Number(monitor.intervalMinutes) || 5) * 60_000
|
|
2674
|
+
if (Date.now() - new Date(monitor.last.at || 0).getTime() > interval * 3) return 'unknown'
|
|
2675
|
+
if (monitor.lastOk === true) return 'ok'
|
|
2676
|
+
return monitor.last.level || 'crit'
|
|
2677
|
+
}
|
|
2678
|
+
|
|
2679
|
+
/** Services for one host with their worst member state. */
|
|
2680
|
+
async function servicesFor(host) {
|
|
2681
|
+
const all = await loadServices()
|
|
2682
|
+
const monitorsAll = await loadMonitors()
|
|
2683
|
+
const list = (monitorsAll[host] || [])
|
|
2684
|
+
return all.services.filter(service => service.host === host).map(service => {
|
|
2685
|
+
const members = list.filter(monitor => service.ids.includes(monitor.id))
|
|
2686
|
+
const levels = members.map(monitorLevelFor)
|
|
2687
|
+
const worst = levels.reduce((acc, level) => (LEVEL_RANK[level] > LEVEL_RANK[acc] ? level : acc), 'ok')
|
|
2688
|
+
return {
|
|
2689
|
+
...service,
|
|
2690
|
+
level: members.length ? worst : 'unknown',
|
|
2691
|
+
members: members.map(monitor => ({ id: monitor.id, label: monitor.label || monitor.target, level: monitorLevelFor(monitor), detail: monitor.last?.detail || '' })),
|
|
2692
|
+
}
|
|
2693
|
+
})
|
|
2694
|
+
}
|
|
2695
|
+
|
|
2696
|
+
|
|
2697
|
+
/* ---------- audit trail: who did what, when, and whether it worked ---------- */
|
|
2698
|
+
|
|
2699
|
+
function auditFile() { return join(kitDir(), 'audit.json') }
|
|
2700
|
+
|
|
2701
|
+
async function loadAudit() {
|
|
2702
|
+
const data = await loadJsonFile('audit.json', { entries: [] })
|
|
2703
|
+
return Array.isArray(data.entries) ? data : { entries: [] }
|
|
2704
|
+
}
|
|
2705
|
+
|
|
2706
|
+
/** Record one state-changing action (kept to the newest 500). */
|
|
2707
|
+
async function appendAudit(entry) {
|
|
2708
|
+
const all = await loadAudit()
|
|
2709
|
+
all.entries = [{
|
|
2710
|
+
at: new Date().toISOString(),
|
|
2711
|
+
host: entry.host || '',
|
|
2712
|
+
action: entry.action || '',
|
|
2713
|
+
detail: String(entry.detail || '').slice(0, 200),
|
|
2714
|
+
ok: entry.ok !== false,
|
|
2715
|
+
source: entry.source || 'panel',
|
|
2716
|
+
}, ...all.entries].slice(0, 500)
|
|
2717
|
+
await saveJsonFile('audit.json', all)
|
|
2718
|
+
return all.entries[0]
|
|
2719
|
+
}
|
|
2720
|
+
|
|
2721
|
+
/**
|
|
2722
|
+
* Wrap an async action so its result lands in the audit trail without
|
|
2723
|
+
* touching the caller's error handling.
|
|
2724
|
+
*/
|
|
2725
|
+
async function audited(cfg, action, detail, fn, source = 'panel') {
|
|
2726
|
+
try {
|
|
2727
|
+
const result = await fn()
|
|
2728
|
+
await appendAudit({ host: cfg?.name, action, detail, ok: result?.ok !== false, source })
|
|
2729
|
+
return result
|
|
2730
|
+
} catch (error) {
|
|
2731
|
+
await appendAudit({ host: cfg?.name, action, detail, ok: false, source })
|
|
2732
|
+
throw error
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
|
|
2736
|
+
|
|
2737
|
+
/** What logs take up space on one host, largest first. */
|
|
2738
|
+
async function logUsage(cfg) {
|
|
2739
|
+
const command = [
|
|
2740
|
+
'echo "JOURNAL $(journalctl --disk-usage 2>/dev/null | tail -1)"',
|
|
2741
|
+
'echo "TOTAL $(du -sm /var/log 2>/dev/null | awk \'{print $1}\')"',
|
|
2742
|
+
'echo "DISK $(df -P / | awk \'NR==2{gsub("%","",$5);print $5}\')"',
|
|
2743
|
+
'find /var/log -maxdepth 2 -type f -size +200k 2>/dev/null -printf "%s %T@ %p\\n" | sort -rn | head -12',
|
|
2744
|
+
].join('; ')
|
|
2745
|
+
const result = await ssh(cfg, command, 40_000)
|
|
2746
|
+
const read = (key) => {
|
|
2747
|
+
const match = result.stdout.match(new RegExp(`^${key} (.*)$`, 'm'))
|
|
2748
|
+
return match ? match[1].trim() : ''
|
|
2749
|
+
}
|
|
2750
|
+
const files = String(result.stdout || '')
|
|
2751
|
+
.split('\n')
|
|
2752
|
+
.map(line => line.match(/^(\d{4,}) ([\d.]+) (.+)$/))
|
|
2753
|
+
.filter(Boolean)
|
|
2754
|
+
.map(match => ({ bytes: Number(match[1]), at: new Date(Number(match[2]) * 1000).toISOString(), path: match[3], source: '系统日志' }))
|
|
2755
|
+
for (const dir of await discoverLogDirs(cfg).catch(() => [])) {
|
|
2756
|
+
try {
|
|
2757
|
+
const found = await ssh(cfg, `find ${JSON.stringify(dir.path)} -maxdepth 2 -type f \\( -name "*.log*" -o -name "*.out" \\) -size +200k -printf "%s %T@ %p\\n" 2>/dev/null | head -8`, 20_000)
|
|
2758
|
+
for (const line of String(found.stdout || '').split('\n')) {
|
|
2759
|
+
const match = line.match(/^(\d{4,}) ([\d.]+) (.+)$/)
|
|
2760
|
+
if (!match) continue
|
|
2761
|
+
files.push({ bytes: Number(match[1]), at: new Date(Number(match[2]) * 1000).toISOString(), path: match[3], source: `应用日志(${dir.app})` })
|
|
2762
|
+
}
|
|
2763
|
+
} catch { /* skip dir */ }
|
|
2764
|
+
}
|
|
2765
|
+
files.sort((a, b) => b.bytes - a.bytes)
|
|
2766
|
+
const journalText = read('JOURNAL')
|
|
2767
|
+
const journalMatch = journalText.match(/([\d.]+)\s*([KMGT])/i)
|
|
2768
|
+
const journalMb = journalMatch
|
|
2769
|
+
? Math.round(Number(journalMatch[1]) * ({ K: 1 / 1024, M: 1, G: 1024, T: 1024 * 1024 }[journalMatch[2].toUpperCase()] || 1))
|
|
2770
|
+
: null
|
|
2771
|
+
return {
|
|
2772
|
+
host: cfg.name,
|
|
2773
|
+
ok: result.ok,
|
|
2774
|
+
journal: journalText,
|
|
2775
|
+
journalMb,
|
|
2776
|
+
totalMb: Number(read('TOTAL')) || 0,
|
|
2777
|
+
disk: Number(read('DISK')) || null,
|
|
2778
|
+
files,
|
|
2779
|
+
error: result.ok ? '' : cleanStderr(result.stderr),
|
|
2780
|
+
}
|
|
2781
|
+
}
|
|
2782
|
+
|
|
2783
|
+
|
|
2784
|
+
/** Which files the cleanup would delete, who owns them and how old they are. */
|
|
2785
|
+
async function cleanupPreview(cfg) {
|
|
2786
|
+
const config = await loadConfig()
|
|
2787
|
+
const keepDays = Math.max(1, Math.min(Number(config.logKeepDays) || 7, 90))
|
|
2788
|
+
const journalMb = Math.max(50, Math.min(Number(config.logJournalMb) || 200, 4096))
|
|
2789
|
+
const command = [
|
|
2790
|
+
'echo "DISK $(df -P / | awk \'NR==2{gsub("%","",$5);print $5}\')"',
|
|
2791
|
+
'echo "JOURNAL $(journalctl --disk-usage 2>/dev/null | grep -oE \'[0-9.]+[KMG]\' | tail -1)"',
|
|
2792
|
+
`find /var/log -maxdepth 1 -type f \\( -name "*.gz" -o -name "*.old" -o -name "*.1" -o -name "messages-*" -o -name "secure-*" -o -name "maillog-*" -o -name "cron-*" \\) -mtime +${keepDays} -printf "%s %T@ %u %p\\n" 2>/dev/null`,
|
|
2793
|
+
].join('; ')
|
|
2794
|
+
const result = await ssh(cfg, command, 40_000)
|
|
2795
|
+
const read = (key) => {
|
|
2796
|
+
const match = result.stdout.match(new RegExp(`^${key} (.*)$`, 'm'))
|
|
2797
|
+
return match ? match[1].trim() : ''
|
|
2798
|
+
}
|
|
2799
|
+
const journalMatch = read('JOURNAL').match(/([0-9.]+)([KMG])/i)
|
|
2800
|
+
const journalCurrentMb = journalMatch
|
|
2801
|
+
? Math.round(Number(journalMatch[1]) * ({ K: 1 / 1024, M: 1, G: 1024 }[journalMatch[2].toUpperCase()] || 1))
|
|
2802
|
+
: null
|
|
2803
|
+
const SOURCES = [
|
|
2804
|
+
{ test: /opt\/|home\/.*\/logs|\/logs\//i, name: '应用日志' },
|
|
2805
|
+
{ test: /nginx/i, name: '网站服务(nginx)' },
|
|
2806
|
+
{ test: /secure|auth/i, name: '登录 / SSH' },
|
|
2807
|
+
{ test: /mysql|mariadb|mysqld/i, name: '数据库' },
|
|
2808
|
+
{ test: /redis/i, name: '缓存(Redis)' },
|
|
2809
|
+
{ test: /cron/i, name: '定时任务' },
|
|
2810
|
+
{ test: /maillog/i, name: '邮件服务' },
|
|
2811
|
+
{ test: /messages|syslog/i, name: '系统日志' },
|
|
2812
|
+
]
|
|
2813
|
+
for (const dir of await discoverLogDirs(cfg).catch(() => [])) {
|
|
2814
|
+
try {
|
|
2815
|
+
const found = await ssh(cfg, `find ${JSON.stringify(dir.path)} -maxdepth 2 -type f \\( -name "*.log" -o -name "*.out" -o -name "*.gz" -o -name "*.old" -o -name "*.log.*" \\) -mtime +${keepDays} -printf "%s %T@ %u %p\\n" 2>/dev/null | sort -rn | head -40`, 25_000)
|
|
2816
|
+
for (const line of String(found.stdout || '').split('\n')) {
|
|
2817
|
+
const match = line.match(/^(\d+) ([\d.]+) (\S+) (.+)$/)
|
|
2818
|
+
if (!match) continue
|
|
2819
|
+
result.stdout += `\n${line}`
|
|
2820
|
+
}
|
|
2821
|
+
} catch { /* skip */ }
|
|
2822
|
+
}
|
|
2823
|
+
const files = String(result.stdout || '')
|
|
2824
|
+
.split('\n')
|
|
2825
|
+
.map(line => line.match(/^(\d+) ([\d.]+) (\S+) (.+)$/))
|
|
2826
|
+
.filter(Boolean)
|
|
2827
|
+
.map(match => {
|
|
2828
|
+
const path = match[4]
|
|
2829
|
+
const source = SOURCES.find(item => item.test.test(path))
|
|
2830
|
+
return {
|
|
2831
|
+
path,
|
|
2832
|
+
bytes: Number(match[1]),
|
|
2833
|
+
sizeMb: Math.round((Number(match[1]) / 1048576) * 10) / 10,
|
|
2834
|
+
at: new Date(Number(match[2]) * 1000).toISOString(),
|
|
2835
|
+
owner: match[3],
|
|
2836
|
+
source: source ? source.name : '其他',
|
|
2837
|
+
}
|
|
2838
|
+
})
|
|
2839
|
+
.sort((a, b) => b.bytes - a.bytes)
|
|
2840
|
+
const filesMb = Math.round(files.reduce((sum, file) => sum + file.bytes, 0) / 1048576)
|
|
2841
|
+
const journalFreedMb = journalCurrentMb === null ? 0 : Math.max(0, journalCurrentMb - journalMb)
|
|
2842
|
+
return {
|
|
2843
|
+
host: cfg.name,
|
|
2844
|
+
ok: result.ok,
|
|
2845
|
+
disk: Number(read('DISK')) || null,
|
|
2846
|
+
policy: { keepDays, journalMb },
|
|
2847
|
+
journal: { currentMb: journalCurrentMb, capMb: journalMb, freedMb: journalFreedMb },
|
|
2848
|
+
files,
|
|
2849
|
+
filesMb,
|
|
2850
|
+
totalFreedMb: filesMb + journalFreedMb,
|
|
2851
|
+
oldestAt: files.length ? files[files.length - 1].at : null,
|
|
2852
|
+
error: result.ok ? '' : cleanStderr(result.stderr),
|
|
2853
|
+
}
|
|
2854
|
+
}
|
|
2855
|
+
|
|
2856
|
+
|
|
2857
|
+
|
|
2858
|
+
/** Application log directories: java process cwd (and its ./logs), plus usual app dirs. */
|
|
2859
|
+
async function discoverLogDirs(cfg) {
|
|
2860
|
+
const command = [
|
|
2861
|
+
'{',
|
|
2862
|
+
' for p in $(pgrep -f java 2>/dev/null | head -6); do',
|
|
2863
|
+
' cwd=$(readlink /proc/$p/cwd 2>/dev/null)',
|
|
2864
|
+
' [ -n "$cwd" ] && [ "$cwd" != "/" ] && printf "%s\\n%s\\n" "$cwd/logs" "$cwd"',
|
|
2865
|
+
' done',
|
|
2866
|
+
' ls -d /opt/*/logs /home/*/logs /home/*/*/logs /www/wwwlogs /usr/local/*/logs 2>/dev/null',
|
|
2867
|
+
'} | sort -u | while read -r d; do [ -d "$d" ] && echo "$d"; done | head -20',
|
|
2868
|
+
].join('\n')
|
|
2869
|
+
const result = await ssh(cfg, command, 25_000)
|
|
2870
|
+
const seen = new Set()
|
|
2871
|
+
const dirs = []
|
|
2872
|
+
for (const line of String(result.stdout || '').split('\n')) {
|
|
2873
|
+
const dir = line.trim()
|
|
2874
|
+
if (!dir || dir === '/' || seen.has(dir)) continue
|
|
2875
|
+
seen.add(dir)
|
|
2876
|
+
const parts = dir.split('/').filter(Boolean)
|
|
2877
|
+
dirs.push({ path: dir, app: parts[parts.length - 1] === 'logs' ? parts[parts.length - 2] : parts[parts.length - 1] })
|
|
2878
|
+
}
|
|
2879
|
+
return dirs.slice(0, 12)
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
/* ---------- log growth watch and user-scheduled auto cleanup ---------- */
|
|
2883
|
+
|
|
2884
|
+
async function logGrowthPass() {
|
|
2885
|
+
const config = await loadConfig()
|
|
2886
|
+
const hostsList = (await loadHosts()).hosts
|
|
2887
|
+
if (hostsList.length === 0) return { sampled: 0 }
|
|
2888
|
+
const state = await loadState()
|
|
2889
|
+
const history = state.logSizes ?? {}
|
|
2890
|
+
const alertAt = state.logGrowAlertAt ?? {}
|
|
2891
|
+
const now = Date.now()
|
|
2892
|
+
const threshold = Math.max(50, Number(config.logGrowAlertMb) || 200)
|
|
2893
|
+
const alerts = []
|
|
2894
|
+
let sampled = 0
|
|
2895
|
+
|
|
2896
|
+
for (const cfg of hostsList) {
|
|
2897
|
+
const series = history[cfg.name] ?? []
|
|
2898
|
+
const last = series[series.length - 1]
|
|
2899
|
+
if (last && now - last.at < 25 * 60_000) continue
|
|
2900
|
+
let usage
|
|
2901
|
+
try { usage = await logUsage(cfg) } catch { continue }
|
|
2902
|
+
if (!usage.ok) continue
|
|
2903
|
+
sampled += 1
|
|
2904
|
+
const next = [...series, { at: now, totalMb: usage.totalMb, journalMb: usage.journalMb ?? null }].slice(-48)
|
|
2905
|
+
history[cfg.name] = next
|
|
2906
|
+
|
|
2907
|
+
const hourAgo = next.find(item => now - item.at >= 50 * 60_000 && now - item.at <= 95 * 60_000)
|
|
2908
|
+
if (!hourAgo) continue
|
|
2909
|
+
const growth = usage.totalMb - hourAgo.totalMb
|
|
2910
|
+
if (growth < threshold) continue
|
|
2911
|
+
if (now - (alertAt[cfg.name] ?? 0) < 6 * 3600_000) continue
|
|
2912
|
+
alertAt[cfg.name] = now
|
|
2913
|
+
alerts.push({
|
|
2914
|
+
at: new Date().toISOString(),
|
|
2915
|
+
level: 'warning',
|
|
2916
|
+
kind: 'loggrowth',
|
|
2917
|
+
host: cfg.name,
|
|
2918
|
+
message: `日志 1 小时内增长 ${growth} MB(现在 ${usage.totalMb} MB),可能有服务在刷错误,建议看看日志`,
|
|
2919
|
+
})
|
|
2920
|
+
}
|
|
2921
|
+
|
|
2922
|
+
await patchState({ logSizes: history, logGrowAlertAt: alertAt })
|
|
2923
|
+
if (alerts.length) await appendAlerts(alerts)
|
|
2924
|
+
return { sampled, alerts: alerts.length }
|
|
2925
|
+
}
|
|
2926
|
+
|
|
2927
|
+
async function logAutoCleanPass() {
|
|
2928
|
+
const config = await loadConfig()
|
|
2929
|
+
if (config.logAutoEnabled !== true) return { skipped: true }
|
|
2930
|
+
const now = new Date()
|
|
2931
|
+
if (now.getHours() !== Math.max(0, Math.min(Number(config.logAutoHour) ?? 3, 23))) return { skipped: true }
|
|
2932
|
+
if (now.getMinutes() !== Math.max(0, Math.min(Number(config.logAutoMinute) ?? 0, 59))) return { skipped: true }
|
|
2933
|
+
const today = now.toISOString().slice(0, 10)
|
|
2934
|
+
const state = await loadState()
|
|
2935
|
+
if (state.logAutoCleanDay === today) return { skipped: true }
|
|
2936
|
+
|
|
2937
|
+
const hostsList = (await loadHosts()).hosts
|
|
2938
|
+
const minDisk = Math.max(50, Math.min(Number(config.logAutoMinDisk) || 80, 99))
|
|
2939
|
+
const results = []
|
|
2940
|
+
for (const cfg of hostsList) {
|
|
2941
|
+
try {
|
|
2942
|
+
const df = await ssh(cfg, "df -P / | awk 'NR==2{gsub(\"%\",\"\",$5);print $5}'", 15_000)
|
|
2943
|
+
const pct = Number(String(df.stdout || '').trim()) || 0
|
|
2944
|
+
if (pct < minDisk) { results.push({ host: cfg.name, skipped: `磁盘 ${pct}% 低于 ${minDisk}%` }); continue }
|
|
2945
|
+
const result = await cleanupDisk(cfg)
|
|
2946
|
+
await appendAudit({ host: cfg.name, action: '自动清理旧日志', detail: `释放 ${result.freedMb ?? 0} MB(${result.before}% → ${result.after}%)`, ok: result.ok, source: 'auto' })
|
|
2947
|
+
results.push({ host: cfg.name, ok: result.ok, freedMb: result.freedMb, before: result.before, after: result.after })
|
|
2948
|
+
} catch (error) {
|
|
2949
|
+
results.push({ host: cfg.name, ok: false, error: String(error?.message || error) })
|
|
2950
|
+
}
|
|
2951
|
+
}
|
|
2952
|
+
await patchState({ logAutoCleanDay: today })
|
|
2953
|
+
if (results.some(item => item.ok)) {
|
|
2954
|
+
await appendAlerts([{
|
|
2955
|
+
at: new Date().toISOString(), level: 'info', kind: 'autoclean', host: results.filter(item => item.ok).map(item => item.host).join(','),
|
|
2956
|
+
message: `按计划自动清理旧日志:${results.filter(item => item.ok).map(item => `${item.host} 释放 ${item.freedMb ?? 0} MB`).join(';')}`,
|
|
2957
|
+
}])
|
|
2958
|
+
}
|
|
2959
|
+
return { results }
|
|
2960
|
+
}
|
|
2961
|
+
|
|
2962
|
+
|
|
2963
|
+
/** Tar the selected log files on the host so they can be downloaded or kept. */
|
|
2964
|
+
async function backupLogs(cfg, paths) {
|
|
2965
|
+
const list = (Array.isArray(paths) ? paths : []).filter(item => logSafePath(item))
|
|
2966
|
+
if (list.length === 0) throw new Error('select at least one log file')
|
|
2967
|
+
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
|
|
2968
|
+
const dest = `/var/backups/dsh-ops-kit/logs-${stamp}.tar.gz`
|
|
2969
|
+
const command = [
|
|
2970
|
+
`mkdir -p /var/backups/dsh-ops-kit`,
|
|
2971
|
+
`tar -czf ${JSON.stringify(dest)} ${list.map(item => JSON.stringify(item)).join(' ')} 2>/dev/null && echo OK`,
|
|
2972
|
+
`stat -c%s ${JSON.stringify(dest)}`,
|
|
2973
|
+
].join('\\n')
|
|
2974
|
+
const result = await ssh(cfg, command, 300_000)
|
|
2975
|
+
const size = Number(String(result.stdout || '').trim().split('\\n').pop()) || 0
|
|
2976
|
+
return { host: cfg.name, ok: result.ok && size > 0, path: dest, sizeMb: Math.round((size / 1048576) * 10) / 10, files: list.length, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2977
|
+
}
|
|
2978
|
+
|
|
2979
|
+
export const __logs = { logUsage, cleanupDisk, cleanupPreview, backupLogs, discoverLogDirs }
|
|
2980
|
+
|
|
2981
|
+
export const __monitors = { runMonitor, runMonitorPass }
|
|
2982
|
+
|
|
2983
|
+
export const __files = { readTextFile, writeTextFile, fsAction, listDir, uploadStatus, uploadChunk, uploadFinish, downloadChunk }
|
|
2984
|
+
|
|
2058
2985
|
export const __terminal = { openTerminal, terminalPoll, terminalInput, terminalResize, terminalClose }
|
|
2059
2986
|
|
|
2060
2987
|
|
|
@@ -2253,7 +3180,11 @@ async function saveMonitors(all) {
|
|
|
2253
3180
|
await writeFile(monitorsFile(), JSON.stringify(all, null, 2) + '\n', 'utf8')
|
|
2254
3181
|
}
|
|
2255
3182
|
|
|
2256
|
-
/**
|
|
3183
|
+
/**
|
|
3184
|
+
* Run one check. Levels follow the Nagios plugin contract:
|
|
3185
|
+
* 0 ok, 1 warning, 2 critical, 3 unknown. Monitors may also emit
|
|
3186
|
+
* `message | key=value;warn;crit;min;max` performance data.
|
|
3187
|
+
*/
|
|
2257
3188
|
async function runMonitor(cfg, monitor) {
|
|
2258
3189
|
const started = Date.now()
|
|
2259
3190
|
const type = String(monitor.type || '')
|
|
@@ -2281,26 +3212,61 @@ async function runMonitor(cfg, monitor) {
|
|
|
2281
3212
|
const result = await ssh(cfg, command, 15_000)
|
|
2282
3213
|
const ms = Date.now() - started
|
|
2283
3214
|
const out = String(result.stdout || '').trim()
|
|
2284
|
-
let
|
|
3215
|
+
let level = 'ok'
|
|
2285
3216
|
let detail = out
|
|
3217
|
+
let perf = null
|
|
3218
|
+
|
|
2286
3219
|
if (type === 'http') {
|
|
2287
3220
|
const [code, time] = out.split(/\s+/)
|
|
2288
|
-
|
|
3221
|
+
const status = Number(code)
|
|
3222
|
+
level = status >= 200 && status < 400 ? 'ok' : status >= 400 && status < 500 ? 'warn' : 'crit'
|
|
2289
3223
|
detail = `HTTP ${code}${time ? ` · ${Math.round(Number(time) * 1000)}ms` : ''}`
|
|
3224
|
+
if (time) perf = { time: { value: Math.round(Number(time) * 1000), unit: 'ms' } }
|
|
2290
3225
|
} else if (type === 'port') {
|
|
2291
|
-
|
|
2292
|
-
detail = ok ? '端口开放' : '端口不通'
|
|
3226
|
+
level = /OPEN/.test(out) ? 'ok' : 'crit'
|
|
3227
|
+
detail = level === 'ok' ? '端口开放' : '端口不通'
|
|
2293
3228
|
} else if (type === 'process') {
|
|
2294
|
-
|
|
2295
|
-
detail = ok ? '进程存在' : '进程不存在'
|
|
3229
|
+
level = /RUNNING/.test(out) ? 'ok' : 'crit'
|
|
3230
|
+
detail = level === 'ok' ? '进程存在' : '进程不存在'
|
|
2296
3231
|
} else if (type === 'service') {
|
|
2297
|
-
|
|
2298
|
-
|
|
3232
|
+
if (out === 'active') { level = 'ok'; detail = 'active' }
|
|
3233
|
+
else if (out === 'failed') { level = 'crit'; detail = 'failed' }
|
|
3234
|
+
else if (out === 'inactive' || out === 'deactivating') { level = 'warn'; detail = out }
|
|
3235
|
+
else { level = 'unknown'; detail = out || 'unknown' }
|
|
2299
3236
|
} else if (type === 'script') {
|
|
2300
|
-
|
|
2301
|
-
|
|
3237
|
+
const code = result.code
|
|
3238
|
+
level = code === 0 ? 'ok' : code === 1 ? 'warn' : code === 2 ? 'crit' : 'unknown'
|
|
3239
|
+
const lines = out.split('\n').filter(Boolean)
|
|
3240
|
+
const first = lines[0] || ''
|
|
3241
|
+
const pipe = first.indexOf('|')
|
|
3242
|
+
const message = (pipe >= 0 ? first.slice(0, pipe) : first).trim()
|
|
3243
|
+
const perfText = pipe >= 0 ? first.slice(pipe + 1) : ''
|
|
3244
|
+
if (perfText) {
|
|
3245
|
+
perf = {}
|
|
3246
|
+
for (const chunk of perfText.split(/\s+/)) {
|
|
3247
|
+
const match = chunk.match(/^([^=]+)=([0-9.]+)[^;]*(?:;([0-9.]+))?(?:;([0-9.]+))?/)
|
|
3248
|
+
if (match) perf[match[1]] = { value: Number(match[2]), warn: Number(match[3]) || null, crit: Number(match[4]) || null }
|
|
3249
|
+
}
|
|
3250
|
+
if (Object.keys(perf).length === 0) perf = null
|
|
3251
|
+
}
|
|
3252
|
+
detail = level === 'ok'
|
|
3253
|
+
? (message || '脚本返回 0')
|
|
3254
|
+
: `${message || '失败'}(退出码 ${code})`
|
|
3255
|
+
}
|
|
3256
|
+
|
|
3257
|
+
if (perf && typeof perf.time === 'undefined' && ms > 0) {
|
|
3258
|
+
perf.duration = { value: ms, unit: 'ms' }
|
|
3259
|
+
}
|
|
3260
|
+
|
|
3261
|
+
return {
|
|
3262
|
+
at: new Date().toISOString(),
|
|
3263
|
+
ok: level === 'ok',
|
|
3264
|
+
level,
|
|
3265
|
+
ms,
|
|
3266
|
+
detail: String(detail).slice(0, 200),
|
|
3267
|
+
code: result.code,
|
|
3268
|
+
perf,
|
|
2302
3269
|
}
|
|
2303
|
-
return { at: new Date().toISOString(), ok, ms, detail, code: result.code }
|
|
2304
3270
|
}
|
|
2305
3271
|
|
|
2306
3272
|
/** Run every monitor of every host that is due, and record alerts on change. */
|
|
@@ -2311,61 +3277,109 @@ async function runMonitorPass(force = false) {
|
|
|
2311
3277
|
if (!force && !(await acquireLock('.monitor-pass.lock', 4 * 60_000))) return { ran: 0, changed: [] }
|
|
2312
3278
|
monitorPassRunning = true
|
|
2313
3279
|
try {
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
3280
|
+
const all = await loadMonitors()
|
|
3281
|
+
const hostsList = (await loadHosts()).hosts
|
|
3282
|
+
const state = await loadState()
|
|
3283
|
+
const lastRun = state.monitorLastRun ?? {}
|
|
3284
|
+
const changed = []
|
|
3285
|
+
let ran = 0
|
|
3286
|
+
|
|
3287
|
+
for (const cfg of hostsList) {
|
|
3288
|
+
const list = all[cfg.name] || []
|
|
3289
|
+
if (list.length === 0) continue
|
|
3290
|
+
|
|
3291
|
+
// A host that cannot be reached suppresses its own checks: one alert
|
|
3292
|
+
// instead of one per monitor (Zabbix trigger dependencies, simplified).
|
|
3293
|
+
const probe = await ssh(cfg, 'echo ok', 10_000)
|
|
3294
|
+
if (!probe.ok) {
|
|
3295
|
+
const suppressedAt = state.monitorSuppressed?.[cfg.name] ?? 0
|
|
3296
|
+
if (Date.now() - suppressedAt > 30 * 60_000) {
|
|
3297
|
+
changed.push({
|
|
3298
|
+
at: new Date().toISOString(), level: 'critical', kind: 'host', host: cfg.name,
|
|
3299
|
+
message: `主机不可达(${cleanStderr(probe.stderr).slice(0, 80) || 'SSH 失败'}),该主机的 ${list.length} 项检查已抑制`,
|
|
3300
|
+
})
|
|
3301
|
+
await patchState({ monitorSuppressed: { ...(state.monitorSuppressed ?? {}), [cfg.name]: Date.now() } })
|
|
3302
|
+
}
|
|
3303
|
+
for (const monitor of list) {
|
|
3304
|
+
monitor.last = { at: new Date().toISOString(), ok: false, level: 'unknown', ms: 0, detail: '主机不可达,已抑制' }
|
|
3305
|
+
monitor.lastOk = false
|
|
3306
|
+
monitor.suppressed = true
|
|
3307
|
+
}
|
|
3308
|
+
await saveMonitors(all)
|
|
3309
|
+
continue
|
|
3310
|
+
} else if (state.monitorSuppressed?.[cfg.name]) {
|
|
2340
3311
|
changed.push({
|
|
2341
|
-
at:
|
|
2342
|
-
|
|
2343
|
-
kind: 'monitor',
|
|
2344
|
-
host: cfg.name,
|
|
2345
|
-
message: `${monitor.type} ${monitor.target} ${result.ok ? '恢复正常' : '检查失败'}(${result.detail})`,
|
|
3312
|
+
at: new Date().toISOString(), level: 'info', kind: 'recovered', host: cfg.name,
|
|
3313
|
+
message: '主机恢复可达,监控项恢复检查',
|
|
2346
3314
|
})
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
3315
|
+
const nextSuppressed = { ...(state.monitorSuppressed ?? {}) }
|
|
3316
|
+
delete nextSuppressed[cfg.name]
|
|
3317
|
+
await patchState({ monitorSuppressed: nextSuppressed })
|
|
3318
|
+
}
|
|
3319
|
+
|
|
3320
|
+
for (const monitor of list) {
|
|
3321
|
+
const interval = Math.max(1, Number(monitor.intervalMinutes) || 5) * 60_000
|
|
3322
|
+
const previous = lastRun[monitor.id] ?? 0
|
|
3323
|
+
if (!force && Date.now() - previous < interval) continue
|
|
3324
|
+
let result
|
|
3325
|
+
try {
|
|
3326
|
+
result = await runMonitor(cfg, monitor)
|
|
3327
|
+
} catch (error) {
|
|
3328
|
+
result = { at: new Date().toISOString(), ok: false, level: 'unknown', ms: 0, detail: String(error?.message || error), code: 1 }
|
|
3329
|
+
}
|
|
3330
|
+
lastRun[monitor.id] = Date.now()
|
|
3331
|
+
ran += 1
|
|
3332
|
+
monitor.suppressed = false
|
|
3333
|
+
monitor.last = result
|
|
3334
|
+
monitor.lastOk = result.ok
|
|
3335
|
+
|
|
3336
|
+
// Nagios-style retry: alert only after N consecutive non-ok checks.
|
|
3337
|
+
const maxAttempts = Math.max(1, Math.min(Number(monitor.maxAttempts) || 3, 10))
|
|
3338
|
+
if (result.ok) {
|
|
3339
|
+
monitor.attempts = 0
|
|
3340
|
+
if (monitor.alerted) {
|
|
3341
|
+
monitor.alerted = false
|
|
3342
|
+
changed.push({
|
|
3343
|
+
at: result.at, level: 'info', kind: 'recovered', host: cfg.name,
|
|
3344
|
+
message: `${monitor.label || monitor.type + ' ' + monitor.target} 恢复正常(${result.detail})`,
|
|
3345
|
+
})
|
|
3346
|
+
}
|
|
3347
|
+
continue
|
|
3348
|
+
}
|
|
3349
|
+
|
|
3350
|
+
monitor.attempts = (monitor.attempts ?? 0) + 1
|
|
3351
|
+
if (monitor.attempts < maxAttempts) continue
|
|
3352
|
+
if (monitor.alerted) {
|
|
3353
|
+
const lastAlert = state.monitorAlertAt?.[monitor.id] ?? 0
|
|
3354
|
+
if (Date.now() - lastAlert < 30 * 60_000) continue
|
|
3355
|
+
const alertState = { ...(state.monitorAlertAt ?? {}), [monitor.id]: Date.now() }
|
|
3356
|
+
await patchState({ monitorAlertAt: alertState })
|
|
3357
|
+
changed.push({
|
|
3358
|
+
at: result.at, level: result.level === 'warn' ? 'warning' : 'critical', kind: 'monitor', host: cfg.name,
|
|
3359
|
+
message: `${monitor.label || monitor.type + ' ' + monitor.target} 仍然异常(${result.detail})`,
|
|
3360
|
+
})
|
|
3361
|
+
continue
|
|
3362
|
+
}
|
|
3363
|
+
monitor.alerted = true
|
|
3364
|
+
const alertState = { ...(state.monitorAlertAt ?? {}), [monitor.id]: Date.now() }
|
|
3365
|
+
await patchState({ monitorAlertAt: alertState })
|
|
2352
3366
|
changed.push({
|
|
2353
3367
|
at: result.at,
|
|
2354
|
-
level: 'warning',
|
|
3368
|
+
level: result.level === 'warn' ? 'warning' : result.level === 'unknown' ? 'warning' : 'critical',
|
|
2355
3369
|
kind: 'monitor',
|
|
2356
3370
|
host: cfg.name,
|
|
2357
|
-
message: `${monitor.type
|
|
3371
|
+
message: `${monitor.label || monitor.type + ' ' + monitor.target} 连续 ${maxAttempts} 次异常(${result.detail})`,
|
|
2358
3372
|
})
|
|
2359
3373
|
}
|
|
3374
|
+
await saveMonitors(all)
|
|
2360
3375
|
}
|
|
2361
|
-
}
|
|
2362
3376
|
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
3377
|
+
if (ran > 0 || changed.length) {
|
|
3378
|
+
await saveMonitors(all)
|
|
3379
|
+
await patchState({ monitorLastRun: lastRun })
|
|
3380
|
+
if (changed.length) await appendAlerts(changed)
|
|
3381
|
+
}
|
|
3382
|
+
return { ran, changed }
|
|
2369
3383
|
} finally {
|
|
2370
3384
|
monitorPassRunning = false
|
|
2371
3385
|
if (!force) await releaseLock('.monitor-pass.lock')
|
|
@@ -2776,7 +3790,21 @@ async function dispatchAlerts(alerts) {
|
|
|
2776
3790
|
const state = await loadState()
|
|
2777
3791
|
const delivered = state.delivered ?? {}
|
|
2778
3792
|
const now = Date.now()
|
|
3793
|
+
const maintenance = state.maintenance ?? {}
|
|
3794
|
+
const monitorsAll = await loadMonitors()
|
|
3795
|
+
const mutedKeys = new Set()
|
|
3796
|
+
for (const [hostName, list] of Object.entries(monitorsAll)) {
|
|
3797
|
+
for (const monitor of list) {
|
|
3798
|
+
if (!monitor) continue
|
|
3799
|
+
const muted = monitor.mutedUntil && new Date(monitor.mutedUntil).getTime() > now
|
|
3800
|
+
const acked = monitor.acked === true && monitor.lastOk === false
|
|
3801
|
+
if (muted || acked) mutedKeys.add(`${hostName}:${monitor.label || monitor.type + ' ' + monitor.target}`)
|
|
3802
|
+
}
|
|
3803
|
+
}
|
|
2779
3804
|
const fresh = list.filter(alert => {
|
|
3805
|
+
const hostMuted = maintenance[alert.host] && new Date(maintenance[alert.host]).getTime() > now
|
|
3806
|
+
if (hostMuted) return false
|
|
3807
|
+
if (alert.kind === 'monitor' && [...mutedKeys].some(key => key.split(':')[0] === alert.host && alert.message.startsWith(key.slice(alert.host.length + 1)))) return false
|
|
2780
3808
|
const key = `${alert.host}:${alert.level}:${alert.message}`.slice(0, 200)
|
|
2781
3809
|
if (delivered[key] && now - delivered[key] < 10 * 60_000) return false
|
|
2782
3810
|
delivered[key] = now
|
|
@@ -3064,6 +4092,14 @@ export function apply(ctx) {
|
|
|
3064
4092
|
aiEnabled: { type: 'boolean', description: 'turn the AI assistant on or off' },
|
|
3065
4093
|
aiProvider: { type: 'string', description: 'provider id for the ops AI; empty means the DSH default model' },
|
|
3066
4094
|
aiModel: { type: 'string', description: 'model id for the ops AI; empty means the DSH default model' },
|
|
4095
|
+
uiMode: { type: 'string', enum: ['simple', 'pro'], description: 'panel mode: simple hides technical pages (for non-technical users)' },
|
|
4096
|
+
logKeepDays: { type: 'number', description: 'keep rotated logs for N days before cleanup deletes them (default 7)' },
|
|
4097
|
+
logJournalMb: { type: 'number', description: 'systemd journal size cap in MB (default 200)' },
|
|
4098
|
+
logAutoEnabled: { type: 'boolean', description: 'run the log cleanup automatically once a day' },
|
|
4099
|
+
logAutoHour: { type: 'number', description: 'auto cleanup hour 0-23 (default 3)' },
|
|
4100
|
+
logAutoMinute: { type: 'number', description: 'auto cleanup minute 0-59 (default 0)' },
|
|
4101
|
+
logAutoMinDisk: { type: 'number', description: 'only auto clean when the disk is at least this percent full (default 80)' },
|
|
4102
|
+
logGrowAlertMb: { type: 'number', description: 'alert when logs grow more than this many MB in an hour (default 200)' },
|
|
3067
4103
|
},
|
|
3068
4104
|
async execute(args = {}) {
|
|
3069
4105
|
const patch = {}
|
|
@@ -3074,6 +4110,14 @@ export function apply(ctx) {
|
|
|
3074
4110
|
if (typeof args.timeoutSec === 'number') patch.timeoutSec = Math.max(5, Math.min(Math.round(args.timeoutSec), 300))
|
|
3075
4111
|
if (typeof args.scanSec === 'number') patch.scanSec = Math.max(10, Math.min(Math.round(args.scanSec), 600))
|
|
3076
4112
|
if (typeof args.actionSec === 'number') patch.actionSec = Math.max(10, Math.min(Math.round(args.actionSec), 600))
|
|
4113
|
+
if (args.uiMode === 'simple' || args.uiMode === 'pro') patch.uiMode = args.uiMode
|
|
4114
|
+
if (typeof args.logKeepDays === 'number') patch.logKeepDays = Math.max(1, Math.min(Math.round(args.logKeepDays), 90))
|
|
4115
|
+
if (typeof args.logJournalMb === 'number') patch.logJournalMb = Math.max(50, Math.min(Math.round(args.logJournalMb), 4096))
|
|
4116
|
+
if (typeof args.logAutoEnabled === 'boolean') patch.logAutoEnabled = args.logAutoEnabled
|
|
4117
|
+
if (typeof args.logAutoHour === 'number') patch.logAutoHour = Math.max(0, Math.min(Math.round(args.logAutoHour), 23))
|
|
4118
|
+
if (typeof args.logAutoMinute === 'number') patch.logAutoMinute = Math.max(0, Math.min(Math.round(args.logAutoMinute), 59))
|
|
4119
|
+
if (typeof args.logAutoMinDisk === 'number') patch.logAutoMinDisk = Math.max(50, Math.min(Math.round(args.logAutoMinDisk), 99))
|
|
4120
|
+
if (typeof args.logGrowAlertMb === 'number') patch.logGrowAlertMb = Math.max(50, Math.min(Math.round(args.logGrowAlertMb), 10240))
|
|
3077
4121
|
if (typeof args.aiEnabled === 'boolean') patch.aiEnabled = args.aiEnabled
|
|
3078
4122
|
if (typeof args.aiProvider === 'string') patch.aiProvider = args.aiProvider.slice(0, 80)
|
|
3079
4123
|
if (typeof args.aiModel === 'string') patch.aiModel = args.aiModel.slice(0, 120)
|
|
@@ -3223,6 +4267,16 @@ export function apply(ctx) {
|
|
|
3223
4267
|
},
|
|
3224
4268
|
}),
|
|
3225
4269
|
|
|
4270
|
+
asTool({
|
|
4271
|
+
name: 'ops_audit',
|
|
4272
|
+
description: 'Recent state-changing actions on the servers (restart, backup, restore, deploy, file delete/chmod, monitor changes), newest first.',
|
|
4273
|
+
parameters: { limit: { type: 'number', description: 'how many entries; defaults to 50' } },
|
|
4274
|
+
async execute(args = {}) {
|
|
4275
|
+
const all = await loadAudit()
|
|
4276
|
+
return { entries: all.entries.slice(0, Math.max(1, Math.min(Number(args.limit) || 50, 200))) }
|
|
4277
|
+
},
|
|
4278
|
+
}),
|
|
4279
|
+
|
|
3226
4280
|
asTool({
|
|
3227
4281
|
name: 'ops_channels',
|
|
3228
4282
|
description: 'List, add, remove or test alert delivery channels (feishu / dingtalk / wecom / generic webhook).',
|
|
@@ -3300,11 +4354,115 @@ export function apply(ctx) {
|
|
|
3300
4354
|
},
|
|
3301
4355
|
}),
|
|
3302
4356
|
|
|
4357
|
+
asTool({
|
|
4358
|
+
name: 'ops_maintenance',
|
|
4359
|
+
description: 'Put one host into maintenance for N minutes (0 ends it). Alerts are still recorded but not delivered while maintenance is active.',
|
|
4360
|
+
parameters: {
|
|
4361
|
+
host: { type: 'string', description: 'host name from ops_hosts' },
|
|
4362
|
+
minutes: { type: 'number', description: 'duration in minutes; 0 ends maintenance' },
|
|
4363
|
+
},
|
|
4364
|
+
async execute(args = {}) {
|
|
4365
|
+
const cfg = pickHost(await loadHosts(), args.host)
|
|
4366
|
+
const state = await loadState()
|
|
4367
|
+
const maintenance = { ...(state.maintenance ?? {}) }
|
|
4368
|
+
const minutes = Number(args.minutes) || 0
|
|
4369
|
+
if (minutes > 0) maintenance[cfg.name] = new Date(Date.now() + minutes * 60_000).toISOString()
|
|
4370
|
+
else delete maintenance[cfg.name]
|
|
4371
|
+
await patchState({ maintenance })
|
|
4372
|
+
return { host: cfg.name, until: maintenance[cfg.name] ?? null }
|
|
4373
|
+
},
|
|
4374
|
+
}),
|
|
4375
|
+
|
|
4376
|
+
asTool({
|
|
4377
|
+
name: 'ops_ack',
|
|
4378
|
+
description: 'Acknowledge a failing monitor (stop repeat notifications until it recovers), or mute it for N minutes, or clear both.',
|
|
4379
|
+
parameters: {
|
|
4380
|
+
host: { type: 'string', description: 'host name from ops_hosts' },
|
|
4381
|
+
id: { type: 'string', description: 'monitor id' },
|
|
4382
|
+
minutes: { type: 'number', description: 'mute for N minutes instead of acknowledging' },
|
|
4383
|
+
clear: { type: 'boolean', description: 'clear the acknowledgement and mute' },
|
|
4384
|
+
},
|
|
4385
|
+
async execute(args = {}) {
|
|
4386
|
+
const cfg = pickHost(await loadHosts(), args.host)
|
|
4387
|
+
const all = await loadMonitors()
|
|
4388
|
+
const monitor = (all[cfg.name] || []).find(item => item.id === args.id)
|
|
4389
|
+
if (!monitor) throw new Error('monitor not found')
|
|
4390
|
+
if (args.clear) { delete monitor.acked; delete monitor.mutedUntil }
|
|
4391
|
+
else if (args.minutes) monitor.mutedUntil = new Date(Date.now() + Number(args.minutes) * 60_000).toISOString()
|
|
4392
|
+
else monitor.acked = true
|
|
4393
|
+
await saveMonitors(all)
|
|
4394
|
+
return { host: cfg.name, id: monitor.id, acked: monitor.acked === true, mutedUntil: monitor.mutedUntil ?? null }
|
|
4395
|
+
},
|
|
4396
|
+
}),
|
|
4397
|
+
|
|
4398
|
+
asTool({
|
|
4399
|
+
name: 'ops_services',
|
|
4400
|
+
description: 'Business services for a host: a few monitors presented as one state. List, create from monitor ids, or remove.',
|
|
4401
|
+
parameters: {
|
|
4402
|
+
host: { type: 'string', description: 'host name from ops_hosts' },
|
|
4403
|
+
action: { type: 'string', enum: ['list', 'create', 'remove'], description: 'defaults to list' },
|
|
4404
|
+
id: { type: 'string', description: 'service id for remove' },
|
|
4405
|
+
name: { type: 'string', description: 'service name, e.g. 网站' },
|
|
4406
|
+
ids: { type: 'array', items: { type: 'string' }, description: 'monitor ids that make up the service' },
|
|
4407
|
+
},
|
|
4408
|
+
async execute(args = {}) {
|
|
4409
|
+
const cfg = pickHost(await loadHosts(), args.host)
|
|
4410
|
+
const all = await loadServices()
|
|
4411
|
+
if ((args.action ?? 'list') === 'list') return { host: cfg.name, services: await servicesFor(cfg.name) }
|
|
4412
|
+
if (args.action === 'remove') {
|
|
4413
|
+
all.services = all.services.filter(item => item.id !== args.id)
|
|
4414
|
+
await saveServices(all)
|
|
4415
|
+
return { host: cfg.name, services: await servicesFor(cfg.name) }
|
|
4416
|
+
}
|
|
4417
|
+
const ids = Array.isArray(args.ids) ? args.ids.filter(Boolean) : []
|
|
4418
|
+
if (ids.length === 0) throw new Error('ids is required')
|
|
4419
|
+
const service = { id: `s${Date.now().toString(36)}`, host: cfg.name, name: String(args.name || '业务服务').slice(0, 40), ids }
|
|
4420
|
+
all.services = [...all.services, service]
|
|
4421
|
+
await saveServices(all)
|
|
4422
|
+
return { host: cfg.name, services: await servicesFor(cfg.name) }
|
|
4423
|
+
},
|
|
4424
|
+
}),
|
|
4425
|
+
|
|
4426
|
+
asTool({
|
|
4427
|
+
name: 'ops_templates',
|
|
4428
|
+
description: 'Save, list, remove or apply monitor templates. A template is a named set of monitors that can be applied to one or many hosts at once.',
|
|
4429
|
+
parameters: {
|
|
4430
|
+
action: { type: 'string', enum: ['list', 'save', 'remove', 'apply'], description: 'defaults to list' },
|
|
4431
|
+
id: { type: 'string', description: 'template id for remove/apply' },
|
|
4432
|
+
name: { type: 'string', description: 'template name for save' },
|
|
4433
|
+
items: { type: 'array', items: { type: 'object' }, description: 'monitors for save: {type,target,label,intervalMinutes,maxAttempts,script,language}' },
|
|
4434
|
+
hosts: { type: 'array', items: { type: 'string' }, description: 'hosts for apply; omit for all hosts' },
|
|
4435
|
+
},
|
|
4436
|
+
async execute(args = {}) {
|
|
4437
|
+
const all = await loadTemplates()
|
|
4438
|
+
const action = args.action ?? 'list'
|
|
4439
|
+
if (action === 'list') return { templates: all.templates }
|
|
4440
|
+
if (action === 'remove') {
|
|
4441
|
+
all.templates = all.templates.filter(item => item.id !== args.id)
|
|
4442
|
+
await saveTemplates(all)
|
|
4443
|
+
return { templates: all.templates }
|
|
4444
|
+
}
|
|
4445
|
+
if (action === 'apply') {
|
|
4446
|
+
const template = all.templates.find(item => item.id === args.id)
|
|
4447
|
+
if (!template) throw new Error('template not found')
|
|
4448
|
+
const hostsList = (await loadHosts()).hosts
|
|
4449
|
+
const hosts = Array.isArray(args.hosts) && args.hosts.length ? args.hosts : hostsList.map(cfg => cfg.name)
|
|
4450
|
+
return applyTemplate(template, hosts)
|
|
4451
|
+
}
|
|
4452
|
+
const items = (args.items || []).map(sanitizeMonitorItem).filter(Boolean)
|
|
4453
|
+
if (items.length === 0) throw new Error('template has no monitors')
|
|
4454
|
+
const template = { id: args.id || `t${Date.now().toString(36)}`, name: String(args.name || '模板').slice(0, 40), items, createdAt: new Date().toISOString() }
|
|
4455
|
+
all.templates = args.id ? all.templates.map(item => item.id === args.id ? { ...item, ...template } : item) : [...all.templates, template]
|
|
4456
|
+
await saveTemplates(all)
|
|
4457
|
+
return { templates: all.templates, template }
|
|
4458
|
+
},
|
|
4459
|
+
}),
|
|
4460
|
+
|
|
3303
4461
|
asTool({
|
|
3304
4462
|
name: 'ops_monitors',
|
|
3305
4463
|
description:
|
|
3306
|
-
'List, add, remove or
|
|
3307
|
-
+ 'process (command pattern), service (systemd unit).',
|
|
4464
|
+
'List, add, remove, test or diagnose service monitors on a host. Types: http (URL), port (host:port), '
|
|
4465
|
+
+ 'process (command pattern), service (systemd unit), script (shell/python/js, exit 0/1/2/3 = ok/warn/crit/unknown).',
|
|
3308
4466
|
parameters: {
|
|
3309
4467
|
host: { type: 'string', description: 'host name from ops_hosts' },
|
|
3310
4468
|
action: { type: 'string', enum: ['list', 'add', 'remove', 'test', 'diagnose'], description: 'defaults to list' },
|
|
@@ -3314,6 +4472,7 @@ export function apply(ctx) {
|
|
|
3314
4472
|
target: { type: 'string', description: 'URL, host:port, process pattern or unit name' },
|
|
3315
4473
|
label: { type: 'string', description: 'short display name' },
|
|
3316
4474
|
intervalMinutes: { type: 'number', description: 'check interval; defaults to 5' },
|
|
4475
|
+
maxAttempts: { type: 'number', description: 'consecutive failures before alerting; defaults to 3' },
|
|
3317
4476
|
id: { type: 'string', description: 'with action=remove or test' },
|
|
3318
4477
|
},
|
|
3319
4478
|
async execute(args = {}) {
|
|
@@ -3343,6 +4502,7 @@ export function apply(ctx) {
|
|
|
3343
4502
|
target: String(args.target ?? '').trim(),
|
|
3344
4503
|
label: String(args.label ?? '').trim(),
|
|
3345
4504
|
intervalMinutes: Math.max(1, Math.min(Number(args.intervalMinutes) || 5, 1440)),
|
|
4505
|
+
maxAttempts: Math.max(1, Math.min(Number(args.maxAttempts) || 3, 10)),
|
|
3346
4506
|
createdAt: new Date().toISOString(),
|
|
3347
4507
|
...(['shell', 'python', 'js'].includes(args.language) ? { language: args.language } : {}),
|
|
3348
4508
|
...(args.script ? { script: String(args.script).slice(0, 4000) } : {}),
|
|
@@ -3481,10 +4641,13 @@ export function apply(ctx) {
|
|
|
3481
4641
|
host: { type: 'string', description: 'host name from ops_hosts' },
|
|
3482
4642
|
source: { type: 'string', description: 'unit name, file:/absolute/path, pid:<pid>, or jar:<jar name>' },
|
|
3483
4643
|
lines: { type: 'number', description: 'line count; defaults to 200' },
|
|
4644
|
+
sinceMinutes: { type: 'number', description: 'only journal entries from the last N minutes' },
|
|
4645
|
+
grep: { type: 'string', description: 'case-insensitive keyword filter' },
|
|
4646
|
+
level: { type: 'string', enum: ['error', 'warn'], description: 'only error or warning lines' },
|
|
3484
4647
|
},
|
|
3485
4648
|
async execute(args = {}) {
|
|
3486
4649
|
const cfg = pickHost(await loadHosts(), args.host)
|
|
3487
|
-
return tailLog(cfg, String(args.source ?? ''), args.lines ?? 200)
|
|
4650
|
+
return tailLog(cfg, String(args.source ?? ''), args.lines ?? 200, { sinceMinutes: args.sinceMinutes, grep: args.grep, level: args.level })
|
|
3488
4651
|
},
|
|
3489
4652
|
}),
|
|
3490
4653
|
|
|
@@ -3553,8 +4716,9 @@ export function apply(ctx) {
|
|
|
3553
4716
|
asTool({
|
|
3554
4717
|
name: 'ops_cleanup',
|
|
3555
4718
|
description:
|
|
3556
|
-
'
|
|
3557
|
-
+ '
|
|
4719
|
+
'Free disk space on one host: vacuum the systemd journal to 200 MB and delete rotated logs '
|
|
4720
|
+
+ '(*.gz, *.old, messages-/secure-/maillog-/cron-*) older than 7 days. Recent logs and business '
|
|
4721
|
+
+ 'data are untouched. Returns the disk percentage before and after.',
|
|
3558
4722
|
parameters: {
|
|
3559
4723
|
host: { type: 'string', description: 'host name from ops_hosts; defaults to the default host' },
|
|
3560
4724
|
confirm: { type: 'boolean', description: 'must be true: this deletes log data' },
|
|
@@ -3694,6 +4858,8 @@ export function apply(ctx) {
|
|
|
3694
4858
|
void runMetricsPass().catch(() => {})
|
|
3695
4859
|
void runMonitorPass().catch(() => {})
|
|
3696
4860
|
void checkCertAlerts().catch(() => {})
|
|
4861
|
+
void logGrowthPass().catch(() => {})
|
|
4862
|
+
void logAutoCleanPass().catch(() => {})
|
|
3697
4863
|
}
|
|
3698
4864
|
const previous = globalThis.__opsKitScheduler
|
|
3699
4865
|
if (previous) { clearInterval(previous.handle); clearTimeout(previous.first) }
|