@hua-ri/dsh-ops 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +60 -2
- package/client.js +183 -0
- package/cordis.patch.yml +3 -0
- package/index.js +1079 -0
- package/lib/argocd/instances.mjs +50 -0
- package/lib/argocd/mod.mjs +221 -0
- package/lib/argowf/instances.mjs +52 -0
- package/lib/argowf/mod.mjs +219 -0
- package/lib/cli.mjs +95 -0
- package/lib/client.js +56 -0
- package/lib/helm/mod.mjs +281 -0
- package/lib/k8s/context.mjs +179 -0
- package/lib/k8s/mod.mjs +347 -0
- package/lib/ssh/config.mjs +53 -0
- package/lib/ssh/hosts.mjs +94 -0
- package/lib/ssh/keys.mjs +76 -0
- package/lib/ssh/mod.mjs +476 -0
- package/lib/ssh/snippet-vars.mjs +22 -0
- package/lib/ssh/tunnels.mjs +97 -0
- package/package.json +60 -4
- package/scripts/doctor.mjs +35 -0
package/index.js
ADDED
|
@@ -0,0 +1,1079 @@
|
|
|
1
|
+
let defineTool = null
|
|
2
|
+
try {
|
|
3
|
+
;({ defineTool } = await import('@deepseek-ai/dsh-tools'))
|
|
4
|
+
} catch {}
|
|
5
|
+
|
|
6
|
+
import { readJson, writeJson, dataDir, ensureDataDir, which, exec, trimOutput } from './lib/cli.mjs'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { mkdirSync, readdirSync, statSync, existsSync } from 'node:fs'
|
|
9
|
+
import { homedir } from 'node:os'
|
|
10
|
+
|
|
11
|
+
import { loadHosts, findHost, addHost, removeHost, updateHost, buildSshArgs, buildRelayCommand } from './lib/ssh/hosts.mjs'
|
|
12
|
+
import { readSshConfig } from './lib/ssh/config.mjs'
|
|
13
|
+
import { substituteVars, extractVars } from './lib/ssh/snippet-vars.mjs'
|
|
14
|
+
import { listKeys, generateKey, deleteKey } from './lib/ssh/keys.mjs'
|
|
15
|
+
import { createTunnel, listTunnels, closeTunnel } from './lib/ssh/tunnels.mjs'
|
|
16
|
+
import { loadContexts, findContext, addContext, removeContext, updateContext, buildKubectlArgs, parseKubeconfig, importContexts } from './lib/k8s/context.mjs'
|
|
17
|
+
import * as argocdInst from './lib/argocd/instances.mjs'
|
|
18
|
+
import * as argowfInst from './lib/argowf/instances.mjs'
|
|
19
|
+
|
|
20
|
+
const name = 'dsh-ops'
|
|
21
|
+
const inject = ['webServer']
|
|
22
|
+
|
|
23
|
+
const DEFAULT_CONFIG = {
|
|
24
|
+
ssh: { enabled: true },
|
|
25
|
+
k8s: { enabled: true },
|
|
26
|
+
argocd: { enabled: false },
|
|
27
|
+
argowf: { enabled: false },
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function configPath() { return join(dataDir(), 'config.json') }
|
|
31
|
+
function loadModuleConfig() { return readJson(configPath(), DEFAULT_CONFIG) }
|
|
32
|
+
function saveModuleConfig(cfg) { ensureDataDir(); writeJson(configPath(), cfg) }
|
|
33
|
+
|
|
34
|
+
function snippetsPath() { return join(dataDir(), 'ssh', 'snippets.json') }
|
|
35
|
+
function loadSnippets() { return readJson(snippetsPath(), []) }
|
|
36
|
+
function saveSnippets(list) {
|
|
37
|
+
mkdirSync(join(dataDir(), 'ssh'), { recursive: true })
|
|
38
|
+
writeJson(snippetsPath(), list)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
let registeredToolCount = 0
|
|
42
|
+
|
|
43
|
+
async function readBody(req) {
|
|
44
|
+
const chunks = []
|
|
45
|
+
for await (const c of req) chunks.push(c)
|
|
46
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function jsonBody(req) {
|
|
50
|
+
return JSON.parse(await readBody(req))
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function ok(res, data) {
|
|
54
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
55
|
+
res.end(JSON.stringify(data))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function err(res, status, msg) {
|
|
59
|
+
res.writeHead(status, { 'content-type': 'application/json' })
|
|
60
|
+
res.end(JSON.stringify({ ok: false, error: msg }))
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function sshExec(host, command, opts = {}) {
|
|
64
|
+
const relay = buildRelayCommand(host, command)
|
|
65
|
+
if (relay) return exec('ssh', relay.args, { timeout: opts.timeout || 30000, stdin: opts.stdin })
|
|
66
|
+
const { args, target } = buildSshArgs(host)
|
|
67
|
+
args.push(target, command)
|
|
68
|
+
return exec('ssh', args, { timeout: opts.timeout || 30000, stdin: opts.stdin })
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function apply(ctx) {
|
|
72
|
+
const toolsSvc = (() => { try { return ctx.get?.('tools') } catch { return null } })()
|
|
73
|
+
const cfg = loadModuleConfig()
|
|
74
|
+
|
|
75
|
+
if (defineTool && toolsSvc?.register) {
|
|
76
|
+
if (cfg.ssh?.enabled !== false) {
|
|
77
|
+
const { registerSSHTools } = await import('./lib/ssh/mod.mjs')
|
|
78
|
+
registerSSHTools(ctx, defineTool, toolsSvc, cfg.ssh)
|
|
79
|
+
registeredToolCount += 17
|
|
80
|
+
}
|
|
81
|
+
if (cfg.k8s?.enabled !== false) {
|
|
82
|
+
const { registerK8sTools } = await import('./lib/k8s/mod.mjs')
|
|
83
|
+
registerK8sTools(ctx, defineTool, toolsSvc, cfg.k8s)
|
|
84
|
+
registeredToolCount += 12
|
|
85
|
+
}
|
|
86
|
+
if (cfg.argocd?.enabled) {
|
|
87
|
+
const { registerArgocdTools } = await import('./lib/argocd/mod.mjs')
|
|
88
|
+
registerArgocdTools(ctx, defineTool, toolsSvc, cfg.argocd)
|
|
89
|
+
registeredToolCount += 9
|
|
90
|
+
}
|
|
91
|
+
if (cfg.argowf?.enabled) {
|
|
92
|
+
const { registerArgowfTools } = await import('./lib/argowf/mod.mjs')
|
|
93
|
+
registerArgowfTools(ctx, defineTool, toolsSvc, cfg.argowf)
|
|
94
|
+
registeredToolCount += 8
|
|
95
|
+
}
|
|
96
|
+
if (cfg.k8s?.enabled !== false) {
|
|
97
|
+
const { registerHelmTools } = await import('./lib/helm/mod.mjs')
|
|
98
|
+
registerHelmTools(ctx, defineTool, toolsSvc, cfg.k8s)
|
|
99
|
+
registeredToolCount += 10
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const ROUTE = '/api/dsh-ops'
|
|
104
|
+
|
|
105
|
+
ctx.webServer.register({
|
|
106
|
+
kind: 'prefix',
|
|
107
|
+
path: ROUTE,
|
|
108
|
+
handler: async (req, res) => {
|
|
109
|
+
const url = new URL(req.url, 'http://localhost')
|
|
110
|
+
const path = url.pathname.slice(ROUTE.length)
|
|
111
|
+
const method = req.method
|
|
112
|
+
|
|
113
|
+
try {
|
|
114
|
+
// ───── General ─────
|
|
115
|
+
if (method === 'GET' && path === '/status') {
|
|
116
|
+
const deps = {}
|
|
117
|
+
for (const bin of ['ssh', 'kubectl', 'helm', 'argocd', 'argo']) {
|
|
118
|
+
const p = await which(bin)
|
|
119
|
+
deps[bin] = { ok: !!p, path: p || null }
|
|
120
|
+
}
|
|
121
|
+
return ok(res, {
|
|
122
|
+
config: loadModuleConfig(),
|
|
123
|
+
deps,
|
|
124
|
+
toolCount: registeredToolCount,
|
|
125
|
+
hostCount: loadHosts().length,
|
|
126
|
+
contextCount: loadContexts().length,
|
|
127
|
+
argocdCount: argocdInst.loadInstances().length,
|
|
128
|
+
argowfCount: argowfInst.loadInstances().length,
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (method === 'POST' && path === '/config') {
|
|
133
|
+
const body = await jsonBody(req)
|
|
134
|
+
const cfg = loadModuleConfig()
|
|
135
|
+
if (body.module && typeof body.enabled === 'boolean') {
|
|
136
|
+
if (cfg[body.module]) cfg[body.module].enabled = body.enabled
|
|
137
|
+
else cfg[body.module] = { enabled: body.enabled }
|
|
138
|
+
saveModuleConfig(cfg)
|
|
139
|
+
}
|
|
140
|
+
return ok(res, { ok: true, config: cfg })
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ───── SSH Hosts ─────
|
|
144
|
+
if (method === 'GET' && path === '/ssh/hosts') {
|
|
145
|
+
return ok(res, loadHosts())
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (method === 'POST' && path === '/ssh/hosts') {
|
|
149
|
+
const body = await jsonBody(req)
|
|
150
|
+
const r = addHost({
|
|
151
|
+
name: body.name, hostname: body.hostname,
|
|
152
|
+
port: body.port, user: body.user,
|
|
153
|
+
identityFile: body.identity_file || body.identityFile,
|
|
154
|
+
proxyJump: body.proxyJump || body.proxy_jump || null,
|
|
155
|
+
relay: body.relay || null,
|
|
156
|
+
tags: body.tags, note: body.note,
|
|
157
|
+
})
|
|
158
|
+
if (!r.ok) return err(res, 400, r.why)
|
|
159
|
+
return ok(res, { ok: true, hosts: loadHosts() })
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const hostMatch = path.match(/^\/ssh\/hosts\/([^/]+)$/)
|
|
163
|
+
if (hostMatch) {
|
|
164
|
+
const hostName = decodeURIComponent(hostMatch[1])
|
|
165
|
+
if (method === 'PUT') {
|
|
166
|
+
const body = await jsonBody(req)
|
|
167
|
+
const r = updateHost(hostName, body)
|
|
168
|
+
if (!r.ok) return err(res, 400, r.why)
|
|
169
|
+
return ok(res, { ok: true, hosts: loadHosts() })
|
|
170
|
+
}
|
|
171
|
+
if (method === 'DELETE') {
|
|
172
|
+
const r = removeHost(hostName)
|
|
173
|
+
if (!r.ok) return err(res, 400, r.why)
|
|
174
|
+
return ok(res, { ok: true, hosts: loadHosts() })
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const hostTestMatch = path.match(/^\/ssh\/hosts\/([^/]+)\/test$/)
|
|
179
|
+
if (method === 'POST' && hostTestMatch) {
|
|
180
|
+
const h = findHost(decodeURIComponent(hostTestMatch[1]))
|
|
181
|
+
if (!h) return err(res, 404, '主机不存在')
|
|
182
|
+
const r = await sshExec(h, 'uname -a', { timeout: 15000 })
|
|
183
|
+
return ok(res, { ok: r.code === 0, code: r.code, stdout: r.stdout, stderr: r.stderr })
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const hostPingMatch = path.match(/^\/ssh\/hosts\/([^/]+)\/ping$/)
|
|
187
|
+
if (method === 'POST' && hostPingMatch) {
|
|
188
|
+
const h = findHost(decodeURIComponent(hostPingMatch[1]))
|
|
189
|
+
if (!h) return err(res, 404, '主机不存在')
|
|
190
|
+
const t0 = Date.now()
|
|
191
|
+
const r = await sshExec(h, 'echo ok', { timeout: 10000 })
|
|
192
|
+
const latencyMs = Date.now() - t0
|
|
193
|
+
return ok(res, { ok: r.code === 0, latencyMs, code: r.code })
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const hostStatsMatch = path.match(/^\/ssh\/hosts\/([^/]+)\/stats$/)
|
|
197
|
+
if (method === 'POST' && hostStatsMatch) {
|
|
198
|
+
const h = findHost(decodeURIComponent(hostStatsMatch[1]))
|
|
199
|
+
if (!h) return err(res, 404, '主机不存在')
|
|
200
|
+
const cmd = [
|
|
201
|
+
'C1=$(grep "^cpu" /proc/stat)',
|
|
202
|
+
'sleep 1',
|
|
203
|
+
'C2=$(grep "^cpu" /proc/stat)',
|
|
204
|
+
'echo "===CPU1===" && echo "$C1"',
|
|
205
|
+
'echo "===CPU2===" && echo "$C2"',
|
|
206
|
+
'echo "===LOAD===" && cat /proc/loadavg',
|
|
207
|
+
'echo "===MEM===" && grep -E "^(MemTotal|MemFree|MemAvailable|Buffers|Cached|SwapTotal|SwapFree):" /proc/meminfo',
|
|
208
|
+
'echo "===DISK===" && df -P -k 2>/dev/null | tail -n+2',
|
|
209
|
+
'echo "===PCOUNT===" && echo "$(ps -e --no-headers 2>/dev/null | wc -l) $(ps -eo nlwp --no-headers 2>/dev/null | awk \'{s+=$1}END{print s}\')"',
|
|
210
|
+
'echo "===PROC===" && ps -eo pid,user:15,%cpu,%mem,nlwp,comm --sort=-%cpu --no-headers 2>/dev/null | head -15',
|
|
211
|
+
].join(' && ')
|
|
212
|
+
const r = await sshExec(h, cmd, { timeout: 15000 })
|
|
213
|
+
if (r.code !== 0) return ok(res, { ok: false, error: r.stderr || `exit ${r.code}` })
|
|
214
|
+
|
|
215
|
+
const out = r.stdout
|
|
216
|
+
const section = (tag) => {
|
|
217
|
+
const re = new RegExp('===' + tag + '===\\n([\\s\\S]*?)(?====\\w|$)')
|
|
218
|
+
const m = out.match(re)
|
|
219
|
+
return m ? m[1].trim() : ''
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
const parseCpuLines = (text) => {
|
|
223
|
+
const result = {}
|
|
224
|
+
for (const line of text.split('\n')) {
|
|
225
|
+
const p = line.trim().split(/\s+/)
|
|
226
|
+
if (p.length < 5) continue
|
|
227
|
+
const id = p[0] === 'cpu' ? 'all' : p[0].replace('cpu', '')
|
|
228
|
+
const nums = p.slice(1).map(Number)
|
|
229
|
+
result[id] = nums
|
|
230
|
+
}
|
|
231
|
+
return result
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const cpu1 = parseCpuLines(section('CPU1'))
|
|
235
|
+
const cpu2 = parseCpuLines(section('CPU2'))
|
|
236
|
+
const cores = []
|
|
237
|
+
let overall = 0
|
|
238
|
+
for (const id of Object.keys(cpu2)) {
|
|
239
|
+
const a = cpu1[id], b = cpu2[id]
|
|
240
|
+
if (!a || !b) continue
|
|
241
|
+
const totalA = a.reduce((s, v) => s + v, 0), totalB = b.reduce((s, v) => s + v, 0)
|
|
242
|
+
const idleA = a[3] + (a[4] || 0), idleB = b[3] + (b[4] || 0)
|
|
243
|
+
const dt = totalB - totalA, di = idleB - idleA
|
|
244
|
+
const usage = dt > 0 ? Math.round((1 - di / dt) * 1000) / 10 : 0
|
|
245
|
+
if (id === 'all') overall = usage
|
|
246
|
+
else cores.push({ id: Number(id), usage })
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const loadParts = section('LOAD').split(/\s+/)
|
|
250
|
+
const load = { '1m': Number(loadParts[0]) || 0, '5m': Number(loadParts[1]) || 0, '15m': Number(loadParts[2]) || 0 }
|
|
251
|
+
|
|
252
|
+
const memLines = section('MEM').split('\n')
|
|
253
|
+
const mem = {}
|
|
254
|
+
for (const l of memLines) {
|
|
255
|
+
const m = l.match(/^(\w+):\s+(\d+)\s+kB/)
|
|
256
|
+
if (m) mem[m[1]] = Math.round(Number(m[2]) / 1024)
|
|
257
|
+
}
|
|
258
|
+
const memory = {
|
|
259
|
+
total: mem.MemTotal || 0, available: mem.MemAvailable || mem.MemFree || 0,
|
|
260
|
+
buffers: mem.Buffers || 0, cached: mem.Cached || 0,
|
|
261
|
+
swapTotal: mem.SwapTotal || 0, swapFree: mem.SwapFree || 0, unit: 'MB',
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const disk = section('DISK').split('\n').filter(Boolean).map(l => {
|
|
265
|
+
const p = l.trim().split(/\s+/)
|
|
266
|
+
return { fs: p[0], size: Number(p[1]) || 0, used: Number(p[2]) || 0, avail: Number(p[3]) || 0, mount: p[5] || p[4] || '' }
|
|
267
|
+
})
|
|
268
|
+
|
|
269
|
+
const procLines = section('PROC').split('\n').filter(Boolean)
|
|
270
|
+
const top = procLines.map(l => {
|
|
271
|
+
const p = l.trim().split(/\s+/)
|
|
272
|
+
const threads = Number(p[4]) || 1
|
|
273
|
+
return { pid: Number(p[0]), user: p[1], cpu: Number(p[2]) || 0, mem: Number(p[3]) || 0, threads, command: p.slice(5).join(' ') }
|
|
274
|
+
})
|
|
275
|
+
|
|
276
|
+
const pcountParts = section('PCOUNT').trim().split(/\s+/)
|
|
277
|
+
const totalProcs = Number(pcountParts[0]) || procLines.length
|
|
278
|
+
const totalThreads = Number(pcountParts[1]) || 0
|
|
279
|
+
|
|
280
|
+
return ok(res, {
|
|
281
|
+
ok: true,
|
|
282
|
+
cpu: { overall, cores },
|
|
283
|
+
load, memory, disk,
|
|
284
|
+
processes: { total: totalProcs, threads: totalThreads },
|
|
285
|
+
top,
|
|
286
|
+
})
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (method === 'GET' && path === '/ssh/import-preview') {
|
|
290
|
+
const result = readSshConfig()
|
|
291
|
+
if (!result.ok) return ok(res, { ok: false, error: result.error })
|
|
292
|
+
const existing = loadHosts().map(h => h.name)
|
|
293
|
+
const hosts = result.hosts.map(h => ({ ...h, exists: existing.includes(h.name) }))
|
|
294
|
+
return ok(res, { ok: true, hosts, path: result.path })
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (method === 'POST' && path === '/ssh/import') {
|
|
298
|
+
const body = await jsonBody(req)
|
|
299
|
+
if (!Array.isArray(body.hosts) || !body.hosts.length) return err(res, 400, '未选择主机')
|
|
300
|
+
const result = readSshConfig()
|
|
301
|
+
if (!result.ok) return ok(res, { ok: false, error: result.error })
|
|
302
|
+
const imported = [], skipped = []
|
|
303
|
+
for (const name of body.hosts) {
|
|
304
|
+
const parsed = result.hosts.find(h => h.name === name)
|
|
305
|
+
if (!parsed) { skipped.push({ name, reason: 'config 中不存在' }); continue }
|
|
306
|
+
const r = addHost({ name: parsed.name, hostname: parsed.hostname, port: parsed.port, user: parsed.user, identityFile: parsed.identityFile, proxyJump: parsed.proxyJump, tags: body.tags || [], note: '' })
|
|
307
|
+
if (r.ok) imported.push(name)
|
|
308
|
+
else skipped.push({ name, reason: r.why })
|
|
309
|
+
}
|
|
310
|
+
return ok(res, { ok: true, imported, skipped, hosts: loadHosts() })
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// ───── SSH Exec ─────
|
|
314
|
+
if (method === 'POST' && path === '/ssh/exec') {
|
|
315
|
+
const body = await jsonBody(req)
|
|
316
|
+
const h = findHost(body.host)
|
|
317
|
+
if (!h) return err(res, 404, `未找到主机 ${body.host}`)
|
|
318
|
+
const r = await sshExec(h, body.command, { timeout: (body.timeout || 60) * 1000 })
|
|
319
|
+
return ok(res, { ok: r.code === 0, code: r.code, stdout: trimOutput(r.stdout, 8000), stderr: trimOutput(r.stderr, 4000) })
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (method === 'POST' && path === '/ssh/batch') {
|
|
323
|
+
const body = await jsonBody(req)
|
|
324
|
+
const timeout = (body.timeout || 60) * 1000
|
|
325
|
+
const stopOnFailure = body.stop_on_failure !== false
|
|
326
|
+
const concurrency = Math.max(1, Math.min(body.concurrency || 1, 20))
|
|
327
|
+
const results = []
|
|
328
|
+
let stopped = false
|
|
329
|
+
|
|
330
|
+
async function runOne(n) {
|
|
331
|
+
const h = findHost(n)
|
|
332
|
+
if (!h) return { host: n, code: -1, stdout: '', stderr: `未找到主机 ${n}` }
|
|
333
|
+
const r = await sshExec(h, body.command, { timeout })
|
|
334
|
+
return { host: n, code: r.code, stdout: r.stdout?.slice(0, 2000) || '', stderr: r.stderr?.slice(0, 1000) || '' }
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
if (concurrency <= 1) {
|
|
338
|
+
for (let i = 0; i < body.hosts.length; i++) {
|
|
339
|
+
const r = await runOne(body.hosts[i])
|
|
340
|
+
results.push(r)
|
|
341
|
+
if (r.code !== 0 && stopOnFailure) {
|
|
342
|
+
if (i === 0) results.push({ host: '_canary', code: -1, stdout: '', stderr: `canary ${body.hosts[i]} 失败,后续 ${body.hosts.length - 1} 台已跳过` })
|
|
343
|
+
break
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
} else {
|
|
347
|
+
const hosts = [...body.hosts]
|
|
348
|
+
let idx = 0
|
|
349
|
+
async function worker() {
|
|
350
|
+
while (idx < hosts.length && !stopped) {
|
|
351
|
+
const i = idx++
|
|
352
|
+
const r = await runOne(hosts[i])
|
|
353
|
+
results.push(r)
|
|
354
|
+
if (r.code !== 0 && stopOnFailure) stopped = true
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, hosts.length) }, () => worker()))
|
|
358
|
+
}
|
|
359
|
+
return ok(res, { ok: results.every(r => r.code === 0), results })
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// ───── SSH Files ─────
|
|
363
|
+
if (method === 'POST' && path === '/ssh/file/list') {
|
|
364
|
+
const body = await jsonBody(req)
|
|
365
|
+
const h = findHost(body.host)
|
|
366
|
+
if (!h) return err(res, 404, `未找到主机 ${body.host}`)
|
|
367
|
+
const lsFlags = body.all ? '-la' : '-l'
|
|
368
|
+
const r = await sshExec(h, `ls ${lsFlags} --time-style=long-iso ${JSON.stringify(body.path)}`, { timeout: 15000 })
|
|
369
|
+
if (r.code !== 0) return ok(res, { ok: false, error: r.stderr || `exit ${r.code}`, raw: '' })
|
|
370
|
+
const lines = r.stdout.split('\n').filter(l => l.trim() && !l.startsWith('total'))
|
|
371
|
+
const files = lines.map(line => {
|
|
372
|
+
const parts = line.split(/\s+/)
|
|
373
|
+
if (parts.length < 8) return null
|
|
374
|
+
const perm = parts[0], size = parts[4], date = parts[5], time = parts[6]
|
|
375
|
+
const name = parts.slice(7).join(' ').replace(/ -> .*$/, '')
|
|
376
|
+
const isDir = perm.startsWith('d')
|
|
377
|
+
const isLink = perm.startsWith('l')
|
|
378
|
+
return { name, perm, size: parseInt(size) || 0, modified: `${date} ${time}`, isDir, isLink }
|
|
379
|
+
}).filter(Boolean)
|
|
380
|
+
return ok(res, { ok: true, files, path: body.path })
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
if (method === 'POST' && path === '/ssh/file/read') {
|
|
384
|
+
const body = await jsonBody(req)
|
|
385
|
+
const h = findHost(body.host)
|
|
386
|
+
if (!h) return err(res, 404, `未找到主机 ${body.host}`)
|
|
387
|
+
const cmd = body.tail ? `tail -n ${body.tail} ${JSON.stringify(body.path)}` : `cat ${JSON.stringify(body.path)}`
|
|
388
|
+
const r = await sshExec(h, cmd, { timeout: 30000 })
|
|
389
|
+
if (r.code !== 0) return ok(res, { ok: false, error: r.stderr || `exit ${r.code}` })
|
|
390
|
+
return ok(res, { ok: true, content: trimOutput(r.stdout, 50000) })
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ───── SSH Snippets ─────
|
|
394
|
+
if (method === 'GET' && path === '/ssh/snippets') {
|
|
395
|
+
return ok(res, loadSnippets())
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
if (method === 'POST' && path === '/ssh/snippets') {
|
|
399
|
+
const body = await jsonBody(req)
|
|
400
|
+
if (!body.name || !body.command) return err(res, 400, 'name 和 command 必填')
|
|
401
|
+
const list = loadSnippets()
|
|
402
|
+
if (list.find(s => s.name === body.name)) return err(res, 400, `片段 ${body.name} 已存在`)
|
|
403
|
+
list.push({ name: body.name, command: body.command, description: body.description || '', tags: body.tags || [], addedAt: new Date().toISOString() })
|
|
404
|
+
saveSnippets(list)
|
|
405
|
+
return ok(res, { ok: true, snippets: list })
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const snippetMatch = path.match(/^\/ssh\/snippets\/([^/]+)$/)
|
|
409
|
+
if (snippetMatch) {
|
|
410
|
+
const sName = decodeURIComponent(snippetMatch[1])
|
|
411
|
+
if (method === 'DELETE') {
|
|
412
|
+
const list = loadSnippets()
|
|
413
|
+
const idx = list.findIndex(s => s.name === sName)
|
|
414
|
+
if (idx === -1) return err(res, 404, `片段 ${sName} 不存在`)
|
|
415
|
+
list.splice(idx, 1)
|
|
416
|
+
saveSnippets(list)
|
|
417
|
+
return ok(res, { ok: true, snippets: list })
|
|
418
|
+
}
|
|
419
|
+
if (method === 'PUT') {
|
|
420
|
+
const body = await jsonBody(req)
|
|
421
|
+
const list = loadSnippets()
|
|
422
|
+
const s = list.find(s => s.name === sName)
|
|
423
|
+
if (!s) return err(res, 404, `片段 ${sName} 不存在`)
|
|
424
|
+
if (body.command !== undefined) s.command = body.command
|
|
425
|
+
if (body.description !== undefined) s.description = body.description
|
|
426
|
+
if (body.tags !== undefined) s.tags = body.tags
|
|
427
|
+
saveSnippets(list)
|
|
428
|
+
return ok(res, { ok: true, snippets: list })
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const snippetExecMatch = path.match(/^\/ssh\/snippets\/([^/]+)\/exec$/)
|
|
433
|
+
if (method === 'POST' && snippetExecMatch) {
|
|
434
|
+
const sName = decodeURIComponent(snippetExecMatch[1])
|
|
435
|
+
const body = await jsonBody(req)
|
|
436
|
+
const list = loadSnippets()
|
|
437
|
+
const s = list.find(s => s.name === sName)
|
|
438
|
+
if (!s) return err(res, 404, `片段 ${sName} 不存在`)
|
|
439
|
+
const h = findHost(body.host)
|
|
440
|
+
if (!h) return err(res, 404, `未找到主机 ${body.host}`)
|
|
441
|
+
const command = substituteVars(s.command, {
|
|
442
|
+
hostName: h.name, hostname: h.hostname,
|
|
443
|
+
user: h.user, port: h.port,
|
|
444
|
+
vars: body.vars || {},
|
|
445
|
+
})
|
|
446
|
+
const r = await sshExec(h, command, { timeout: (body.timeout || 60) * 1000 })
|
|
447
|
+
return ok(res, { ok: r.code === 0, code: r.code, command, stdout: trimOutput(r.stdout, 8000), stderr: trimOutput(r.stderr, 4000) })
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (method === 'POST' && path === '/ssh/snippets/vars') {
|
|
451
|
+
const body = await jsonBody(req)
|
|
452
|
+
return ok(res, { vars: extractVars(body.template || '') })
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// ───── SSH Keys ─────
|
|
456
|
+
if (method === 'GET' && path === '/ssh/keys') {
|
|
457
|
+
const keys = await listKeys()
|
|
458
|
+
return ok(res, keys)
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
if (method === 'POST' && path === '/ssh/keys/generate') {
|
|
462
|
+
const body = await jsonBody(req)
|
|
463
|
+
const r = await generateKey({ type: body.type, bits: body.bits, comment: body.comment, path: body.path })
|
|
464
|
+
if (!r.ok) return err(res, 400, r.error)
|
|
465
|
+
return ok(res, r)
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const keyMatch = path.match(/^\/ssh\/keys\/([^/]+)$/)
|
|
469
|
+
if (method === 'DELETE' && keyMatch) {
|
|
470
|
+
const r = deleteKey(decodeURIComponent(keyMatch[1]))
|
|
471
|
+
if (!r.ok) return err(res, 400, r.error)
|
|
472
|
+
return ok(res, { ok: true, deleted: r.deleted })
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// ───── SSH Tunnels ─────
|
|
476
|
+
if (method === 'GET' && path === '/ssh/tunnels') {
|
|
477
|
+
return ok(res, listTunnels())
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
if (method === 'POST' && path === '/ssh/tunnels') {
|
|
481
|
+
const body = await jsonBody(req)
|
|
482
|
+
if (!body.host || !body.type || !body.localPort) return err(res, 400, 'host, type, localPort 必填')
|
|
483
|
+
const r = createTunnel({ hostName: body.host, type: body.type, localPort: body.localPort, remoteHost: body.remoteHost, remotePort: body.remotePort })
|
|
484
|
+
if (!r.ok) return err(res, 400, r.error)
|
|
485
|
+
return ok(res, r)
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
const tunnelMatch = path.match(/^\/ssh\/tunnels\/([^/]+)$/)
|
|
489
|
+
if (method === 'DELETE' && tunnelMatch) {
|
|
490
|
+
const r = closeTunnel(decodeURIComponent(tunnelMatch[1]))
|
|
491
|
+
if (!r.ok) return err(res, 400, r.error)
|
|
492
|
+
return ok(res, { ok: true, tunnels: listTunnels() })
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// ───── SSH File Operations ─────
|
|
496
|
+
if (method === 'POST' && path === '/ssh/file/mkdir') {
|
|
497
|
+
const body = await jsonBody(req)
|
|
498
|
+
const h = findHost(body.host)
|
|
499
|
+
if (!h) return err(res, 404, `未找到主机 ${body.host}`)
|
|
500
|
+
const r = await sshExec(h, `mkdir -p ${JSON.stringify(body.path)}`, { timeout: 15000 })
|
|
501
|
+
return ok(res, { ok: r.code === 0, stderr: r.stderr })
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
if (method === 'POST' && path === '/ssh/file/delete') {
|
|
505
|
+
const body = await jsonBody(req)
|
|
506
|
+
const h = findHost(body.host)
|
|
507
|
+
if (!h) return err(res, 404, `未找到主机 ${body.host}`)
|
|
508
|
+
const target_path = body.path
|
|
509
|
+
if (!target_path || target_path === '/' || target_path === '~') return err(res, 400, '不允许删除根目录')
|
|
510
|
+
const flag = body.recursive ? '-rf' : '-f'
|
|
511
|
+
const r = await sshExec(h, `rm ${flag} ${JSON.stringify(target_path)}`, { timeout: 15000 })
|
|
512
|
+
return ok(res, { ok: r.code === 0, stderr: r.stderr })
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
if (method === 'POST' && path === '/ssh/file/write') {
|
|
516
|
+
const body = await jsonBody(req)
|
|
517
|
+
const h = findHost(body.host)
|
|
518
|
+
if (!h) return err(res, 404, `未找到主机 ${body.host}`)
|
|
519
|
+
const r = await sshExec(h, `cat > ${JSON.stringify(body.path)} << 'DSHEOF'\n${body.content}\nDSHEOF`, { timeout: 30000 })
|
|
520
|
+
return ok(res, { ok: r.code === 0, stderr: r.stderr })
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// ───── K8s helper ─────
|
|
524
|
+
function kArgs(ctxName, extra = []) {
|
|
525
|
+
const c = findContext(ctxName)
|
|
526
|
+
return c ? buildKubectlArgs(c, extra) : ['--context', ctxName, ...extra]
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
if (method === 'POST' && path === '/k8s/browse-local') {
|
|
530
|
+
const body = await jsonBody(req)
|
|
531
|
+
let dir = body.path || join(homedir(), '.kube')
|
|
532
|
+
dir = dir.replace(/^~/, homedir())
|
|
533
|
+
try {
|
|
534
|
+
const st = statSync(dir)
|
|
535
|
+
if (!st.isDirectory()) return ok(res, { ok: true, isFile: true, path: dir })
|
|
536
|
+
} catch { return err(res, 400, '路径不存在: ' + dir) }
|
|
537
|
+
try {
|
|
538
|
+
const entries = readdirSync(dir, { withFileTypes: true }).map(e => ({
|
|
539
|
+
name: e.name, isDir: e.isDirectory(),
|
|
540
|
+
path: join(dir, e.name),
|
|
541
|
+
})).filter(e => !e.name.startsWith('.') || body.showHidden).sort((a, b) => (b.isDir - a.isDir) || a.name.localeCompare(b.name))
|
|
542
|
+
return ok(res, { ok: true, dir, entries, parent: join(dir, '..') })
|
|
543
|
+
} catch (e) { return err(res, 400, '无法读取目录: ' + e.message) }
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// ───── K8s Contexts ─────
|
|
547
|
+
if (method === 'GET' && path === '/k8s/contexts') {
|
|
548
|
+
return ok(res, loadContexts())
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
if (method === 'POST' && path === '/k8s/contexts') {
|
|
552
|
+
const body = await jsonBody(req)
|
|
553
|
+
const r = addContext(body)
|
|
554
|
+
if (!r.ok) return err(res, 400, r.why)
|
|
555
|
+
return ok(res, { ok: true, contexts: loadContexts() })
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const ctxMatch = path.match(/^\/k8s\/contexts\/([^/]+)$/)
|
|
559
|
+
if (method === 'DELETE' && ctxMatch) {
|
|
560
|
+
const r = removeContext(decodeURIComponent(ctxMatch[1]))
|
|
561
|
+
if (!r.ok) return err(res, 400, r.why)
|
|
562
|
+
return ok(res, { ok: true, contexts: loadContexts() })
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
if (method === 'POST' && path === '/k8s/parse-kubeconfig') {
|
|
566
|
+
const body = await jsonBody(req)
|
|
567
|
+
const input = body.content || body.path || ''
|
|
568
|
+
if (!input) return err(res, 400, '请提供 kubeconfig 路径或内容')
|
|
569
|
+
const r = await parseKubeconfig(input)
|
|
570
|
+
if (!r.ok) return err(res, 400, r.error)
|
|
571
|
+
return ok(res, r)
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
if (method === 'POST' && path === '/k8s/import-contexts') {
|
|
575
|
+
const body = await jsonBody(req)
|
|
576
|
+
if (!body.selected?.length) return err(res, 400, '请选择至少一个上下文')
|
|
577
|
+
const input = body.content || body.path || ''
|
|
578
|
+
const parsed = await parseKubeconfig(input)
|
|
579
|
+
if (!parsed.ok) return err(res, 400, parsed.error)
|
|
580
|
+
const results = importContexts(parsed, body.selected, body.path || undefined)
|
|
581
|
+
return ok(res, { ok: true, results, contexts: loadContexts() })
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
const ctxTestMatch = path.match(/^\/k8s\/contexts\/([^/]+)\/test$/)
|
|
585
|
+
if (method === 'POST' && ctxTestMatch) {
|
|
586
|
+
const name = decodeURIComponent(ctxTestMatch[1])
|
|
587
|
+
const args = kArgs(name, ['cluster-info'])
|
|
588
|
+
const r = await exec('kubectl', args, { timeout: 10000 })
|
|
589
|
+
return ok(res, { ok: r.code === 0, output: r.code === 0 ? r.stdout.split('\n').slice(0, 3).join('\n') : r.stderr })
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// ───── K8s Overview ─────
|
|
593
|
+
if (method === 'POST' && path === '/k8s/overview') {
|
|
594
|
+
const body = await jsonBody(req)
|
|
595
|
+
const base = kArgs(body.context)
|
|
596
|
+
const [nodesR, podsR, deploysR, nsR, evtsR, verR] = await Promise.all([
|
|
597
|
+
exec('kubectl', [...base, 'get', 'nodes', '-o', 'json'], { timeout: 15000 }),
|
|
598
|
+
exec('kubectl', [...base, 'get', 'pods', '-A', '-o', 'json', '--field-selector=status.phase!=Succeeded'], { timeout: 15000 }),
|
|
599
|
+
exec('kubectl', [...base, 'get', 'deployments', '-A', '-o', 'json'], { timeout: 15000 }),
|
|
600
|
+
exec('kubectl', [...base, 'get', 'namespaces', '-o', 'json'], { timeout: 10000 }),
|
|
601
|
+
exec('kubectl', [...base, 'get', 'events', '-A', '--field-selector=type=Warning', '--sort-by=.lastTimestamp', '-o', 'json'], { timeout: 10000 }),
|
|
602
|
+
exec('kubectl', [...base, 'version', '-o', 'json'], { timeout: 10000 }),
|
|
603
|
+
])
|
|
604
|
+
const parseItems = (r) => { try { return JSON.parse(r.stdout)?.items || [] } catch { return [] } }
|
|
605
|
+
const nodes = parseItems(nodesR)
|
|
606
|
+
const pods = parseItems(podsR)
|
|
607
|
+
const deploys = parseItems(deploysR)
|
|
608
|
+
const nsList = parseItems(nsR).map(n => n.metadata?.name).filter(Boolean)
|
|
609
|
+
const events = parseItems(evtsR).slice(0, 20).map(e => ({
|
|
610
|
+
type: e.type, reason: e.reason, message: e.message,
|
|
611
|
+
object: `${e.involvedObject?.kind}/${e.involvedObject?.name}`,
|
|
612
|
+
lastTimestamp: e.lastTimestamp || e.eventTime,
|
|
613
|
+
count: e.count || 1,
|
|
614
|
+
}))
|
|
615
|
+
let version = {}
|
|
616
|
+
try { version = JSON.parse(verR.stdout) } catch {}
|
|
617
|
+
return ok(res, {
|
|
618
|
+
ok: true,
|
|
619
|
+
nodes: { total: nodes.length, ready: nodes.filter(n => n.status?.conditions?.find(c => c.type === 'Ready' && c.status === 'True')).length },
|
|
620
|
+
pods: {
|
|
621
|
+
total: pods.length,
|
|
622
|
+
running: pods.filter(p => p.status?.phase === 'Running').length,
|
|
623
|
+
pending: pods.filter(p => p.status?.phase === 'Pending').length,
|
|
624
|
+
failed: pods.filter(p => p.status?.phase === 'Failed').length,
|
|
625
|
+
},
|
|
626
|
+
deployments: {
|
|
627
|
+
total: deploys.length,
|
|
628
|
+
available: deploys.filter(d => (d.status?.availableReplicas || 0) >= (d.spec?.replicas || 1)).length,
|
|
629
|
+
},
|
|
630
|
+
namespaces: nsList,
|
|
631
|
+
events,
|
|
632
|
+
version: { server: version.serverVersion?.gitVersion || '', platform: version.serverVersion?.platform || '' },
|
|
633
|
+
})
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// ───── K8s Resources ─────
|
|
637
|
+
if (method === 'POST' && path === '/k8s/resources') {
|
|
638
|
+
const body = await jsonBody(req)
|
|
639
|
+
const args = kArgs(body.context, ['get', body.kind])
|
|
640
|
+
if (body.name) args.push(body.name)
|
|
641
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
642
|
+
else if (body.all_namespaces) args.push('--all-namespaces')
|
|
643
|
+
if (body.label_selector) args.push('-l', body.label_selector)
|
|
644
|
+
args.push('-o', body.name ? 'yaml' : 'json')
|
|
645
|
+
const r = await exec('kubectl', args, { timeout: 15000 })
|
|
646
|
+
if (body.name) return ok(res, { ok: r.code === 0, output: trimOutput(r.stdout, 30000), stderr: r.stderr })
|
|
647
|
+
let items = []
|
|
648
|
+
try { items = JSON.parse(r.stdout)?.items || [] } catch {}
|
|
649
|
+
return ok(res, { ok: r.code === 0, items, stderr: r.stderr })
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
if (method === 'POST' && path === '/k8s/describe') {
|
|
653
|
+
const body = await jsonBody(req)
|
|
654
|
+
const args = kArgs(body.context, ['describe', body.kind, body.name])
|
|
655
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
656
|
+
const r = await exec('kubectl', args, { timeout: 15000 })
|
|
657
|
+
return ok(res, { ok: r.code === 0, output: trimOutput(r.stdout, 30000), stderr: r.stderr })
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
if (method === 'POST' && path === '/k8s/logs') {
|
|
661
|
+
const body = await jsonBody(req)
|
|
662
|
+
const args = kArgs(body.context, ['logs', body.pod])
|
|
663
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
664
|
+
if (body.container) args.push('-c', body.container)
|
|
665
|
+
if (body.previous) args.push('--previous')
|
|
666
|
+
args.push('--tail', String(body.tail || 200))
|
|
667
|
+
if (body.since) args.push('--since', body.since)
|
|
668
|
+
const r = await exec('kubectl', args, { timeout: 30000 })
|
|
669
|
+
return ok(res, { ok: r.code === 0, output: trimOutput(r.stdout, 50000), stderr: r.stderr })
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
if (method === 'POST' && path === '/k8s/events') {
|
|
673
|
+
const body = await jsonBody(req)
|
|
674
|
+
const args = kArgs(body.context, ['get', 'events', '--sort-by=.lastTimestamp', '-o', 'json'])
|
|
675
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
676
|
+
else if (body.all_namespaces) args.push('--all-namespaces')
|
|
677
|
+
if (body.type) args.push('--field-selector', `type=${body.type}`)
|
|
678
|
+
const r = await exec('kubectl', args, { timeout: 15000 })
|
|
679
|
+
let items = []
|
|
680
|
+
try { items = JSON.parse(r.stdout)?.items || [] } catch {}
|
|
681
|
+
return ok(res, { ok: r.code === 0, items: items.slice(0, 100).map(e => ({
|
|
682
|
+
type: e.type, reason: e.reason, message: e.message,
|
|
683
|
+
object: `${e.involvedObject?.kind}/${e.involvedObject?.name}`,
|
|
684
|
+
namespace: e.involvedObject?.namespace || '',
|
|
685
|
+
lastTimestamp: e.lastTimestamp || e.eventTime,
|
|
686
|
+
count: e.count || 1,
|
|
687
|
+
})), stderr: r.stderr })
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
if (method === 'POST' && path === '/k8s/exec') {
|
|
691
|
+
const body = await jsonBody(req)
|
|
692
|
+
const args = kArgs(body.context, ['exec', body.pod])
|
|
693
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
694
|
+
if (body.container) args.push('-c', body.container)
|
|
695
|
+
const shell = body.shell || 'sh'
|
|
696
|
+
args.push('--', shell, '-c', body.command)
|
|
697
|
+
const r = await exec('kubectl', args, { timeout: (body.timeout || 60) * 1000 })
|
|
698
|
+
return ok(res, { ok: r.code === 0, code: r.code, stdout: trimOutput(r.stdout, 8000), stderr: trimOutput(r.stderr, 4000) })
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
if (method === 'POST' && path === '/k8s/exec-terminal') {
|
|
702
|
+
const body = await jsonBody(req)
|
|
703
|
+
const ctx = findContext(body.context)
|
|
704
|
+
if (!ctx) return err(res, 404, '集群不存在')
|
|
705
|
+
const args = buildKubectlArgs(ctx, ['exec', '-it', body.pod])
|
|
706
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
707
|
+
if (body.container) args.push('-c', body.container)
|
|
708
|
+
const shell = body.shell || 'sh'
|
|
709
|
+
args.push('--', shell)
|
|
710
|
+
const cmd = `kubectl ${args.map(a => a.includes(' ') ? `"${a}"` : a).join(' ')}`
|
|
711
|
+
return ok(res, { ok: true, command: cmd })
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
if (method === 'POST' && path === '/k8s/top') {
|
|
715
|
+
const body = await jsonBody(req)
|
|
716
|
+
const args = kArgs(body.context, ['top', body.kind])
|
|
717
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
718
|
+
if (body.sort_by) args.push('--sort-by', body.sort_by)
|
|
719
|
+
const r = await exec('kubectl', args, { timeout: 15000 })
|
|
720
|
+
return ok(res, { ok: r.code === 0, output: trimOutput(r.stdout, 20000), stderr: r.stderr })
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
if (method === 'POST' && path === '/k8s/scale') {
|
|
724
|
+
const body = await jsonBody(req)
|
|
725
|
+
const args = kArgs(body.context, ['scale', `${body.kind}/${body.name}`, `--replicas=${body.replicas}`])
|
|
726
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
727
|
+
const r = await exec('kubectl', args, { timeout: 15000 })
|
|
728
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
if (method === 'POST' && path === '/k8s/rollout') {
|
|
732
|
+
const body = await jsonBody(req)
|
|
733
|
+
const args = kArgs(body.context, ['rollout', body.action, `${body.kind}/${body.name}`])
|
|
734
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
735
|
+
if (body.action === 'undo' && body.to_revision) args.push(`--to-revision=${body.to_revision}`)
|
|
736
|
+
const r = await exec('kubectl', args, { timeout: 30000 })
|
|
737
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
if (method === 'POST' && path === '/k8s/delete-resource') {
|
|
741
|
+
const body = await jsonBody(req)
|
|
742
|
+
const args = kArgs(body.context, ['delete', body.kind, body.name])
|
|
743
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
744
|
+
const r = await exec('kubectl', args, { timeout: 30000 })
|
|
745
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
if (method === 'POST' && path === '/k8s/apply') {
|
|
749
|
+
const body = await jsonBody(req)
|
|
750
|
+
const args = kArgs(body.context, ['apply', '-f', '-'])
|
|
751
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
752
|
+
if (body.dry_run) args.push('--dry-run=server')
|
|
753
|
+
const r = await exec('kubectl', args, { timeout: 30000, stdin: body.manifest })
|
|
754
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// ───── Helm ─────
|
|
758
|
+
function helmArgs(ctxName, extra = []) {
|
|
759
|
+
const c = findContext(ctxName)
|
|
760
|
+
if (!c) return ['--kube-context', ctxName, ...extra]
|
|
761
|
+
const args = []
|
|
762
|
+
const src = c.source || 'kubeconfig'
|
|
763
|
+
if (src === 'kubeconfig') {
|
|
764
|
+
if (c.kubeconfig) args.push('--kubeconfig', c.kubeconfig)
|
|
765
|
+
if (c.context) args.push('--kube-context', c.context)
|
|
766
|
+
} else {
|
|
767
|
+
const cDir = join(dataDir(), 'k8s', 'creds', c.name)
|
|
768
|
+
if (c.server) {
|
|
769
|
+
args.push('--kube-apiserver', c.server)
|
|
770
|
+
const caFile = join(cDir, 'ca.pem')
|
|
771
|
+
if (existsSync(caFile)) args.push('--kube-ca-file', caFile)
|
|
772
|
+
if (src === 'token') {
|
|
773
|
+
const tokenFile = join(cDir, 'token')
|
|
774
|
+
if (existsSync(tokenFile)) args.push('--kube-token', readFileSync(tokenFile, 'utf8').trim())
|
|
775
|
+
else args.push('--kube-insecure-skip-tls-verify')
|
|
776
|
+
} else if (src === 'cert') {
|
|
777
|
+
const certFile = join(cDir, 'client.pem')
|
|
778
|
+
const keyFile = join(cDir, 'client-key.pem')
|
|
779
|
+
if (existsSync(certFile)) args.push('--kube-tls-serverName', c.server.replace(/^https?:\/\//, '').replace(/:\d+$/, ''))
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
args.push(...extra)
|
|
784
|
+
return args
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
if (method === 'POST' && path === '/helm/list') {
|
|
788
|
+
const body = await jsonBody(req)
|
|
789
|
+
const args = helmArgs(body.context, ['list', '--output', 'json'])
|
|
790
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
791
|
+
else args.push('--all-namespaces')
|
|
792
|
+
const r = await exec('helm', args, { timeout: 30000 })
|
|
793
|
+
if (r.code !== 0) return ok(res, { ok: false, items: [], stderr: r.stderr })
|
|
794
|
+
try { return ok(res, { ok: true, items: JSON.parse(r.stdout || '[]') }) }
|
|
795
|
+
catch { return ok(res, { ok: true, items: [], output: r.stdout }) }
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
if (method === 'POST' && path === '/helm/status') {
|
|
799
|
+
const body = await jsonBody(req)
|
|
800
|
+
const args = helmArgs(body.context, ['status', body.release, '--output', 'json'])
|
|
801
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
802
|
+
const r = await exec('helm', args, { timeout: 15000 })
|
|
803
|
+
if (r.code !== 0) return ok(res, { ok: false, output: r.stderr })
|
|
804
|
+
try { return ok(res, { ok: true, data: JSON.parse(r.stdout) }) }
|
|
805
|
+
catch { return ok(res, { ok: true, output: r.stdout }) }
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
if (method === 'POST' && path === '/helm/values') {
|
|
809
|
+
const body = await jsonBody(req)
|
|
810
|
+
const args = helmArgs(body.context, ['get', 'values', body.release, '--output', 'yaml'])
|
|
811
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
812
|
+
if (body.all) args.push('--all')
|
|
813
|
+
const r = await exec('helm', args, { timeout: 15000 })
|
|
814
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
if (method === 'POST' && path === '/helm/history') {
|
|
818
|
+
const body = await jsonBody(req)
|
|
819
|
+
const args = helmArgs(body.context, ['history', body.release, '--output', 'json'])
|
|
820
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
821
|
+
const r = await exec('helm', args, { timeout: 15000 })
|
|
822
|
+
if (r.code !== 0) return ok(res, { ok: false, items: [], stderr: r.stderr })
|
|
823
|
+
try { return ok(res, { ok: true, items: JSON.parse(r.stdout || '[]') }) }
|
|
824
|
+
catch { return ok(res, { ok: true, items: [], output: r.stdout }) }
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
if (method === 'POST' && path === '/helm/install') {
|
|
828
|
+
const body = await jsonBody(req)
|
|
829
|
+
const args = helmArgs(body.context, ['install', body.release, body.chart])
|
|
830
|
+
if (body.namespace) args.push('-n', body.namespace, '--create-namespace')
|
|
831
|
+
if (body.version) args.push('--version', body.version)
|
|
832
|
+
if (body.values) args.push('--values', '-')
|
|
833
|
+
if (body.dry_run) args.push('--dry-run')
|
|
834
|
+
const r = await exec('helm', args, { timeout: 120000, stdin: body.values || undefined })
|
|
835
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
if (method === 'POST' && path === '/helm/upgrade') {
|
|
839
|
+
const body = await jsonBody(req)
|
|
840
|
+
const args = helmArgs(body.context, ['upgrade', body.release, body.chart])
|
|
841
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
842
|
+
if (body.version) args.push('--version', body.version)
|
|
843
|
+
if (body.values) args.push('--values', '-')
|
|
844
|
+
if (body.dry_run) args.push('--dry-run')
|
|
845
|
+
if (body.reuse_values) args.push('--reuse-values')
|
|
846
|
+
const r = await exec('helm', args, { timeout: 120000, stdin: body.values || undefined })
|
|
847
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
if (method === 'POST' && path === '/helm/uninstall') {
|
|
851
|
+
const body = await jsonBody(req)
|
|
852
|
+
const args = helmArgs(body.context, ['uninstall', body.release])
|
|
853
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
854
|
+
if (body.dry_run) args.push('--dry-run')
|
|
855
|
+
const r = await exec('helm', args, { timeout: 60000 })
|
|
856
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
if (method === 'POST' && path === '/helm/search') {
|
|
860
|
+
const body = await jsonBody(req)
|
|
861
|
+
const args = ['search', body.source || 'repo', body.keyword || '', '--output', 'json']
|
|
862
|
+
if (body.version) args.push('--version', body.version)
|
|
863
|
+
if (body.versions) args.push('--versions')
|
|
864
|
+
if (body.devel) args.push('--devel')
|
|
865
|
+
const r = await exec('helm', args, { timeout: 30000 })
|
|
866
|
+
if (r.code !== 0) return ok(res, { ok: false, items: [], stderr: r.stderr })
|
|
867
|
+
try { return ok(res, { ok: true, items: JSON.parse(r.stdout || '[]') }) }
|
|
868
|
+
catch { return ok(res, { ok: true, items: [], output: r.stdout }) }
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
if (method === 'POST' && path === '/helm/show') {
|
|
872
|
+
const body = await jsonBody(req)
|
|
873
|
+
const sub = body.sub || 'chart'
|
|
874
|
+
const args = ['show', sub, body.chart]
|
|
875
|
+
if (body.version) args.push('--version', body.version)
|
|
876
|
+
const r = await exec('helm', args, { timeout: 30000 })
|
|
877
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
if (method === 'POST' && path === '/helm/repo-list') {
|
|
881
|
+
const r = await exec('helm', ['repo', 'list', '--output', 'json'], { timeout: 15000 })
|
|
882
|
+
if (r.code !== 0) return ok(res, { ok: false, items: [], stderr: r.stderr })
|
|
883
|
+
try { return ok(res, { ok: true, items: JSON.parse(r.stdout || '[]') }) }
|
|
884
|
+
catch { return ok(res, { ok: true, items: [], output: r.stdout }) }
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
if (method === 'POST' && path === '/helm/repo-add') {
|
|
888
|
+
const body = await jsonBody(req)
|
|
889
|
+
const args = ['repo', 'add', body.name, body.url]
|
|
890
|
+
if (body.force_update) args.push('--force-update')
|
|
891
|
+
const r = await exec('helm', args, { timeout: 30000 })
|
|
892
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
if (method === 'POST' && path === '/helm/repo-remove') {
|
|
896
|
+
const body = await jsonBody(req)
|
|
897
|
+
const r = await exec('helm', ['repo', 'remove', body.name], { timeout: 15000 })
|
|
898
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
if (method === 'POST' && path === '/helm/repo-update') {
|
|
902
|
+
const body = await jsonBody(req)
|
|
903
|
+
const args = ['repo', 'update']
|
|
904
|
+
if (body.name) args.push(body.name)
|
|
905
|
+
const r = await exec('helm', args, { timeout: 60000 })
|
|
906
|
+
return ok(res, { ok: r.code === 0, output: r.stdout || r.stderr })
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
// ───── Argo CD Instances ─────
|
|
910
|
+
if (method === 'GET' && path === '/argocd/instances') {
|
|
911
|
+
return ok(res, argocdInst.loadInstances())
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
if (method === 'POST' && path === '/argocd/instances') {
|
|
915
|
+
const body = await jsonBody(req)
|
|
916
|
+
const r = argocdInst.addInstance(body)
|
|
917
|
+
if (!r.ok) return err(res, 400, r.why)
|
|
918
|
+
return ok(res, { ok: true, instances: argocdInst.loadInstances() })
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
const acdInstMatch = path.match(/^\/argocd\/instances\/([^/]+)$/)
|
|
922
|
+
if (method === 'DELETE' && acdInstMatch) {
|
|
923
|
+
const r = argocdInst.removeInstance(decodeURIComponent(acdInstMatch[1]))
|
|
924
|
+
if (!r.ok) return err(res, 400, r.why)
|
|
925
|
+
return ok(res, { ok: true, instances: argocdInst.loadInstances() })
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
// ───── Argo CD Apps ─────
|
|
929
|
+
if (method === 'POST' && path === '/argocd/apps') {
|
|
930
|
+
const body = await jsonBody(req)
|
|
931
|
+
const inst = argocdInst.findInstance(body.instance)
|
|
932
|
+
if (!inst) return err(res, 404, `实例 ${body.instance} 不存在`)
|
|
933
|
+
const args = argocdInst.buildArgocdArgs(inst, ['app', 'list', '-o', 'json'])
|
|
934
|
+
if (body.project) args.push('-p', body.project)
|
|
935
|
+
if (body.selector) args.push('-l', body.selector)
|
|
936
|
+
const r = await exec('argocd', args, { timeout: 15000 })
|
|
937
|
+
if (r.code !== 0) return ok(res, { ok: false, error: r.stderr || `exit ${r.code}` })
|
|
938
|
+
try { return ok(res, { ok: true, apps: JSON.parse(r.stdout) }) }
|
|
939
|
+
catch { return ok(res, { ok: true, raw: trimOutput(r.stdout, 20000) }) }
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
if (method === 'POST' && path === '/argocd/app') {
|
|
943
|
+
const body = await jsonBody(req)
|
|
944
|
+
const inst = argocdInst.findInstance(body.instance)
|
|
945
|
+
if (!inst) return err(res, 404, `实例 ${body.instance} 不存在`)
|
|
946
|
+
const args = argocdInst.buildArgocdArgs(inst, ['app', 'get', body.app, '-o', 'json'])
|
|
947
|
+
const r = await exec('argocd', args, { timeout: 15000 })
|
|
948
|
+
if (r.code !== 0) return ok(res, { ok: false, error: r.stderr || `exit ${r.code}` })
|
|
949
|
+
try { return ok(res, { ok: true, app: JSON.parse(r.stdout) }) }
|
|
950
|
+
catch { return ok(res, { ok: true, raw: trimOutput(r.stdout, 20000) }) }
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
if (method === 'POST' && path === '/argocd/sync') {
|
|
954
|
+
const body = await jsonBody(req)
|
|
955
|
+
const inst = argocdInst.findInstance(body.instance)
|
|
956
|
+
if (!inst) return err(res, 404, `实例 ${body.instance} 不存在`)
|
|
957
|
+
const args = argocdInst.buildArgocdArgs(inst, ['app', 'sync', body.app])
|
|
958
|
+
if (body.dry_run !== false) args.push('--dry-run')
|
|
959
|
+
if (body.prune) args.push('--prune')
|
|
960
|
+
if (body.revision) args.push('--revision', body.revision)
|
|
961
|
+
const r = await exec('argocd', args, { timeout: 60000 })
|
|
962
|
+
return ok(res, { ok: r.code === 0, output: trimOutput(r.stdout, 20000), stderr: r.stderr })
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
if (method === 'POST' && path === '/argocd/diagnose') {
|
|
966
|
+
const body = await jsonBody(req)
|
|
967
|
+
const inst = argocdInst.findInstance(body.instance)
|
|
968
|
+
if (!inst) return err(res, 404, `实例 ${body.instance} 不存在`)
|
|
969
|
+
const getArgs = argocdInst.buildArgocdArgs(inst, ['app', 'get', body.app])
|
|
970
|
+
const diffArgs = argocdInst.buildArgocdArgs(inst, ['app', 'diff', body.app])
|
|
971
|
+
const [rGet, rDiff] = await Promise.all([
|
|
972
|
+
exec('argocd', getArgs, { timeout: 15000 }),
|
|
973
|
+
exec('argocd', diffArgs, { timeout: 15000 }),
|
|
974
|
+
])
|
|
975
|
+
return ok(res, {
|
|
976
|
+
ok: true,
|
|
977
|
+
get: trimOutput(rGet.stdout, 10000),
|
|
978
|
+
diff: trimOutput(rDiff.stdout, 10000),
|
|
979
|
+
stderr: [rGet.stderr, rDiff.stderr].filter(Boolean).join('\n'),
|
|
980
|
+
})
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
// ───── Argo Workflows Instances ─────
|
|
984
|
+
if (method === 'GET' && path === '/argowf/instances') {
|
|
985
|
+
return ok(res, argowfInst.loadInstances())
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
if (method === 'POST' && path === '/argowf/instances') {
|
|
989
|
+
const body = await jsonBody(req)
|
|
990
|
+
const r = argowfInst.addInstance(body)
|
|
991
|
+
if (!r.ok) return err(res, 400, r.why)
|
|
992
|
+
return ok(res, { ok: true, instances: argowfInst.loadInstances() })
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
const awfInstMatch = path.match(/^\/argowf\/instances\/([^/]+)$/)
|
|
996
|
+
if (method === 'DELETE' && awfInstMatch) {
|
|
997
|
+
const r = argowfInst.removeInstance(decodeURIComponent(awfInstMatch[1]))
|
|
998
|
+
if (!r.ok) return err(res, 400, r.why)
|
|
999
|
+
return ok(res, { ok: true, instances: argowfInst.loadInstances() })
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
// ───── Argo Workflows ─────
|
|
1003
|
+
if (method === 'POST' && path === '/argowf/list') {
|
|
1004
|
+
const body = await jsonBody(req)
|
|
1005
|
+
const inst = argowfInst.findInstance(body.instance)
|
|
1006
|
+
if (!inst) return err(res, 404, `实例 ${body.instance} 不存在`)
|
|
1007
|
+
const args = argowfInst.buildArgoArgs(inst, ['list', '-o', 'json'])
|
|
1008
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
1009
|
+
if (body.status) args.push('--status', body.status)
|
|
1010
|
+
if (body.label_selector) args.push('-l', body.label_selector)
|
|
1011
|
+
args.push('--chunk-size', String(body.limit || 50))
|
|
1012
|
+
const r = await exec('argo', args, { timeout: 15000 })
|
|
1013
|
+
if (r.code !== 0) return ok(res, { ok: false, error: r.stderr || `exit ${r.code}` })
|
|
1014
|
+
try { return ok(res, { ok: true, workflows: JSON.parse(r.stdout) }) }
|
|
1015
|
+
catch { return ok(res, { ok: true, raw: trimOutput(r.stdout, 20000) }) }
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
if (method === 'POST' && path === '/argowf/get') {
|
|
1019
|
+
const body = await jsonBody(req)
|
|
1020
|
+
const inst = argowfInst.findInstance(body.instance)
|
|
1021
|
+
if (!inst) return err(res, 404, `实例 ${body.instance} 不存在`)
|
|
1022
|
+
const args = argowfInst.buildArgoArgs(inst, ['get', body.name, '-o', 'json'])
|
|
1023
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
1024
|
+
const r = await exec('argo', args, { timeout: 15000 })
|
|
1025
|
+
if (r.code !== 0) return ok(res, { ok: false, error: r.stderr || `exit ${r.code}` })
|
|
1026
|
+
try { return ok(res, { ok: true, workflow: JSON.parse(r.stdout) }) }
|
|
1027
|
+
catch { return ok(res, { ok: true, raw: trimOutput(r.stdout, 20000) }) }
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
if (method === 'POST' && path === '/argowf/submit') {
|
|
1031
|
+
const body = await jsonBody(req)
|
|
1032
|
+
const inst = argowfInst.findInstance(body.instance)
|
|
1033
|
+
if (!inst) return err(res, 404, `实例 ${body.instance} 不存在`)
|
|
1034
|
+
const args = argowfInst.buildArgoArgs(inst, ['submit', '--from', `wftmpl/${body.template}`])
|
|
1035
|
+
if (body.namespace) args.push('-n', body.namespace)
|
|
1036
|
+
if (body.dry_run) args.push('--dry-run')
|
|
1037
|
+
if (body.parameters && typeof body.parameters === 'object') {
|
|
1038
|
+
for (const [k, v] of Object.entries(body.parameters)) {
|
|
1039
|
+
args.push('-p', `${k}=${v}`)
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
args.push('-o', 'json')
|
|
1043
|
+
const r = await exec('argo', args, { timeout: 30000 })
|
|
1044
|
+
if (r.code !== 0) return ok(res, { ok: false, error: r.stderr || `exit ${r.code}` })
|
|
1045
|
+
try { return ok(res, { ok: true, workflow: JSON.parse(r.stdout) }) }
|
|
1046
|
+
catch { return ok(res, { ok: true, raw: trimOutput(r.stdout, 20000) }) }
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
if (method === 'POST' && path === '/argowf/diagnose') {
|
|
1050
|
+
const body = await jsonBody(req)
|
|
1051
|
+
const inst = argowfInst.findInstance(body.instance)
|
|
1052
|
+
if (!inst) return err(res, 404, `实例 ${body.instance} 不存在`)
|
|
1053
|
+
const getArgs = argowfInst.buildArgoArgs(inst, ['get', body.name])
|
|
1054
|
+
if (body.namespace) getArgs.push('-n', body.namespace)
|
|
1055
|
+
const logArgs = argowfInst.buildArgoArgs(inst, ['logs', body.name, '--tail', '100'])
|
|
1056
|
+
if (body.namespace) logArgs.push('-n', body.namespace)
|
|
1057
|
+
const [rGet, rLog] = await Promise.all([
|
|
1058
|
+
exec('argo', getArgs, { timeout: 15000 }),
|
|
1059
|
+
exec('argo', logArgs, { timeout: 15000 }),
|
|
1060
|
+
])
|
|
1061
|
+
return ok(res, {
|
|
1062
|
+
ok: true,
|
|
1063
|
+
get: trimOutput(rGet.stdout, 10000),
|
|
1064
|
+
logs: trimOutput(rLog.stdout, 10000),
|
|
1065
|
+
stderr: [rGet.stderr, rLog.stderr].filter(Boolean).join('\n'),
|
|
1066
|
+
})
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
// ───── 404 ─────
|
|
1070
|
+
err(res, 404, 'not found')
|
|
1071
|
+
|
|
1072
|
+
} catch (e) {
|
|
1073
|
+
err(res, 500, String(e?.message || e))
|
|
1074
|
+
}
|
|
1075
|
+
},
|
|
1076
|
+
})
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
export { apply, inject, name }
|