@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/helm/mod.mjs
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
import { exec, trimOutput, dataDir } from '../cli.mjs'
|
|
2
|
+
import { findContext, buildKubectlArgs } from '../k8s/context.mjs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
5
|
+
|
|
6
|
+
function helmArgs(ctxName, extra = []) {
|
|
7
|
+
const c = findContext(ctxName)
|
|
8
|
+
if (!c) return ['--kube-context', ctxName, ...extra]
|
|
9
|
+
const args = []
|
|
10
|
+
const src = c.source || 'kubeconfig'
|
|
11
|
+
if (src === 'kubeconfig') {
|
|
12
|
+
if (c.kubeconfig) args.push('--kubeconfig', c.kubeconfig)
|
|
13
|
+
if (c.context) args.push('--kube-context', c.context)
|
|
14
|
+
} else {
|
|
15
|
+
const cDir = join(dataDir(), 'k8s', 'creds', c.name)
|
|
16
|
+
if (c.server) {
|
|
17
|
+
args.push('--kube-apiserver', c.server)
|
|
18
|
+
const caFile = join(cDir, 'ca.pem')
|
|
19
|
+
if (existsSync(caFile)) args.push('--kube-ca-file', caFile)
|
|
20
|
+
if (src === 'token') {
|
|
21
|
+
const tokenFile = join(cDir, 'token')
|
|
22
|
+
if (existsSync(tokenFile)) args.push('--kube-token', readFileSync(tokenFile, 'utf8').trim())
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
args.push(...extra)
|
|
27
|
+
return args
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function registerHelmTools(ctx, defineTool, toolsSvc, config) {
|
|
31
|
+
const textOutput = {
|
|
32
|
+
schema: { type: 'object', properties: {}, additionalProperties: true },
|
|
33
|
+
render: (_args, value) => [{ type: 'text', text: String(value?.text ?? '') }],
|
|
34
|
+
}
|
|
35
|
+
const register = (tool) => toolsSvc.register(defineTool(tool))
|
|
36
|
+
|
|
37
|
+
register({
|
|
38
|
+
name: 'ops_helm_list',
|
|
39
|
+
description: '列出 Helm Releases。',
|
|
40
|
+
parameters: {
|
|
41
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
42
|
+
namespace: { type: 'string', description: '命名空间(不填则当前命名空间)' },
|
|
43
|
+
all_namespaces: { type: 'boolean', description: '查看所有命名空间' },
|
|
44
|
+
},
|
|
45
|
+
output: textOutput,
|
|
46
|
+
async execute(args) {
|
|
47
|
+
const extra = ['list', '--output', 'json']
|
|
48
|
+
if (args.namespace) extra.push('-n', args.namespace)
|
|
49
|
+
if (args.all_namespaces) extra.push('-A')
|
|
50
|
+
const r = await exec('helm', helmArgs(args.context, extra), { timeout: 30000 })
|
|
51
|
+
if (r.code !== 0) return { ok: false, text: `helm list 失败:${r.stderr}` }
|
|
52
|
+
try {
|
|
53
|
+
const items = JSON.parse(r.stdout || '[]')
|
|
54
|
+
if (!items.length) return { ok: true, text: '无 Helm Release' }
|
|
55
|
+
const lines = items.map(i => `${i.name} ns=${i.namespace} chart=${i.chart} status=${i.status} v${i.revision || i.version || '-'}`)
|
|
56
|
+
return { ok: true, text: lines.join('\n') }
|
|
57
|
+
} catch { return { ok: true, text: r.stdout } }
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
register({
|
|
62
|
+
name: 'ops_helm_status',
|
|
63
|
+
description: '查看 Helm Release 的状态详情。',
|
|
64
|
+
parameters: {
|
|
65
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
66
|
+
release: { type: 'string', description: 'Release 名称', required: true },
|
|
67
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
68
|
+
},
|
|
69
|
+
output: textOutput,
|
|
70
|
+
async execute(args) {
|
|
71
|
+
const extra = ['status', args.release, '--output', 'json']
|
|
72
|
+
if (args.namespace) extra.push('-n', args.namespace)
|
|
73
|
+
const r = await exec('helm', helmArgs(args.context, extra), { timeout: 15000 })
|
|
74
|
+
if (r.code !== 0) return { ok: false, text: `helm status 失败:${r.stderr}` }
|
|
75
|
+
try {
|
|
76
|
+
const d = JSON.parse(r.stdout)
|
|
77
|
+
const info = d.info || {}
|
|
78
|
+
return { ok: true, text: `Release: ${d.name}\n状态: ${info.status}\n版本: ${d.version}\n命名空间: ${d.namespace}\n最后部署: ${info.last_deployed || '-'}\n描述: ${info.description || '-'}` }
|
|
79
|
+
} catch { return { ok: true, text: r.stdout } }
|
|
80
|
+
},
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
register({
|
|
84
|
+
name: 'ops_helm_values',
|
|
85
|
+
description: '获取 Helm Release 的 Values 配置。',
|
|
86
|
+
parameters: {
|
|
87
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
88
|
+
release: { type: 'string', description: 'Release 名称', required: true },
|
|
89
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
90
|
+
all: { type: 'boolean', description: '显示所有 values(包含默认值)' },
|
|
91
|
+
},
|
|
92
|
+
output: textOutput,
|
|
93
|
+
async execute(args) {
|
|
94
|
+
const extra = ['get', 'values', args.release, '--output', 'yaml']
|
|
95
|
+
if (args.namespace) extra.push('-n', args.namespace)
|
|
96
|
+
if (args.all) extra.push('--all')
|
|
97
|
+
const r = await exec('helm', helmArgs(args.context, extra), { timeout: 15000 })
|
|
98
|
+
if (r.code !== 0) return { ok: false, text: `helm get values 失败:${r.stderr}` }
|
|
99
|
+
return { ok: true, text: trimOutput(r.stdout || '无自定义 Values') }
|
|
100
|
+
},
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
register({
|
|
104
|
+
name: 'ops_helm_history',
|
|
105
|
+
description: '查看 Helm Release 的部署历史。',
|
|
106
|
+
parameters: {
|
|
107
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
108
|
+
release: { type: 'string', description: 'Release 名称', required: true },
|
|
109
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
110
|
+
},
|
|
111
|
+
output: textOutput,
|
|
112
|
+
async execute(args) {
|
|
113
|
+
const extra = ['history', args.release, '--output', 'json']
|
|
114
|
+
if (args.namespace) extra.push('-n', args.namespace)
|
|
115
|
+
const r = await exec('helm', helmArgs(args.context, extra), { timeout: 15000 })
|
|
116
|
+
if (r.code !== 0) return { ok: false, text: `helm history 失败:${r.stderr}` }
|
|
117
|
+
try {
|
|
118
|
+
const items = JSON.parse(r.stdout || '[]')
|
|
119
|
+
if (!items.length) return { ok: true, text: '无历史记录' }
|
|
120
|
+
const lines = items.map(h => `v${h.revision} ${h.status} chart=${h.chart} app=${h.app_version || '-'} ${h.description || ''}`)
|
|
121
|
+
return { ok: true, text: lines.join('\n') }
|
|
122
|
+
} catch { return { ok: true, text: r.stdout } }
|
|
123
|
+
},
|
|
124
|
+
})
|
|
125
|
+
|
|
126
|
+
register({
|
|
127
|
+
name: 'ops_helm_install',
|
|
128
|
+
description: '安装 Helm Chart(默认 dry-run,需显式设 dry_run=false 才真正安装)。',
|
|
129
|
+
parameters: {
|
|
130
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
131
|
+
release: { type: 'string', description: 'Release 名称', required: true },
|
|
132
|
+
chart: { type: 'string', description: 'Chart(repo/name 或 URL)', required: true },
|
|
133
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
134
|
+
version: { type: 'string', description: 'Chart 版本' },
|
|
135
|
+
values: { type: 'string', description: '自定义 Values(YAML 格式)' },
|
|
136
|
+
dry_run: { type: 'boolean', description: '是否只做 dry-run(默认 true)' },
|
|
137
|
+
},
|
|
138
|
+
output: textOutput,
|
|
139
|
+
async execute(args) {
|
|
140
|
+
const extra = ['install', args.release, args.chart]
|
|
141
|
+
if (args.namespace) extra.push('-n', args.namespace, '--create-namespace')
|
|
142
|
+
if (args.version) extra.push('--version', args.version)
|
|
143
|
+
if (args.values) extra.push('--values', '-')
|
|
144
|
+
if (args.dry_run !== false) extra.push('--dry-run')
|
|
145
|
+
const r = await exec('helm', helmArgs(args.context, extra), { timeout: 120000, stdin: args.values || undefined })
|
|
146
|
+
const prefix = args.dry_run !== false ? '[dry-run] ' : ''
|
|
147
|
+
if (r.code !== 0) return { ok: false, text: `${prefix}helm install 失败:${r.stderr || r.stdout}` }
|
|
148
|
+
return { ok: true, text: trimOutput(`${prefix}${r.stdout}`) }
|
|
149
|
+
},
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
register({
|
|
153
|
+
name: 'ops_helm_upgrade',
|
|
154
|
+
description: '升级 Helm Release(默认 dry-run)。',
|
|
155
|
+
parameters: {
|
|
156
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
157
|
+
release: { type: 'string', description: 'Release 名称', required: true },
|
|
158
|
+
chart: { type: 'string', description: 'Chart(repo/name 或 URL)', required: true },
|
|
159
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
160
|
+
version: { type: 'string', description: 'Chart 版本' },
|
|
161
|
+
values: { type: 'string', description: '自定义 Values(YAML 格式)' },
|
|
162
|
+
reuse_values: { type: 'boolean', description: '复用现有 Values' },
|
|
163
|
+
dry_run: { type: 'boolean', description: '是否只做 dry-run(默认 true)' },
|
|
164
|
+
},
|
|
165
|
+
output: textOutput,
|
|
166
|
+
async execute(args) {
|
|
167
|
+
const extra = ['upgrade', args.release, args.chart]
|
|
168
|
+
if (args.namespace) extra.push('-n', args.namespace)
|
|
169
|
+
if (args.version) extra.push('--version', args.version)
|
|
170
|
+
if (args.values) extra.push('--values', '-')
|
|
171
|
+
if (args.reuse_values) extra.push('--reuse-values')
|
|
172
|
+
if (args.dry_run !== false) extra.push('--dry-run')
|
|
173
|
+
const r = await exec('helm', helmArgs(args.context, extra), { timeout: 120000, stdin: args.values || undefined })
|
|
174
|
+
const prefix = args.dry_run !== false ? '[dry-run] ' : ''
|
|
175
|
+
if (r.code !== 0) return { ok: false, text: `${prefix}helm upgrade 失败:${r.stderr || r.stdout}` }
|
|
176
|
+
return { ok: true, text: trimOutput(`${prefix}${r.stdout}`) }
|
|
177
|
+
},
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
register({
|
|
181
|
+
name: 'ops_helm_uninstall',
|
|
182
|
+
description: '卸载 Helm Release(会删除所有关联的 K8s 资源)。默认 dry-run。',
|
|
183
|
+
parameters: {
|
|
184
|
+
context: { type: 'string', description: 'kubectl context 名称', required: true },
|
|
185
|
+
release: { type: 'string', description: 'Release 名称', required: true },
|
|
186
|
+
namespace: { type: 'string', description: '命名空间' },
|
|
187
|
+
dry_run: { type: 'boolean', description: '是否只做 dry-run(默认 true)' },
|
|
188
|
+
},
|
|
189
|
+
output: textOutput,
|
|
190
|
+
async execute(args) {
|
|
191
|
+
const extra = ['uninstall', args.release]
|
|
192
|
+
if (args.namespace) extra.push('-n', args.namespace)
|
|
193
|
+
if (args.dry_run !== false) extra.push('--dry-run')
|
|
194
|
+
const r = await exec('helm', helmArgs(args.context, extra), { timeout: 60000 })
|
|
195
|
+
const prefix = args.dry_run !== false ? '[dry-run] ' : ''
|
|
196
|
+
if (r.code !== 0) return { ok: false, text: `${prefix}helm uninstall 失败:${r.stderr}` }
|
|
197
|
+
return { ok: true, text: `${prefix}${r.stdout || `已卸载 ${args.release}`}` }
|
|
198
|
+
},
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
register({
|
|
202
|
+
name: 'ops_helm_repo',
|
|
203
|
+
description: '管理 Helm 仓库:list 列出、add 添加、remove 删除、update 更新索引。',
|
|
204
|
+
parameters: {
|
|
205
|
+
action: { type: 'string', enum: ['list', 'add', 'remove', 'update'], description: '操作(默认 list)' },
|
|
206
|
+
name: { type: 'string', description: 'add/remove 时仓库名称' },
|
|
207
|
+
url: { type: 'string', description: 'add 时仓库 URL' },
|
|
208
|
+
},
|
|
209
|
+
output: textOutput,
|
|
210
|
+
async execute(args) {
|
|
211
|
+
const action = args.action || 'list'
|
|
212
|
+
if (action === 'list') {
|
|
213
|
+
const r = await exec('helm', ['repo', 'list', '--output', 'json'], { timeout: 15000 })
|
|
214
|
+
if (r.code !== 0) return { ok: false, text: `helm repo list 失败:${r.stderr}` }
|
|
215
|
+
try {
|
|
216
|
+
const items = JSON.parse(r.stdout || '[]')
|
|
217
|
+
if (!items.length) return { ok: true, text: '无 Helm 仓库' }
|
|
218
|
+
return { ok: true, text: items.map(r => `${r.name} ${r.url}`).join('\n') }
|
|
219
|
+
} catch { return { ok: true, text: r.stdout } }
|
|
220
|
+
}
|
|
221
|
+
if (action === 'add') {
|
|
222
|
+
if (!args.name || !args.url) return { ok: false, text: '需要 name 和 url 参数' }
|
|
223
|
+
const r = await exec('helm', ['repo', 'add', args.name, args.url, '--force-update'], { timeout: 30000 })
|
|
224
|
+
return { ok: r.code === 0, text: r.code === 0 ? `已添加仓库 ${args.name}` : `添加失败:${r.stderr || r.stdout}` }
|
|
225
|
+
}
|
|
226
|
+
if (action === 'remove') {
|
|
227
|
+
if (!args.name) return { ok: false, text: '需要 name 参数' }
|
|
228
|
+
const r = await exec('helm', ['repo', 'remove', args.name], { timeout: 15000 })
|
|
229
|
+
return { ok: r.code === 0, text: r.code === 0 ? `已删除仓库 ${args.name}` : `删除失败:${r.stderr || r.stdout}` }
|
|
230
|
+
}
|
|
231
|
+
if (action === 'update') {
|
|
232
|
+
const updateArgs = ['repo', 'update']
|
|
233
|
+
if (args.name) updateArgs.push(args.name)
|
|
234
|
+
const r = await exec('helm', updateArgs, { timeout: 60000 })
|
|
235
|
+
return { ok: r.code === 0, text: r.code === 0 ? trimOutput(r.stdout) : `更新失败:${r.stderr || r.stdout}` }
|
|
236
|
+
}
|
|
237
|
+
return { ok: false, text: `未知操作 ${action}` }
|
|
238
|
+
},
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
register({
|
|
242
|
+
name: 'ops_helm_search',
|
|
243
|
+
description: '搜索 Helm Chart(从已添加的仓库中搜索)。',
|
|
244
|
+
parameters: {
|
|
245
|
+
keyword: { type: 'string', description: '搜索关键词', required: true },
|
|
246
|
+
versions: { type: 'boolean', description: '显示所有版本' },
|
|
247
|
+
},
|
|
248
|
+
output: textOutput,
|
|
249
|
+
async execute(args) {
|
|
250
|
+
const extra = ['search', 'repo', args.keyword, '--output', 'json']
|
|
251
|
+
if (args.versions) extra.push('--versions')
|
|
252
|
+
const r = await exec('helm', extra, { timeout: 30000 })
|
|
253
|
+
if (r.code !== 0) return { ok: false, text: `helm search 失败:${r.stderr}` }
|
|
254
|
+
try {
|
|
255
|
+
const items = JSON.parse(r.stdout || '[]')
|
|
256
|
+
if (!items.length) return { ok: true, text: '未找到匹配的 Chart' }
|
|
257
|
+
const lines = items.map(c => `${c.name} v${c.version} app=${c.app_version || '-'} ${(c.description || '').slice(0, 80)}`)
|
|
258
|
+
return { ok: true, text: trimOutput(lines.join('\n')) }
|
|
259
|
+
} catch { return { ok: true, text: r.stdout } }
|
|
260
|
+
},
|
|
261
|
+
})
|
|
262
|
+
|
|
263
|
+
register({
|
|
264
|
+
name: 'ops_helm_show',
|
|
265
|
+
description: '查看 Chart 的详情(chart 元数据、values 默认值、readme)。',
|
|
266
|
+
parameters: {
|
|
267
|
+
chart: { type: 'string', description: 'Chart 名称(repo/name)', required: true },
|
|
268
|
+
sub: { type: 'string', enum: ['chart', 'values', 'readme'], description: '查看内容(默认 chart)' },
|
|
269
|
+
version: { type: 'string', description: 'Chart 版本' },
|
|
270
|
+
},
|
|
271
|
+
output: textOutput,
|
|
272
|
+
async execute(args) {
|
|
273
|
+
const sub = args.sub || 'chart'
|
|
274
|
+
const extra = ['show', sub, args.chart]
|
|
275
|
+
if (args.version) extra.push('--version', args.version)
|
|
276
|
+
const r = await exec('helm', extra, { timeout: 30000 })
|
|
277
|
+
if (r.code !== 0) return { ok: false, text: `helm show ${sub} 失败:${r.stderr}` }
|
|
278
|
+
return { ok: true, text: trimOutput(r.stdout) }
|
|
279
|
+
},
|
|
280
|
+
})
|
|
281
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { readJson, writeJson, dataDir, exec } from '../cli.mjs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { mkdirSync, existsSync, writeFileSync, readFileSync, rmSync, unlinkSync } from 'node:fs'
|
|
4
|
+
import { homedir } from 'node:os'
|
|
5
|
+
import { tmpdir } from 'node:os'
|
|
6
|
+
|
|
7
|
+
const contextsFile = () => join(dataDir(), 'k8s', 'contexts.json')
|
|
8
|
+
|
|
9
|
+
export function loadContexts() {
|
|
10
|
+
return readJson(contextsFile(), [])
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function saveContexts(contexts) {
|
|
14
|
+
const dir = join(dataDir(), 'k8s')
|
|
15
|
+
mkdirSync(dir, { recursive: true })
|
|
16
|
+
writeJson(contextsFile(), contexts)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function findContext(name) {
|
|
20
|
+
const contexts = loadContexts()
|
|
21
|
+
return contexts.find((c) => c.name === name) || null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function credDir(name) {
|
|
25
|
+
const dir = join(dataDir(), 'k8s', 'creds', name)
|
|
26
|
+
mkdirSync(dir, { recursive: true })
|
|
27
|
+
return dir
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function saveCredFile(ctxName, filename, content) {
|
|
31
|
+
const dir = credDir(ctxName)
|
|
32
|
+
const p = join(dir, filename)
|
|
33
|
+
writeFileSync(p, content, { mode: 0o600 })
|
|
34
|
+
return p
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function removeCredFiles(ctxName) {
|
|
38
|
+
const dir = join(dataDir(), 'k8s', 'creds', ctxName)
|
|
39
|
+
if (existsSync(dir)) rmSync(dir, { recursive: true, force: true })
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function addContext({ name, kubeconfig, context, namespace, server, token, caData, certData, keyData, source, tags, note }) {
|
|
43
|
+
const contexts = loadContexts()
|
|
44
|
+
if (contexts.find((c) => c.name === name)) {
|
|
45
|
+
return { ok: false, why: `上下文 ${name} 已存在` }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const entry = {
|
|
49
|
+
name,
|
|
50
|
+
source: source || 'kubeconfig',
|
|
51
|
+
kubeconfig: null,
|
|
52
|
+
context: context || null,
|
|
53
|
+
server: server || null,
|
|
54
|
+
namespace: namespace || 'default',
|
|
55
|
+
tags: tags || [],
|
|
56
|
+
note: note || '',
|
|
57
|
+
addedAt: new Date().toISOString(),
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (source === 'token') {
|
|
61
|
+
entry.server = server
|
|
62
|
+
if (token) saveCredFile(name, 'token', token)
|
|
63
|
+
if (caData) saveCredFile(name, 'ca.pem', caData)
|
|
64
|
+
} else if (source === 'cert') {
|
|
65
|
+
entry.server = server
|
|
66
|
+
if (caData) saveCredFile(name, 'ca.pem', caData)
|
|
67
|
+
if (certData) saveCredFile(name, 'client.pem', certData)
|
|
68
|
+
if (keyData) saveCredFile(name, 'client-key.pem', keyData)
|
|
69
|
+
} else {
|
|
70
|
+
entry.kubeconfig = kubeconfig || join(homedir(), '.kube', 'config')
|
|
71
|
+
entry.context = context || name
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
contexts.push(entry)
|
|
75
|
+
saveContexts(contexts)
|
|
76
|
+
return { ok: true }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function removeContext(name) {
|
|
80
|
+
const contexts = loadContexts()
|
|
81
|
+
const idx = contexts.findIndex((c) => c.name === name)
|
|
82
|
+
if (idx === -1) return { ok: false, why: `上下文 ${name} 不存在` }
|
|
83
|
+
contexts.splice(idx, 1)
|
|
84
|
+
saveContexts(contexts)
|
|
85
|
+
removeCredFiles(name)
|
|
86
|
+
return { ok: true }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function updateContext(name, patch) {
|
|
90
|
+
const contexts = loadContexts()
|
|
91
|
+
const c = contexts.find((c) => c.name === name)
|
|
92
|
+
if (!c) return { ok: false, why: `上下文 ${name} 不存在` }
|
|
93
|
+
if (patch.namespace !== undefined) c.namespace = patch.namespace
|
|
94
|
+
if (patch.tags !== undefined) c.tags = patch.tags
|
|
95
|
+
if (patch.note !== undefined) c.note = patch.note
|
|
96
|
+
saveContexts(contexts)
|
|
97
|
+
return { ok: true }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function buildKubectlArgs(context, extraArgs = []) {
|
|
101
|
+
const args = []
|
|
102
|
+
const src = context.source || 'kubeconfig'
|
|
103
|
+
const cDir = join(dataDir(), 'k8s', 'creds', context.name)
|
|
104
|
+
|
|
105
|
+
if (src === 'token') {
|
|
106
|
+
args.push('--server', context.server)
|
|
107
|
+
const tokenFile = join(cDir, 'token')
|
|
108
|
+
if (existsSync(tokenFile)) {
|
|
109
|
+
const tk = readFileSync(tokenFile, 'utf8').trim()
|
|
110
|
+
args.push('--token', tk)
|
|
111
|
+
}
|
|
112
|
+
const caFile = join(cDir, 'ca.pem')
|
|
113
|
+
if (existsSync(caFile)) args.push('--certificate-authority', caFile)
|
|
114
|
+
else args.push('--insecure-skip-tls-verify=true')
|
|
115
|
+
} else if (src === 'cert') {
|
|
116
|
+
args.push('--server', context.server)
|
|
117
|
+
const caFile = join(cDir, 'ca.pem')
|
|
118
|
+
if (existsSync(caFile)) args.push('--certificate-authority', caFile)
|
|
119
|
+
const certFile = join(cDir, 'client.pem')
|
|
120
|
+
if (existsSync(certFile)) args.push('--client-certificate', certFile)
|
|
121
|
+
const keyFile = join(cDir, 'client-key.pem')
|
|
122
|
+
if (existsSync(keyFile)) args.push('--client-key', keyFile)
|
|
123
|
+
} else {
|
|
124
|
+
if (context.kubeconfig) args.push('--kubeconfig', context.kubeconfig)
|
|
125
|
+
if (context.context) args.push('--context', context.context)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
args.push(...extraArgs)
|
|
129
|
+
return args
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function parseKubeconfig(pathOrContent) {
|
|
133
|
+
let filePath = pathOrContent
|
|
134
|
+
let tmpPath = null
|
|
135
|
+
|
|
136
|
+
if (pathOrContent.includes('\n') || pathOrContent.includes('apiVersion')) {
|
|
137
|
+
tmpPath = join(tmpdir(), `dsh-ops-kc-${Date.now()}.yaml`)
|
|
138
|
+
writeFileSync(tmpPath, pathOrContent, 'utf8')
|
|
139
|
+
filePath = tmpPath
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
try {
|
|
143
|
+
const r = await exec('kubectl', ['config', 'view', '--kubeconfig', filePath, '--raw', '-o', 'json'], { timeout: 10000 })
|
|
144
|
+
if (r.code !== 0) return { ok: false, error: r.stderr || `kubectl config view 失败 (exit ${r.code})` }
|
|
145
|
+
const cfg = JSON.parse(r.stdout)
|
|
146
|
+
const clusters = (cfg.clusters || []).map(c => ({ name: c.name, server: c.cluster?.server || '', caData: c.cluster?.['certificate-authority-data'] || '' }))
|
|
147
|
+
const users = (cfg.users || []).map(u => ({ name: u.name, token: u.user?.token || '', certData: u.user?.['client-certificate-data'] || '', keyData: u.user?.['client-key-data'] || '' }))
|
|
148
|
+
const contexts = (cfg.contexts || []).map(c => ({
|
|
149
|
+
name: c.name,
|
|
150
|
+
cluster: c.context?.cluster || '',
|
|
151
|
+
user: c.context?.user || '',
|
|
152
|
+
namespace: c.context?.namespace || 'default',
|
|
153
|
+
}))
|
|
154
|
+
return { ok: true, contexts, clusters, users, currentContext: cfg['current-context'] || '' }
|
|
155
|
+
} catch (e) {
|
|
156
|
+
return { ok: false, error: String(e.message || e) }
|
|
157
|
+
} finally {
|
|
158
|
+
if (tmpPath) try { unlinkSync(tmpPath) } catch {}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function importContexts(parsed, selectedNames, kubeconfigPath) {
|
|
163
|
+
const results = []
|
|
164
|
+
for (const ctxInfo of parsed.contexts) {
|
|
165
|
+
if (!selectedNames.includes(ctxInfo.name)) continue
|
|
166
|
+
const existing = findContext(ctxInfo.name)
|
|
167
|
+
if (existing) { results.push({ name: ctxInfo.name, ok: false, why: '已存在' }); continue }
|
|
168
|
+
|
|
169
|
+
const r = addContext({
|
|
170
|
+
name: ctxInfo.name,
|
|
171
|
+
kubeconfig: kubeconfigPath || join(homedir(), '.kube', 'config'),
|
|
172
|
+
context: ctxInfo.name,
|
|
173
|
+
namespace: ctxInfo.namespace || 'default',
|
|
174
|
+
source: 'kubeconfig',
|
|
175
|
+
})
|
|
176
|
+
results.push({ name: ctxInfo.name, ...r })
|
|
177
|
+
}
|
|
178
|
+
return results
|
|
179
|
+
}
|