dsh-ops-kit 0.3.2 → 0.3.4

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/client.js CHANGED
@@ -96,7 +96,9 @@ window.__ModuleLoader__.load({
96
96
  aiNeedTerm: '先连上终端,生成的命令才会发到服务器', aiModel: '模型',
97
97
  process: '进程', byCpu: '按 CPU', byMem: '按内存', pid: 'PID', cpuUse: 'CPU', memUse: '内存', cmd: '命令',
98
98
  end: '结束', ending: '结束中…', confirmKill: '结束这个进程?',
99
- logs: '日志', logSource: '来源(nginx.service 或 file:/var/log/x.log)', lines: '行数', load: '读取', auto: '自动刷新(5s)',
99
+ logs: '日志', logSource: '日志来源(可下拉选:服务名 / pid:12345 / file:/var/log/x.log)', lines: '行数', load: '读取', auto: '自动刷新(5s)',
100
+ logHint: '不知道填什么?点输入框会弹出下拉列表:systemd 服务(如 nginx.service)、java 进程(pid:12345)、或日志文件(file:/var/log/xxx.log)。选 java 进程时插件自己找日志——属于某个服务就用 journalctl,否则取它打开的最新 .log / .out 文件。',
101
+ logPick: '先选一个来源(点输入框有下拉列表),再点「读取」。',
100
102
  ssl: '证书', domain: '域名', checkSsl: '检查证书', daysLeft: '剩余天数', expireAt: '到期', noExpire: '没读到证书',
101
103
  files: '文件', upload: '上传', newFolder: '新建文件夹', size: '大小', modified: '修改时间', open: '进入', download: '下载', del: '删除', folderName: '文件夹名', confirmDel: '删除这个路径?',
102
104
  ask: '问一下', diagnose: '智能诊断', diagnosing: '诊断中…', askPh: '例如:网站为什么打不开?',
@@ -177,7 +179,9 @@ window.__ModuleLoader__.load({
177
179
  aiNeedTerm: 'Connect the terminal first so the command can be sent', aiModel: 'model',
178
180
  process: 'Processes', byCpu: 'By CPU', byMem: 'By memory', pid: 'PID', cpuUse: 'CPU', memUse: 'MEM', cmd: 'Command',
179
181
  end: 'End', ending: 'Ending…', confirmKill: 'Kill this process?',
180
- logs: 'Logs', logSource: 'Source (nginx.service or file:/var/log/x.log)', lines: 'Lines', load: 'Load', auto: 'Auto refresh (5s)',
182
+ logs: 'Logs', logSource: 'Log source (pick from the list: unit / pid:12345 / file:/var/log/x.log)', lines: 'Lines', load: 'Load', auto: 'Auto refresh (5s)',
183
+ logHint: 'Not sure what to type? Click the field for a list: a systemd unit (nginx.service), a java process (pid:12345), or a log file (file:/var/log/x.log). For a java process the plugin finds the log itself — journalctl when it belongs to a unit, otherwise the newest .log / .out file it has open.',
184
+ logPick: 'Pick a source first (click the field for the list), then press Load.',
181
185
  ssl: 'Certificate', domain: 'Domain', checkSsl: 'Check certificate', daysLeft: 'days left', expireAt: 'expires', noExpire: 'no certificate read',
182
186
  files: 'Files', upload: 'Upload', newFolder: 'New folder', size: 'Size', modified: 'Modified', open: 'Open', download: 'Download', del: 'Delete', folderName: 'Folder name', confirmDel: 'Delete this path?',
183
187
  ask: 'Ask', diagnose: 'Diagnose', diagnosing: 'Diagnosing…', askPh: 'e.g. why is the site down?',
@@ -516,11 +520,19 @@ window.__ModuleLoader__.load({
516
520
  } catch (e) { setError(String(e.message || e)) } finally { setBusy('') }
517
521
  }
518
522
 
519
- const loadLogs = async () => {
523
+ const loadLogs = async (src) => {
524
+ const source = String(src ?? logSource).trim()
525
+ if (!source) { setLogText(T.logPick); return }
520
526
  setBusy('logs')
521
527
  try {
522
- const data = await api(`tail?host=${encodeURIComponent(cHost || hosts[0]?.name)}&source=${encodeURIComponent(logSource)}&lines=${logLines}`, {}, timeoutFor('action'))
523
- setLogText(data.lines || data.error || '')
528
+ const data = await api(`tail?host=${encodeURIComponent(cHost || hosts[0]?.name)}&source=${encodeURIComponent(source)}&lines=${logLines}`, {}, timeoutFor('action'))
529
+ if (data.missing) {
530
+ setLogText(data.error || '')
531
+ void loadInv(cHost || hosts[0]?.name, true)
532
+ return
533
+ }
534
+ const head = data.resolved ? `# ${data.via === 'journal' ? 'journalctl -u ' + data.resolved : data.resolved}\n\n` : ''
535
+ setLogText(head + (data.lines || data.error || ''))
524
536
  } catch (e) { setLogText(String(e.message || e)) } finally { setBusy('') }
525
537
  }
526
538
 
@@ -1069,7 +1081,20 @@ window.__ModuleLoader__.load({
1069
1081
  h('span', { className: app.status ? 'ops-ok' : 'ops-dim', style: { fontSize: '12px' } }, app.status || ''),
1070
1082
  h('span', { style: { display: 'flex', gap: '6px', justifyContent: 'flex-end' } },
1071
1083
  app.config ? h('button', { className: 'ops-btn ops-btn-sm', onClick: () => { void openFile(app.config, app.name) } }, T.configFile) : null,
1072
- h('button', { className: 'ops-btn ops-btn-sm', disabled: busy === `act:${app.kind}:${app.name}:logs`, onClick: () => { void doAction(app.kind, app.name, 'logs') } }, busy === `act:${app.kind}:${app.name}:logs` ? T.reading : T.logs),
1084
+ h('button', {
1085
+ className: 'ops-btn ops-btn-sm',
1086
+ disabled: busy === `act:${app.kind}:${app.name}:logs`,
1087
+ onClick: () => {
1088
+ if (app.kind === 'java') {
1089
+ const src = app.jar ? `jar:${app.jar}` : `pid:${String(app.pid || app.name).replace(/[^0-9]/g, '')}`
1090
+ setLogSource(src)
1091
+ setDetailTab('logs')
1092
+ void loadLogs(src)
1093
+ return
1094
+ }
1095
+ void doAction(app.kind, app.name, 'logs')
1096
+ },
1097
+ }, busy === `act:${app.kind}:${app.name}:logs` ? T.reading : T.logs),
1073
1098
  app.kind === 'service' ? h('button', { className: 'ops-btn ops-btn-sm', disabled: busy === `act:${app.kind}:${app.name}:stop`, onClick: () => { void doAction(app.kind, app.name, 'stop') } }, T.stop) : null,
1074
1099
  app.kind !== 'java' ? h('button', { className: 'ops-btn ops-btn-sm', disabled: busy === `act:${app.kind}:${app.name}:restart`, onClick: () => { void doAction(app.kind, app.name, 'restart') } }, busy === `act:${app.kind}:${app.name}:restart` ? '…' : T.restart) : null))))),
1075
1100
  output ? h('pre', { className: 'ops-pre' }, output) : null,
@@ -1137,6 +1162,15 @@ window.__ModuleLoader__.load({
1137
1162
  h('div', { className: sslResult.daysLeft !== null && sslResult.daysLeft < 15 ? 'ops-bad' : 'ops-sub', style: { fontSize: '12px' } },
1138
1163
  sslResult.daysLeft === null ? T.noExpire : `${T.expireAt} ${sslResult.notAfter} · ${T.daysLeft} ${sslResult.daysLeft}`)) : null)))
1139
1164
 
1165
+ const logChoices = (() => {
1166
+ const apps = inv?.apps || []
1167
+ const services = apps.filter(a => a.kind === 'service').map(a => a.name)
1168
+ const pids = apps.filter(a => a.kind === 'java').map(a => `pid:${String(a.name).replace(/[^0-9]/g, '')}`)
1169
+ const files = ['file:/var/log/syslog', 'file:/var/log/messages', 'file:/var/log/nginx/error.log',
1170
+ 'file:/var/log/nginx/access.log', 'file:/var/log/auth.log']
1171
+ return [...services, ...pids, ...files]
1172
+ })()
1173
+
1140
1174
  const logsView = h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } },
1141
1175
  h('div', { className: 'ops-chips' }, (detailHost ? null : hostPicker(cHost, setCHost))),
1142
1176
  h('div', { className: 'ops-card' },
@@ -1147,9 +1181,15 @@ window.__ModuleLoader__.load({
1147
1181
  h('button', { className: 'ops-btn ops-btn-primary ops-btn-sm', disabled: busy === 'logs', onClick: () => { void loadLogs() } }, busy === 'logs' ? T.reading : T.load))),
1148
1182
  h('div', { className: 'ops-card-b' },
1149
1183
  h('div', { className: 'ops-chips' },
1150
- h('input', { className: 'ops-input', style: { flex: '1 1 320px' }, value: logSource, placeholder: T.logSource, onChange: e => setLogSource(e.target.value), onKeyDown: e => { if (e.key === 'Enter') void loadLogs() } }),
1184
+ h('input', {
1185
+ className: 'ops-input', style: { flex: '1 1 320px' }, value: logSource, list: 'ops-log-sources',
1186
+ placeholder: T.logSource, onChange: e => setLogSource(e.target.value),
1187
+ onKeyDown: e => { if (e.key === 'Enter') void loadLogs() },
1188
+ }),
1189
+ h('datalist', { id: 'ops-log-sources' }, ...logChoices.map(o => h('option', { key: o, value: o }))),
1151
1190
  h('label', { className: 'ops-sub' }, T.lines,
1152
1191
  h('input', { className: 'ops-input', type: 'number', min: 20, max: 1000, value: logLines, style: { width: '90px' }, onChange: e => setLogLines(Number(e.target.value)) }))),
1192
+ h('p', { className: 'ops-sub', style: { margin: '0 0 8px', fontSize: '12px' } }, T.logHint),
1153
1193
  h('pre', { className: 'ops-pre', style: { maxHeight: '55vh' } }, logText || (busy === 'logs' ? T.reading : '')))))
1154
1194
 
1155
1195
  const filesView = h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } },
package/docs/USAGE.md CHANGED
@@ -99,6 +99,10 @@ Click a host from the overview; the left side has ten sub-pages:
99
99
  | **Tasks** | visual crontab editing |
100
100
  | **Deploy** | one-click job: git pull → build → restart → health check |
101
101
 
102
+ **You do not have to remember log sources**: clicking the source field opens a list — a systemd unit (`nginx.service`), a java process (`pid:3154754`), or a log file (`file:/var/log/x.log`). For a java process the plugin finds the log itself: `journalctl -u` when the process belongs to a unit, otherwise the newest `.log` / `.out` file it has open. The resolved source is shown above the output.
103
+
104
+ **A java app restarts, so its pid changes**: clicking Logs on a java row uses `jar:<jar file>` instead — it looks up the current pid from the command line, so it keeps working after a restart. If you type a `pid:12345` that no longer exists, the page says so explicitly and rescans the inventory for you.
105
+
102
106
  **Restart, stop, restore and rollback all ask for confirmation first.**
103
107
 
104
108
  ---
@@ -86,6 +86,10 @@ ops_check_all
86
86
  | **计划任务** | crontab 可视化增删 |
87
87
  | **发布** | 一键发布任务:git pull → 构建 → 重启 → 健康检查 |
88
88
 
89
+ **日志来源不用记**:点来源输入框会弹出列表 —— systemd 服务名(`nginx.service`)、java 进程(`pid:3154754`)、或日志文件(`file:/var/log/xxx.log`)。选 java 进程时插件自己找日志:该进程属于某个服务就用 `journalctl -u`,否则取它打开的最新的 `.log` / `.out` 文件。读取结果顶部会标出实际用的来源。
90
+
91
+ **java 应用会重启,pid 会变**:所以在「应用」页点 java 进程的「日志」时,插件优先用 `jar:<jar 文件名>` 定位(按命令行反查当前 pid,重启后仍然有效)。如果你手动填了 `pid:12345` 而那个进程已经没了,页面会明确告诉你,并自动重新扫描清单。
92
+
89
93
  **重启 / 停止 / 回滚 / 恢复都会先弹确认**,不会点了就执行。
90
94
 
91
95
  ---
package/index.js CHANGED
@@ -592,10 +592,16 @@ function createApiHandler({ connection } = {}) {
592
592
  if (route === 'app' && method === 'POST') {
593
593
  const body = (await readBody(req)) || {}
594
594
  const kind = String(body.kind ?? '')
595
- if (!['service', 'docker'].includes(kind)) { sendJson(res, 400, { error: 'unsupported app kind' }); return }
595
+ if (!['service', 'docker', 'java'].includes(kind)) { sendJson(res, 400, { error: 'unsupported app kind' }); return }
596
596
  const action = String(body.action ?? 'logs')
597
597
  if (action !== 'logs' && body.confirm !== true) { sendJson(res, 400, { error: 'changing an app needs confirm=true' }); return }
598
598
  const cfg = pickHost(await loadHosts(), body.host)
599
+ if (kind === 'java') {
600
+ if (action !== 'logs') { sendJson(res, 400, { error: 'a java process only supports logs' }); return }
601
+ const pid = Number(String(body.name ?? '').replace(/[^0-9]/g, ''))
602
+ sendJson(res, 200, await tailProcessLog(cfg, pid, Number(body.lines) || 200))
603
+ return
604
+ }
599
605
  sendJson(res, 200, await hostAction(kind, cfg, String(body.name ?? ''), action))
600
606
  return
601
607
  }
@@ -1356,7 +1362,8 @@ async function discover(cfg) {
1356
1362
  ...docker.map(row => ({ kind: 'docker', name: row.name, status: row.status, ports: row.ports, config: null })),
1357
1363
  ...services.filter(name => !/^(systemd-|dbus|cron|crond|sshd|rsyslog|polkit|NetworkManager|auditd|tuned|chronyd|irqbalance|atd|rngd|rpcbind|gssproxy|firewalld|BT-FirewallServices|aegis|aliyun|cloudmonitor|getty|serial-getty|user@|postfix)/.test(name))
1358
1364
  .map(name => ({ kind: 'service', name, status: 'running', ports: '', config: configFor(name) })),
1359
- ...java.map(row => ({ kind: 'java', name: `java pid ${row.pid}`, status: row.uptime, ports: '', config: null })),
1365
+ ...java.map(row => ({ kind: 'java', name: `java pid ${row.pid}`, status: row.uptime, ports: '', config: null,
1366
+ pid: row.pid, jar: String(row.cmd || '').replace(/^.*-jar\s+/, '').replace(/\s.*$/, '').replace(/^.*\//, '') })),
1360
1367
  ]
1361
1368
  const portRows = lines('ports').filter(line => /^LISTEN/.test(line)).map(line => {
1362
1369
  const portMatch = line.match(/(?:\d{1,3}\.){3}\d{1,3}:(\d+)|\*:(\d+)|:(\d+)\s/)
@@ -1663,6 +1670,7 @@ async function killProcess(cfg, pid, signal = 'TERM') {
1663
1670
  async function tailLog(cfg, source, lines = 200) {
1664
1671
  const n = Math.min(Math.max(Number(lines) || 200, 20), 1000)
1665
1672
  const raw = String(source || '')
1673
+ if (raw.startsWith('pid:') || raw.startsWith('jar:')) return await tailProcessLog(cfg, raw, n)
1666
1674
  let command
1667
1675
  if (raw.startsWith('file:')) {
1668
1676
  const path = raw.slice(5)
@@ -1676,6 +1684,75 @@ async function tailLog(cfg, source, lines = 200) {
1676
1684
  return { host: cfg.name, source: raw, ok: result.ok, lines: String(result.stdout || '').slice(0, 60_000), error: result.ok ? '' : cleanStderr(result.stderr) }
1677
1685
  }
1678
1686
 
1687
+ /**
1688
+ * Log for a bare PID (java processes have no unit name).
1689
+ * Uses the owning systemd unit when there is one, otherwise tails the newest
1690
+ * .log/.out file the process actually has open.
1691
+ */
1692
+ async function tailProcessLog(cfg, source, lines = 200) {
1693
+ const n = Math.min(Math.max(Number(lines) || 200, 20), 1000)
1694
+ const raw = String(source || '')
1695
+
1696
+ let pid = 0
1697
+ if (raw.startsWith('jar:')) {
1698
+ const jar = raw.slice(4).trim()
1699
+ if (!/^[A-Za-z0-9._@/-]+$/.test(jar)) throw new Error('bad jar name')
1700
+ const found = await ssh(cfg, `pgrep -f -- ${JSON.stringify(jar)} 2>/dev/null | head -1`, 20_000)
1701
+ pid = Number(String(found.stdout || '').trim())
1702
+ if (!pid) {
1703
+ return {
1704
+ host: cfg.name, source: raw, resolved: '', via: 'none', missing: true, ok: false, lines: '',
1705
+ error: `没有找到正在运行 ${jar} 的进程。应用可能没在跑,或启动方式已变(不再带 -jar)。到「应用」页点「重新扫描」看看当前进程。`,
1706
+ }
1707
+ }
1708
+ } else {
1709
+ pid = Number(raw.slice(4))
1710
+ if (!Number.isInteger(pid) || pid <= 0) throw new Error('a valid pid is required')
1711
+ }
1712
+
1713
+ // One round trip: an existing pid's unit, or a marker when the pid is gone.
1714
+ const probe = await ssh(cfg, `if [ -d /proc/${pid} ]; then ps -o unit= -p ${pid} 2>/dev/null | tr -d ' \\n'; else echo '__GONE__'; fi`, 20_000)
1715
+ const probed = String(probe.stdout || '').trim()
1716
+ if (probed === '__GONE__') {
1717
+ return {
1718
+ host: cfg.name, source: raw, resolved: '', via: 'none', missing: true, ok: false, lines: '',
1719
+ error: `PID ${pid} 已经不存在了(应用可能重启过)。到「应用」页点「重新扫描」取最新的进程;如果这个应用会重启,改用 jar 名定位更稳。`,
1720
+ }
1721
+ }
1722
+
1723
+ if (probed && probed !== '-' && !probed.startsWith('session-') && !probed.includes(' ')) {
1724
+ const res = await ssh(cfg, `journalctl -u ${probed} -n ${n} --no-pager 2>&1`, 25_000)
1725
+ return {
1726
+ host: cfg.name, source: raw, resolved: probed, via: 'journal',
1727
+ ok: res.ok, lines: String(res.stdout || '').slice(0, 60_000),
1728
+ error: res.ok ? '' : cleanStderr(res.stderr),
1729
+ }
1730
+ }
1731
+
1732
+ const scan = await ssh(
1733
+ cfg,
1734
+ `for f in /proc/${pid}/fd/*; do t=$(readlink "$f" 2>/dev/null); case "$t" in *.log|*.out) [ -f "$t" ] && printf '%s\\n' "$t";; esac; done 2>/dev/null | sort -u | head -20`,
1735
+ 20_000,
1736
+ )
1737
+ const files = String(scan.stdout || '').split('\n').map(s => s.trim()).filter(f => f.startsWith('/'))
1738
+ if (files.length === 0) {
1739
+ return {
1740
+ host: cfg.name, source: raw, resolved: '', via: 'none', ok: false, lines: '',
1741
+ error: `PID ${pid} 不是 systemd 服务,也没有打开 .log / .out 文件。请到「文件」页找到日志路径,再在来源里填 file:/var/log/xxx.log`,
1742
+ }
1743
+ }
1744
+
1745
+ const quoted = files.map(f => JSON.stringify(f)).join(' ')
1746
+ const newest = await ssh(cfg, `ls -1t ${quoted} 2>/dev/null | head -1`, 20_000)
1747
+ const picked = String(newest.stdout || '').split('\n')[0].trim() || files[0]
1748
+ const res = await ssh(cfg, `tail -n ${n} ${JSON.stringify(picked)} 2>&1`, 25_000)
1749
+ return {
1750
+ host: cfg.name, source: raw, resolved: picked, via: 'file',
1751
+ ok: res.ok, lines: String(res.stdout || '').slice(0, 60_000),
1752
+ error: res.ok ? '' : cleanStderr(res.stderr),
1753
+ }
1754
+ }
1755
+
1679
1756
  /** TLS certificate expiry for a domain (checked from the host itself). */
1680
1757
  async function sslCheck(cfg, domain) {
1681
1758
  const host = String(domain || '').replace(/[^A-Za-z0-9.-]/g, '')
@@ -3289,10 +3366,10 @@ export function apply(ctx) {
3289
3366
 
3290
3367
  asTool({
3291
3368
  name: 'ops_logs',
3292
- description: 'Last N lines from a systemd unit or a log file on a host. Use source "nginx.service" or "file:/var/log/nginx/error.log".',
3369
+ description: 'Last N lines from a systemd unit, a log file, a bare pid or a java app. Use source "nginx.service", "file:/var/log/nginx/error.log", "pid:1234" for one process, or "jar:app.jar" to follow a java app across restarts.',
3293
3370
  parameters: {
3294
3371
  host: { type: 'string', description: 'host name from ops_hosts' },
3295
- source: { type: 'string', description: 'unit name, or file:/absolute/path' },
3372
+ source: { type: 'string', description: 'unit name, file:/absolute/path, pid:<pid>, or jar:<jar name>' },
3296
3373
  lines: { type: 'number', description: 'line count; defaults to 200' },
3297
3374
  },
3298
3375
  async execute(args = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ops-kit",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "Server operations kit for DeepSeek Harness: server cards, health charts, config browser, app manager and plain-language AI diagnosis — over SSH, no agent install.",
5
5
  "license": "MIT",
6
6
  "type": "module",