@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/lib/k8s/mod.mjs
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import { exec, trimOutput } from '../cli.mjs'
|
|
2
|
+
import { loadContexts, findContext, addContext, removeContext, buildKubectlArgs } from './context.mjs'
|
|
3
|
+
|
|
4
|
+
export function registerK8sTools(ctx, defineTool, toolsSvc, config) {
|
|
5
|
+
const textOutput = {
|
|
6
|
+
schema: { type: 'object', properties: {}, additionalProperties: true },
|
|
7
|
+
render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
|
|
8
|
+
}
|
|
9
|
+
const register = (tool) => toolsSvc.register(defineTool(tool))
|
|
10
|
+
|
|
11
|
+
register({
|
|
12
|
+
name: 'ops_kube_get',
|
|
13
|
+
description: '列出或获取 Kubernetes 资源。不指定 name 时列出所有资源(表格),指定 name 时返回 YAML。',
|
|
14
|
+
parameters: {
|
|
15
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
16
|
+
kind: { type: 'string', description: '资源类型,如 pods、deployments、services', required: true },
|
|
17
|
+
name: { type: 'string', description: '资源名称(可选,不填则列出所有)' },
|
|
18
|
+
namespace: { type: 'string', description: '命名空间(可选)' },
|
|
19
|
+
all_namespaces: { type: 'boolean', description: '是否查看所有命名空间' },
|
|
20
|
+
label_selector: { type: 'string', description: '标签选择器,如 app=web' },
|
|
21
|
+
output: { type: 'string', description: '输出格式:wide / yaml / json(默认无,表格)' },
|
|
22
|
+
},
|
|
23
|
+
output: textOutput,
|
|
24
|
+
async execute(args) {
|
|
25
|
+
const c = findContext(args.context)
|
|
26
|
+
const kubectlArgs = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
27
|
+
kubectlArgs.push('get', args.kind)
|
|
28
|
+
if (args.name) kubectlArgs.push(args.name)
|
|
29
|
+
if (args.namespace) kubectlArgs.push('-n', args.namespace)
|
|
30
|
+
else if (c?.namespace) kubectlArgs.push('-n', c.namespace)
|
|
31
|
+
if (args.all_namespaces) kubectlArgs.push('-A')
|
|
32
|
+
if (args.label_selector) kubectlArgs.push('-l', args.label_selector)
|
|
33
|
+
if (args.name && !args.output) kubectlArgs.push('-o', 'yaml')
|
|
34
|
+
else if (args.output) kubectlArgs.push('-o', args.output)
|
|
35
|
+
const r = await exec('kubectl', kubectlArgs, { timeout: 30000 })
|
|
36
|
+
if (r.code !== 0) return { ok: false, text: `kubectl get 失败:${r.stderr || `exit ${r.code}`}` }
|
|
37
|
+
return { ok: true, text: trimOutput(r.stdout) }
|
|
38
|
+
},
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
register({
|
|
42
|
+
name: 'ops_kube_describe',
|
|
43
|
+
description: '显示 Kubernetes 资源的详细信息(条件、事件、容器状态等)。',
|
|
44
|
+
parameters: {
|
|
45
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
46
|
+
kind: { type: 'string', description: '资源类型', required: true },
|
|
47
|
+
name: { type: 'string', description: '资源名称', required: true },
|
|
48
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
49
|
+
},
|
|
50
|
+
output: textOutput,
|
|
51
|
+
async execute(args) {
|
|
52
|
+
const c = findContext(args.context)
|
|
53
|
+
const kubectlArgs = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
54
|
+
kubectlArgs.push('describe', args.kind, args.name)
|
|
55
|
+
if (args.namespace) kubectlArgs.push('-n', args.namespace)
|
|
56
|
+
else if (c?.namespace) kubectlArgs.push('-n', c.namespace)
|
|
57
|
+
const r = await exec('kubectl', kubectlArgs, { timeout: 30000 })
|
|
58
|
+
if (r.code !== 0) return { ok: false, text: `kubectl describe 失败:${r.stderr}` }
|
|
59
|
+
return { ok: true, text: trimOutput(r.stdout) }
|
|
60
|
+
},
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
register({
|
|
64
|
+
name: 'ops_kube_logs',
|
|
65
|
+
description: '查看 Pod 的日志。',
|
|
66
|
+
parameters: {
|
|
67
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
68
|
+
pod: { type: 'string', description: 'Pod 名称', required: true },
|
|
69
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
70
|
+
container: { type: 'string', description: '容器名(多容器 Pod 需要指定)' },
|
|
71
|
+
tail: { type: 'number', description: '显示最后 N 行,默认 200' },
|
|
72
|
+
previous: { type: 'boolean', description: '查看上一次(已崩溃)容器的日志' },
|
|
73
|
+
since: { type: 'string', description: '只显示多久以内的日志,如 10m、2h' },
|
|
74
|
+
},
|
|
75
|
+
output: textOutput,
|
|
76
|
+
async execute(args) {
|
|
77
|
+
const c = findContext(args.context)
|
|
78
|
+
const kubectlArgs = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
79
|
+
kubectlArgs.push('logs', args.pod)
|
|
80
|
+
if (args.namespace) kubectlArgs.push('-n', args.namespace)
|
|
81
|
+
else if (c?.namespace) kubectlArgs.push('-n', c.namespace)
|
|
82
|
+
if (args.container) kubectlArgs.push('-c', args.container)
|
|
83
|
+
kubectlArgs.push('--tail', String(args.tail || 200))
|
|
84
|
+
if (args.previous) kubectlArgs.push('--previous')
|
|
85
|
+
if (args.since) kubectlArgs.push(`--since=${args.since}`)
|
|
86
|
+
const r = await exec('kubectl', kubectlArgs, { timeout: 30000 })
|
|
87
|
+
if (r.code !== 0) return { ok: false, text: `kubectl logs 失败:${r.stderr}` }
|
|
88
|
+
return { ok: true, text: trimOutput(r.stdout) }
|
|
89
|
+
},
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
register({
|
|
93
|
+
name: 'ops_kube_exec',
|
|
94
|
+
description: '在容器内执行一条命令。',
|
|
95
|
+
parameters: {
|
|
96
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
97
|
+
pod: { type: 'string', description: 'Pod 名称', required: true },
|
|
98
|
+
command: { type: 'string', description: '要执行的命令', required: true },
|
|
99
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
100
|
+
container: { type: 'string', description: '容器名' },
|
|
101
|
+
timeout: { type: 'number', description: '超时秒数,默认 60' },
|
|
102
|
+
},
|
|
103
|
+
output: textOutput,
|
|
104
|
+
async execute(args) {
|
|
105
|
+
const c = findContext(args.context)
|
|
106
|
+
const kubectlArgs = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
107
|
+
kubectlArgs.push('exec', args.pod)
|
|
108
|
+
if (args.namespace) kubectlArgs.push('-n', args.namespace)
|
|
109
|
+
else if (c?.namespace) kubectlArgs.push('-n', c.namespace)
|
|
110
|
+
if (args.container) kubectlArgs.push('-c', args.container)
|
|
111
|
+
kubectlArgs.push('--', 'sh', '-c', args.command)
|
|
112
|
+
const r = await exec('kubectl', kubectlArgs, { timeout: (args.timeout || 60) * 1000 })
|
|
113
|
+
return {
|
|
114
|
+
ok: r.code === 0,
|
|
115
|
+
text: trimOutput(`[exit ${r.code}]\n${r.stdout}${r.stderr ? '\nstderr: ' + r.stderr : ''}`),
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
register({
|
|
121
|
+
name: 'ops_kube_apply',
|
|
122
|
+
description: '应用 YAML 清单到集群(默认 dry-run,需显式设 dry_run=false 才真正执行)。',
|
|
123
|
+
parameters: {
|
|
124
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
125
|
+
manifest: { type: 'string', description: 'YAML 清单内容', required: true },
|
|
126
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
127
|
+
dry_run: { type: 'boolean', description: '是否只做 dry-run(默认 true)' },
|
|
128
|
+
},
|
|
129
|
+
output: textOutput,
|
|
130
|
+
async execute(args) {
|
|
131
|
+
const c = findContext(args.context)
|
|
132
|
+
const kubectlArgs = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
133
|
+
kubectlArgs.push('apply', '-f', '-')
|
|
134
|
+
if (args.namespace) kubectlArgs.push('-n', args.namespace)
|
|
135
|
+
else if (c?.namespace) kubectlArgs.push('-n', c.namespace)
|
|
136
|
+
if (args.dry_run !== false) kubectlArgs.push('--dry-run=server')
|
|
137
|
+
kubectlArgs.push('--server-side')
|
|
138
|
+
const r = await exec('kubectl', kubectlArgs, { timeout: 30000, stdin: args.manifest })
|
|
139
|
+
const prefix = args.dry_run !== false ? '[dry-run] ' : ''
|
|
140
|
+
if (r.code !== 0) return { ok: false, text: `${prefix}kubectl apply 失败:${r.stderr}` }
|
|
141
|
+
return { ok: true, text: trimOutput(`${prefix}${r.stdout}`) }
|
|
142
|
+
},
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
register({
|
|
146
|
+
name: 'ops_kube_delete',
|
|
147
|
+
description: '删除一个 Kubernetes 资源。',
|
|
148
|
+
parameters: {
|
|
149
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
150
|
+
kind: { type: 'string', description: '资源类型', required: true },
|
|
151
|
+
name: { type: 'string', description: '资源名称', required: true },
|
|
152
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
153
|
+
},
|
|
154
|
+
output: textOutput,
|
|
155
|
+
async execute(args) {
|
|
156
|
+
const c = findContext(args.context)
|
|
157
|
+
const kubectlArgs = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
158
|
+
kubectlArgs.push('delete', args.kind, args.name)
|
|
159
|
+
if (args.namespace) kubectlArgs.push('-n', args.namespace)
|
|
160
|
+
else if (c?.namespace) kubectlArgs.push('-n', c.namespace)
|
|
161
|
+
const r = await exec('kubectl', kubectlArgs, { timeout: 30000 })
|
|
162
|
+
if (r.code !== 0) return { ok: false, text: `kubectl delete 失败:${r.stderr}` }
|
|
163
|
+
return { ok: true, text: r.stdout || `已删除 ${args.kind}/${args.name}` }
|
|
164
|
+
},
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
register({
|
|
168
|
+
name: 'ops_kube_scale',
|
|
169
|
+
description: '调整 Deployment/StatefulSet/ReplicaSet 的副本数。',
|
|
170
|
+
parameters: {
|
|
171
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
172
|
+
kind: { type: 'string', description: '资源类型(deployment/statefulset/replicaset)', required: true },
|
|
173
|
+
name: { type: 'string', description: '资源名称', required: true },
|
|
174
|
+
replicas: { type: 'number', description: '目标副本数', required: true },
|
|
175
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
176
|
+
},
|
|
177
|
+
output: textOutput,
|
|
178
|
+
async execute(args) {
|
|
179
|
+
const c = findContext(args.context)
|
|
180
|
+
const kubectlArgs = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
181
|
+
kubectlArgs.push('scale', `${args.kind}/${args.name}`, `--replicas=${args.replicas}`)
|
|
182
|
+
if (args.namespace) kubectlArgs.push('-n', args.namespace)
|
|
183
|
+
else if (c?.namespace) kubectlArgs.push('-n', c.namespace)
|
|
184
|
+
const r = await exec('kubectl', kubectlArgs, { timeout: 30000 })
|
|
185
|
+
if (r.code !== 0) return { ok: false, text: `kubectl scale 失败:${r.stderr}` }
|
|
186
|
+
return { ok: true, text: r.stdout || `已缩放 ${args.kind}/${args.name} → ${args.replicas}` }
|
|
187
|
+
},
|
|
188
|
+
})
|
|
189
|
+
|
|
190
|
+
register({
|
|
191
|
+
name: 'ops_kube_rollout',
|
|
192
|
+
description: '管理滚动更新:查看状态、重启、暂停、恢复、回滚。',
|
|
193
|
+
parameters: {
|
|
194
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
195
|
+
action: { type: 'string', enum: ['status', 'restart', 'pause', 'resume', 'undo'], description: '操作', required: true },
|
|
196
|
+
kind: { type: 'string', description: '资源类型(deployment/statefulset/daemonset)', required: true },
|
|
197
|
+
name: { type: 'string', description: '资源名称', required: true },
|
|
198
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
199
|
+
to_revision: { type: 'number', description: 'undo 时回滚到的版本号(可选)' },
|
|
200
|
+
},
|
|
201
|
+
output: textOutput,
|
|
202
|
+
async execute(args) {
|
|
203
|
+
const c = findContext(args.context)
|
|
204
|
+
const kubectlArgs = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
205
|
+
kubectlArgs.push('rollout', args.action, `${args.kind}/${args.name}`)
|
|
206
|
+
if (args.namespace) kubectlArgs.push('-n', args.namespace)
|
|
207
|
+
else if (c?.namespace) kubectlArgs.push('-n', c.namespace)
|
|
208
|
+
if (args.action === 'undo' && args.to_revision) {
|
|
209
|
+
kubectlArgs.push(`--to-revision=${args.to_revision}`)
|
|
210
|
+
}
|
|
211
|
+
const r = await exec('kubectl', kubectlArgs, { timeout: 60000 })
|
|
212
|
+
if (r.code !== 0) return { ok: false, text: `kubectl rollout ${args.action} 失败:${r.stderr}` }
|
|
213
|
+
return { ok: true, text: trimOutput(r.stdout) }
|
|
214
|
+
},
|
|
215
|
+
})
|
|
216
|
+
|
|
217
|
+
register({
|
|
218
|
+
name: 'ops_kube_events',
|
|
219
|
+
description: '查看集群事件(默认只看 Warning 类型的最近事件)。',
|
|
220
|
+
parameters: {
|
|
221
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
222
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
223
|
+
all_namespaces: { type: 'boolean', description: '查看所有命名空间' },
|
|
224
|
+
type: { type: 'string', enum: ['Warning', 'Normal'], description: '事件类型过滤' },
|
|
225
|
+
},
|
|
226
|
+
output: textOutput,
|
|
227
|
+
async execute(args) {
|
|
228
|
+
const c = findContext(args.context)
|
|
229
|
+
const kubectlArgs = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
230
|
+
kubectlArgs.push('get', 'events', '--sort-by=.lastTimestamp')
|
|
231
|
+
if (args.namespace) kubectlArgs.push('-n', args.namespace)
|
|
232
|
+
else if (c?.namespace && !args.all_namespaces) kubectlArgs.push('-n', c.namespace)
|
|
233
|
+
if (args.all_namespaces) kubectlArgs.push('-A')
|
|
234
|
+
if (args.type) kubectlArgs.push(`--field-selector=type=${args.type}`)
|
|
235
|
+
const r = await exec('kubectl', kubectlArgs, { timeout: 30000 })
|
|
236
|
+
if (r.code !== 0) return { ok: false, text: `kubectl get events 失败:${r.stderr}` }
|
|
237
|
+
return { ok: true, text: trimOutput(r.stdout) }
|
|
238
|
+
},
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
register({
|
|
242
|
+
name: 'ops_kube_top',
|
|
243
|
+
description: '查看 Pod 或 Node 的资源用量(需要 metrics-server)。',
|
|
244
|
+
parameters: {
|
|
245
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
246
|
+
kind: { type: 'string', enum: ['pods', 'nodes'], description: 'pods 或 nodes', required: true },
|
|
247
|
+
namespace: { type: 'string', description: '命名空间(仅 pods)' },
|
|
248
|
+
sort_by: { type: 'string', enum: ['cpu', 'memory'], description: '排序方式' },
|
|
249
|
+
},
|
|
250
|
+
output: textOutput,
|
|
251
|
+
async execute(args) {
|
|
252
|
+
const c = findContext(args.context)
|
|
253
|
+
const kubectlArgs = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
254
|
+
kubectlArgs.push('top', args.kind)
|
|
255
|
+
if (args.kind === 'pods' && args.namespace) kubectlArgs.push('-n', args.namespace)
|
|
256
|
+
else if (args.kind === 'pods' && c?.namespace) kubectlArgs.push('-n', c.namespace)
|
|
257
|
+
if (args.sort_by) kubectlArgs.push(`--sort-by=${args.sort_by}`)
|
|
258
|
+
const r = await exec('kubectl', kubectlArgs, { timeout: 30000 })
|
|
259
|
+
if (r.code !== 0) return { ok: false, text: `kubectl top 失败:${r.stderr}` }
|
|
260
|
+
return { ok: true, text: trimOutput(r.stdout) }
|
|
261
|
+
},
|
|
262
|
+
})
|
|
263
|
+
|
|
264
|
+
register({
|
|
265
|
+
name: 'ops_kube_contexts',
|
|
266
|
+
description: '列出已保存的 Kubernetes 上下文,或从 kubeconfig 导入上下文。',
|
|
267
|
+
parameters: {
|
|
268
|
+
action: { type: 'string', enum: ['list', 'add', 'remove'], description: '操作(默认 list)' },
|
|
269
|
+
name: { type: 'string', description: 'add/remove 时的上下文名称' },
|
|
270
|
+
kubeconfig: { type: 'string', description: 'add 时的 kubeconfig 路径' },
|
|
271
|
+
namespace: { type: 'string', description: 'add 时的默认命名空间' },
|
|
272
|
+
},
|
|
273
|
+
output: textOutput,
|
|
274
|
+
async execute(args) {
|
|
275
|
+
const action = args.action || 'list'
|
|
276
|
+
if (action === 'list') {
|
|
277
|
+
const contexts = loadContexts()
|
|
278
|
+
if (!contexts.length) {
|
|
279
|
+
const r = await exec('kubectl', ['config', 'get-contexts', '-o', 'name'], { timeout: 10000 })
|
|
280
|
+
if (r.code === 0 && r.stdout) {
|
|
281
|
+
return { ok: true, text: '没有已保存的上下文。系统 kubeconfig 中的上下文:\n' + r.stdout + '\n\n可以直接在 ops_kube_get 等工具中使用这些名称,或用 ops_kube_contexts action=add 保存。' }
|
|
282
|
+
}
|
|
283
|
+
return { ok: true, text: '没有已保存的上下文,也没有找到系统 kubeconfig。用 ops_kube_contexts action=add 添加。' }
|
|
284
|
+
}
|
|
285
|
+
const lines = contexts.map((c) =>
|
|
286
|
+
`${c.name} ns=${c.namespace} kubeconfig=${c.kubeconfig}` +
|
|
287
|
+
(c.tags?.length ? ` [${c.tags.join(', ')}]` : '') +
|
|
288
|
+
(c.note ? ` — ${c.note}` : '')
|
|
289
|
+
)
|
|
290
|
+
return { ok: true, text: lines.join('\n') }
|
|
291
|
+
}
|
|
292
|
+
if (action === 'add') {
|
|
293
|
+
if (!args.name) return { ok: false, text: '需要 name 参数' }
|
|
294
|
+
const r = addContext({ name: args.name, kubeconfig: args.kubeconfig, namespace: args.namespace })
|
|
295
|
+
return { ok: r.ok, text: r.ok ? `已添加上下文 ${args.name}` : r.why }
|
|
296
|
+
}
|
|
297
|
+
if (action === 'remove') {
|
|
298
|
+
if (!args.name) return { ok: false, text: '需要 name 参数' }
|
|
299
|
+
const r = removeContext(args.name)
|
|
300
|
+
return { ok: r.ok, text: r.ok ? `已删除上下文 ${args.name}` : r.why }
|
|
301
|
+
}
|
|
302
|
+
return { ok: false, text: `未知操作 ${action}` }
|
|
303
|
+
},
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
register({
|
|
307
|
+
name: 'ops_kube_overview',
|
|
308
|
+
description: '获取集群概览:节点数、Pod 状态、Deployment 数、命名空间数、近期 Warning 事件。',
|
|
309
|
+
parameters: {
|
|
310
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
311
|
+
},
|
|
312
|
+
output: textOutput,
|
|
313
|
+
async execute(args) {
|
|
314
|
+
const c = findContext(args.context)
|
|
315
|
+
const base = c ? buildKubectlArgs(c, []) : ['--context', args.context]
|
|
316
|
+
const run = (extra) => exec('kubectl', [...base, ...extra], { timeout: 30000 })
|
|
317
|
+
const [nodesR, podsR, depsR, nsR, evtR] = await Promise.all([
|
|
318
|
+
run(['get', 'nodes', '-o', 'json']),
|
|
319
|
+
run(['get', 'pods', '-A', '-o', 'json']),
|
|
320
|
+
run(['get', 'deployments', '-A', '-o', 'json']),
|
|
321
|
+
run(['get', 'namespaces', '-o', 'json']),
|
|
322
|
+
run(['get', 'events', '-A', '--field-selector=type=Warning', '--sort-by=.lastTimestamp', '-o', 'json']),
|
|
323
|
+
])
|
|
324
|
+
const parse = (r) => { try { return JSON.parse(r.stdout) } catch { return { items: [] } } }
|
|
325
|
+
const nodes = parse(nodesR).items || []
|
|
326
|
+
const pods = parse(podsR).items || []
|
|
327
|
+
const deps = parse(depsR).items || []
|
|
328
|
+
const nss = parse(nsR).items || []
|
|
329
|
+
const evts = (parse(evtR).items || []).slice(0, 10)
|
|
330
|
+
|
|
331
|
+
const running = pods.filter(p => p.status?.phase === 'Running').length
|
|
332
|
+
const lines = [
|
|
333
|
+
`节点: ${nodes.length}`,
|
|
334
|
+
`Pod: ${running}/${pods.length} 运行中`,
|
|
335
|
+
`Deployment: ${deps.length}`,
|
|
336
|
+
`命名空间: ${nss.length} (${nss.map(n => n.metadata?.name).filter(Boolean).join(', ')})`,
|
|
337
|
+
]
|
|
338
|
+
if (evts.length) {
|
|
339
|
+
lines.push(`\n最近 Warning 事件 (${evts.length}):`)
|
|
340
|
+
for (const e of evts) {
|
|
341
|
+
lines.push(` ${e.reason} — ${e.involvedObject?.kind}/${e.involvedObject?.name}: ${(e.message || '').slice(0, 120)}`)
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return { ok: true, text: lines.join('\n') }
|
|
345
|
+
},
|
|
346
|
+
})
|
|
347
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
|
|
5
|
+
export function parseSshConfig(text) {
|
|
6
|
+
const hosts = []
|
|
7
|
+
let current = null
|
|
8
|
+
|
|
9
|
+
for (const raw of text.split('\n')) {
|
|
10
|
+
const line = raw.trim()
|
|
11
|
+
if (!line || line.startsWith('#')) continue
|
|
12
|
+
|
|
13
|
+
const hostMatch = line.match(/^Host\s+(.+)/i)
|
|
14
|
+
if (hostMatch) {
|
|
15
|
+
if (current && current.name) hosts.push(current)
|
|
16
|
+
const name = hostMatch[1].trim()
|
|
17
|
+
if (name.includes('*') || name.includes('?')) {
|
|
18
|
+
current = null
|
|
19
|
+
continue
|
|
20
|
+
}
|
|
21
|
+
current = { name, hostname: null, user: null, port: 22, identityFile: null, proxyJump: null }
|
|
22
|
+
continue
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (!current) continue
|
|
26
|
+
|
|
27
|
+
const kv = line.match(/^(\S+)\s+(.+)/)
|
|
28
|
+
if (!kv) continue
|
|
29
|
+
const [, key, value] = kv
|
|
30
|
+
const k = key.toLowerCase()
|
|
31
|
+
|
|
32
|
+
if (k === 'hostname') current.hostname = value
|
|
33
|
+
else if (k === 'user') current.user = value
|
|
34
|
+
else if (k === 'port') current.port = parseInt(value, 10) || 22
|
|
35
|
+
else if (k === 'identityfile') current.identityFile = value.replace(/^~/, homedir())
|
|
36
|
+
else if (k === 'proxyjump') current.proxyJump = value
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (current && current.name) hosts.push(current)
|
|
40
|
+
|
|
41
|
+
return hosts.filter(h => h.hostname)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function readSshConfig() {
|
|
45
|
+
const configPath = join(homedir(), '.ssh', 'config')
|
|
46
|
+
try {
|
|
47
|
+
const text = readFileSync(configPath, 'utf8')
|
|
48
|
+
return { ok: true, hosts: parseSshConfig(text), path: configPath }
|
|
49
|
+
} catch (e) {
|
|
50
|
+
if (e.code === 'ENOENT') return { ok: false, error: '未找到 ~/.ssh/config 文件' }
|
|
51
|
+
return { ok: false, error: e.message }
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { readJson, writeJson, dataDir } from '../cli.mjs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { mkdirSync } from 'node:fs'
|
|
4
|
+
|
|
5
|
+
const hostsFile = () => join(dataDir(), 'ssh', 'hosts.json')
|
|
6
|
+
|
|
7
|
+
export function loadHosts() {
|
|
8
|
+
return readJson(hostsFile(), [])
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function saveHosts(hosts) {
|
|
12
|
+
const dir = join(dataDir(), 'ssh')
|
|
13
|
+
mkdirSync(dir, { recursive: true })
|
|
14
|
+
writeJson(hostsFile(), hosts)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function findHost(nameOrAlias) {
|
|
18
|
+
const hosts = loadHosts()
|
|
19
|
+
return hosts.find((h) => h.name === nameOrAlias) || null
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function addHost({ name, hostname, port, user, identityFile, proxyJump, relay, tags, note }) {
|
|
23
|
+
const hosts = loadHosts()
|
|
24
|
+
if (hosts.find((h) => h.name === name)) {
|
|
25
|
+
return { ok: false, why: `主机 ${name} 已存在` }
|
|
26
|
+
}
|
|
27
|
+
hosts.push({
|
|
28
|
+
name,
|
|
29
|
+
hostname,
|
|
30
|
+
port: port || 22,
|
|
31
|
+
user: user || process.env.USER || '',
|
|
32
|
+
identityFile: identityFile || null,
|
|
33
|
+
proxyJump: proxyJump || null,
|
|
34
|
+
relay: relay || null,
|
|
35
|
+
tags: tags || [],
|
|
36
|
+
note: note || '',
|
|
37
|
+
addedAt: new Date().toISOString(),
|
|
38
|
+
})
|
|
39
|
+
saveHosts(hosts)
|
|
40
|
+
return { ok: true }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function removeHost(name) {
|
|
44
|
+
const hosts = loadHosts()
|
|
45
|
+
const idx = hosts.findIndex((h) => h.name === name)
|
|
46
|
+
if (idx === -1) return { ok: false, why: `主机 ${name} 不存在` }
|
|
47
|
+
hosts.splice(idx, 1)
|
|
48
|
+
saveHosts(hosts)
|
|
49
|
+
return { ok: true }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function updateHost(name, patch) {
|
|
53
|
+
const hosts = loadHosts()
|
|
54
|
+
const h = hosts.find((h) => h.name === name)
|
|
55
|
+
if (!h) return { ok: false, why: `主机 ${name} 不存在` }
|
|
56
|
+
if (patch.hostname !== undefined) h.hostname = patch.hostname
|
|
57
|
+
if (patch.port !== undefined) h.port = patch.port
|
|
58
|
+
if (patch.user !== undefined) h.user = patch.user
|
|
59
|
+
if (patch.identityFile !== undefined) h.identityFile = patch.identityFile
|
|
60
|
+
if (patch.proxyJump !== undefined) h.proxyJump = patch.proxyJump
|
|
61
|
+
if (patch.relay !== undefined) h.relay = patch.relay
|
|
62
|
+
if (patch.tags !== undefined) h.tags = patch.tags
|
|
63
|
+
if (patch.note !== undefined) h.note = patch.note
|
|
64
|
+
saveHosts(hosts)
|
|
65
|
+
return { ok: true }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function buildSshArgs(host, extraArgs = []) {
|
|
69
|
+
const args = ['-o', 'StrictHostKeyChecking=accept-new', '-o', 'BatchMode=yes']
|
|
70
|
+
if (host.port && host.port !== 22) args.push('-p', String(host.port))
|
|
71
|
+
if (host.identityFile) args.push('-i', host.identityFile)
|
|
72
|
+
if (host.proxyJump) args.push('-J', host.proxyJump)
|
|
73
|
+
args.push(...extraArgs)
|
|
74
|
+
const target = host.user ? `${host.user}@${host.hostname}` : host.hostname
|
|
75
|
+
return { args, target }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function shellQuote(s) {
|
|
79
|
+
return "'" + s.replace(/'/g, "'\\''") + "'"
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function buildRelayCommand(host, command) {
|
|
83
|
+
if (!host.relay) return null
|
|
84
|
+
const relayHost = findHost(host.relay)
|
|
85
|
+
if (!relayHost) return null
|
|
86
|
+
const { args: relayArgs, target: relayTarget } = buildSshArgs(relayHost)
|
|
87
|
+
const innerParts = ['ssh', '-o', 'StrictHostKeyChecking=accept-new', '-o', 'BatchMode=yes']
|
|
88
|
+
if (host.port && host.port !== 22) innerParts.push('-p', String(host.port))
|
|
89
|
+
if (host.identityFile) innerParts.push('-i', host.identityFile)
|
|
90
|
+
const innerTarget = host.user ? `${host.user}@${host.hostname}` : host.hostname
|
|
91
|
+
innerParts.push(innerTarget, shellQuote(command))
|
|
92
|
+
relayArgs.push(relayTarget, innerParts.join(' '))
|
|
93
|
+
return { args: relayArgs, isRelay: true }
|
|
94
|
+
}
|
package/lib/ssh/keys.mjs
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { readdirSync, statSync, unlinkSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { exec } from '../cli.mjs'
|
|
5
|
+
|
|
6
|
+
const SSH_DIR = join(homedir(), '.ssh')
|
|
7
|
+
|
|
8
|
+
export async function listKeys() {
|
|
9
|
+
const keys = []
|
|
10
|
+
let entries
|
|
11
|
+
try { entries = readdirSync(SSH_DIR) } catch { return keys }
|
|
12
|
+
|
|
13
|
+
const privNames = entries.filter(n =>
|
|
14
|
+
n.startsWith('id_') && !n.endsWith('.pub')
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
for (const name of privNames) {
|
|
18
|
+
const privPath = join(SSH_DIR, name)
|
|
19
|
+
const pubPath = privPath + '.pub'
|
|
20
|
+
let hasPublic = false
|
|
21
|
+
try { statSync(pubPath); hasPublic = true } catch {}
|
|
22
|
+
|
|
23
|
+
let fingerprint = ''
|
|
24
|
+
let type = ''
|
|
25
|
+
let comment = ''
|
|
26
|
+
try {
|
|
27
|
+
const r = await exec('ssh-keygen', ['-lf', privPath], { timeout: 5000 })
|
|
28
|
+
if (r.code === 0) {
|
|
29
|
+
const line = r.stdout.trim()
|
|
30
|
+
const parts = line.split(/\s+/)
|
|
31
|
+
fingerprint = parts[1] || ''
|
|
32
|
+
const typeMatch = line.match(/\((\w+)\)/)
|
|
33
|
+
type = typeMatch ? typeMatch[1] : ''
|
|
34
|
+
const commentMatch = line.match(/^\d+\s+\S+\s+(.+?)\s+\(\w+\)$/)
|
|
35
|
+
comment = commentMatch ? commentMatch[1] : ''
|
|
36
|
+
}
|
|
37
|
+
} catch {}
|
|
38
|
+
|
|
39
|
+
keys.push({ name, path: privPath, type, hasPublic, fingerprint, comment })
|
|
40
|
+
}
|
|
41
|
+
return keys
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function generateKey({ type = 'ed25519', bits, comment, path }) {
|
|
45
|
+
const keyPath = path || join(SSH_DIR, `id_${type}`)
|
|
46
|
+
const args = ['-t', type, '-f', keyPath, '-N', '']
|
|
47
|
+
if (bits && (type === 'rsa')) args.push('-b', String(bits))
|
|
48
|
+
if (comment) args.push('-C', comment)
|
|
49
|
+
else args.push('-C', `${process.env.USER || 'user'}@dsh-ops`)
|
|
50
|
+
|
|
51
|
+
const r = await exec('ssh-keygen', args, { timeout: 15000 })
|
|
52
|
+
if (r.code !== 0) return { ok: false, error: r.stderr || `exit ${r.code}` }
|
|
53
|
+
|
|
54
|
+
let fingerprint = ''
|
|
55
|
+
try {
|
|
56
|
+
const fp = await exec('ssh-keygen', ['-lf', keyPath], { timeout: 5000 })
|
|
57
|
+
if (fp.code === 0) fingerprint = fp.stdout.trim().split(/\s+/)[1] || ''
|
|
58
|
+
} catch {}
|
|
59
|
+
|
|
60
|
+
return { ok: true, path: keyPath, fingerprint }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function deleteKey(name) {
|
|
64
|
+
if (!name.startsWith('id_') || name.includes('/') || name.includes('..')) {
|
|
65
|
+
return { ok: false, error: '无效的密钥名称' }
|
|
66
|
+
}
|
|
67
|
+
const privPath = join(SSH_DIR, name)
|
|
68
|
+
const pubPath = privPath + '.pub'
|
|
69
|
+
let deleted = []
|
|
70
|
+
try { unlinkSync(privPath); deleted.push(name) } catch (e) {
|
|
71
|
+
if (e.code !== 'ENOENT') return { ok: false, error: e.message }
|
|
72
|
+
}
|
|
73
|
+
try { unlinkSync(pubPath); deleted.push(name + '.pub') } catch {}
|
|
74
|
+
if (!deleted.length) return { ok: false, error: '密钥文件不存在' }
|
|
75
|
+
return { ok: true, deleted }
|
|
76
|
+
}
|