dotop-gpu-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +148 -2
- package/bin/dotop-gpu.mjs +597 -0
- package/package.json +33 -4
- package/src/api.mjs +214 -0
- package/src/config.mjs +91 -0
- package/src/prompts.mjs +529 -0
- package/src/render.mjs +185 -0
- package/src/rentargs.mjs +232 -0
- package/src/rentflow.mjs +186 -0
- package/src/sshkeys.mjs +69 -0
- package/src/wizard.mjs +1056 -0
package/src/render.mjs
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// 终端渲染:表格、状态色(仅 ANSI 前景色,不用背景色)、金额与时长格式化。
|
|
2
|
+
const CSI = '\u001b[';
|
|
3
|
+
const RESET = `${CSI}0m`;
|
|
4
|
+
const DIM = `${CSI}2m`;
|
|
5
|
+
const BOLD = `${CSI}1m`;
|
|
6
|
+
const color = (code) => (s) => `${CSI}${code}m${s}${RESET}`;
|
|
7
|
+
|
|
8
|
+
const noColor = !!process.env.NO_COLOR || !process.stdout.isTTY;
|
|
9
|
+
|
|
10
|
+
// 菜单高亮用的前景色(青 + 粗体)。不用背景色:深色/浅色终端下
|
|
11
|
+
// 反色块容易出现文字与底色撞色,前景色到哪都看得清。
|
|
12
|
+
const ACTIVE = `${CSI}36;1m`;
|
|
13
|
+
|
|
14
|
+
// 高亮整行,同时**保留行内已有的颜色**。
|
|
15
|
+
//
|
|
16
|
+
// 行内文本可能自带 paint.dim() / paint.green() 之类的序列,而它们都以
|
|
17
|
+
// \x1b[0m 结尾 —— 一旦出现就把外层的青色粗体一起清掉了,后半行会掉回默认色。
|
|
18
|
+
// 所以在每个内层 reset 之后重新补一次 ACTIVE,让外层属性接力下去。
|
|
19
|
+
function highlight(s) {
|
|
20
|
+
const body = String(s ?? '').replaceAll(RESET, `${RESET}${ACTIVE}`);
|
|
21
|
+
return `${ACTIVE}${body}${RESET}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const paint = noColor
|
|
25
|
+
? {
|
|
26
|
+
dim: (s) => String(s),
|
|
27
|
+
bold: (s) => String(s),
|
|
28
|
+
green: (s) => String(s),
|
|
29
|
+
red: (s) => String(s),
|
|
30
|
+
yellow: (s) => String(s),
|
|
31
|
+
cyan: (s) => String(s),
|
|
32
|
+
gray: (s) => String(s),
|
|
33
|
+
highlight: (s) => String(s),
|
|
34
|
+
}
|
|
35
|
+
: {
|
|
36
|
+
dim: (s) => `${DIM}${s}${RESET}`,
|
|
37
|
+
bold: (s) => `${BOLD}${s}${RESET}`,
|
|
38
|
+
green: color('32'),
|
|
39
|
+
red: color('31'),
|
|
40
|
+
yellow: color('33'),
|
|
41
|
+
cyan: color('36'),
|
|
42
|
+
gray: color('90'),
|
|
43
|
+
highlight,
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// ANSI 颜色序列:只影响终端显示,不占字符宽度
|
|
47
|
+
const ANSI_RE = /\x1b\[[0-9;]*[A-Za-z]/g;
|
|
48
|
+
|
|
49
|
+
export function stripAnsi(str) {
|
|
50
|
+
return String(str ?? '').replace(ANSI_RE, '');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// 中日韩字符按 2 列宽计算,否则表格会歪。
|
|
54
|
+
// 必须先剔掉 ANSI 序列:否则 paint.dim() 包过的文本会被算成「多出好几列」,
|
|
55
|
+
// 表格补空格和菜单截断都会错位。
|
|
56
|
+
function displayWidth(str) {
|
|
57
|
+
let w = 0;
|
|
58
|
+
for (const ch of stripAnsi(str)) {
|
|
59
|
+
const code = ch.codePointAt(0);
|
|
60
|
+
const wide =
|
|
61
|
+
(code >= 0x1100 && code <= 0x115f) ||
|
|
62
|
+
(code >= 0x2e80 && code <= 0xa4cf) ||
|
|
63
|
+
(code >= 0xac00 && code <= 0xd7a3) ||
|
|
64
|
+
(code >= 0xf900 && code <= 0xfaff) ||
|
|
65
|
+
(code >= 0xfe30 && code <= 0xfe6f) ||
|
|
66
|
+
(code >= 0xff00 && code <= 0xff60) ||
|
|
67
|
+
(code >= 0xffe0 && code <= 0xffe6) ||
|
|
68
|
+
(code >= 0x1f300 && code <= 0x1f64f);
|
|
69
|
+
w += wide ? 2 : 1;
|
|
70
|
+
}
|
|
71
|
+
return w;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function pad(str, width) {
|
|
75
|
+
const s = String(str ?? '');
|
|
76
|
+
const diff = width - displayWidth(s);
|
|
77
|
+
return diff > 0 ? s + ' '.repeat(diff) : s;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function table(columns, rows) {
|
|
81
|
+
if (!rows || rows.length === 0) return '';
|
|
82
|
+
const widths = columns.map((c) =>
|
|
83
|
+
Math.max(displayWidth(c.title), ...rows.map((r) => displayWidth(c.get(r)))),
|
|
84
|
+
);
|
|
85
|
+
const head = columns.map((c, i) => pad(c.title, widths[i])).join(' ');
|
|
86
|
+
const lines = [paint.dim(head)];
|
|
87
|
+
for (const r of rows) {
|
|
88
|
+
lines.push(columns.map((c, i) => pad(c.get(r), widths[i])).join(' '));
|
|
89
|
+
}
|
|
90
|
+
return lines.join('\n');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// gpu-16 / srv-16 这类名字过长时截断,避免撑破终端
|
|
94
|
+
export function shortId(s, n = 18) {
|
|
95
|
+
const str = String(s ?? '');
|
|
96
|
+
return displayWidth(str) <= n ? str : `${str.slice(0, n - 1)}…`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function money(v) {
|
|
100
|
+
const n = Number(v);
|
|
101
|
+
if (!Number.isFinite(n)) return '-';
|
|
102
|
+
if (n === 0) return '¥0';
|
|
103
|
+
const abs = Math.abs(n);
|
|
104
|
+
if (abs >= 100) return `¥${n.toFixed(2)}`;
|
|
105
|
+
if (abs >= 1) return `¥${n.toFixed(3).replace(/0+$/, '').replace(/\.$/, '')}`;
|
|
106
|
+
return `¥${n.toFixed(4).replace(/0+$/, '').replace(/\.$/, '')}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function duration(seconds) {
|
|
110
|
+
const s = Math.max(0, Math.floor(Number(seconds) || 0));
|
|
111
|
+
if (s < 60) return `${s}秒`;
|
|
112
|
+
const m = Math.floor(s / 60);
|
|
113
|
+
if (m < 60) return `${m}分${s % 60 ? `${s % 60}秒` : ''}`;
|
|
114
|
+
const h = Math.floor(m / 60);
|
|
115
|
+
if (h < 24) return `${h}小时${m % 60 ? `${m % 60}分` : ''}`;
|
|
116
|
+
const d = Math.floor(h / 24);
|
|
117
|
+
return `${d}天${h % 24 ? `${h % 24}小时` : ''}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function ts(unix) {
|
|
121
|
+
const n = Number(unix);
|
|
122
|
+
if (!n || n <= 0) return '-';
|
|
123
|
+
const d = new Date(n * 1000);
|
|
124
|
+
const p = (x) => String(x).padStart(2, '0');
|
|
125
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const STATE_LABEL = {
|
|
129
|
+
provisioning: '创建中',
|
|
130
|
+
running: '运行中',
|
|
131
|
+
stopped: '已停机',
|
|
132
|
+
destroyed: '已销毁',
|
|
133
|
+
failed: '已失败',
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
export function stateText(state, bootState) {
|
|
137
|
+
const label = STATE_LABEL[state] || state || '-';
|
|
138
|
+
if (state === 'running') {
|
|
139
|
+
if (bootState === 'ready') return paint.green(label);
|
|
140
|
+
if (bootState === 'timeout') return paint.red(`${label}·启动超时`);
|
|
141
|
+
if (bootState === 'booting') return paint.yellow(`${label}·启动中`);
|
|
142
|
+
return paint.yellow(label);
|
|
143
|
+
}
|
|
144
|
+
if (state === 'provisioning') return paint.yellow(label);
|
|
145
|
+
if (state === 'failed') return paint.red(label);
|
|
146
|
+
if (state === 'destroyed') return paint.gray(label);
|
|
147
|
+
return label;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const BILLING_LABEL = {
|
|
151
|
+
'on-demand': '按量',
|
|
152
|
+
daily: '包日',
|
|
153
|
+
weekly: '包周',
|
|
154
|
+
monthly: '包月',
|
|
155
|
+
yearly: '包年',
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
export function billingText(mode) {
|
|
159
|
+
return BILLING_LABEL[mode] || mode || '-';
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// 轮询用的可读进度
|
|
163
|
+
export function progressLine(detail, elapsedSec) {
|
|
164
|
+
const parts = [`${paint.dim('已等待')} ${duration(elapsedSec)}`];
|
|
165
|
+
if (detail.state === 'provisioning') parts.push('虚拟机创建中…');
|
|
166
|
+
else if (detail.state === 'running' && detail.boot_state === 'booting') parts.push('系统启动中…');
|
|
167
|
+
else if (detail.state === 'running' && detail.boot_state === 'ready') parts.push('就绪');
|
|
168
|
+
else if (detail.state === 'failed') parts.push(paint.red('创建失败'));
|
|
169
|
+
else parts.push(`${detail.state}/${detail.boot_state || '-'}`);
|
|
170
|
+
return parts.join(' ');
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 建机进度的三态判定:与文档里的判定表保持一致
|
|
174
|
+
export function pollDecision(detail) {
|
|
175
|
+
const { state, boot_state: boot } = detail;
|
|
176
|
+
if (state === 'provisioning') return 'continue';
|
|
177
|
+
if (state === 'running') {
|
|
178
|
+
if (boot === 'ready') return 'done';
|
|
179
|
+
if (boot === 'timeout') return 'fail';
|
|
180
|
+
return 'continue';
|
|
181
|
+
}
|
|
182
|
+
if (state === 'failed' || state === 'destroyed') return 'fail';
|
|
183
|
+
if (state === 'stopped') return 'done';
|
|
184
|
+
return 'continue';
|
|
185
|
+
}
|
package/src/rentargs.mjs
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// `dotop-gpu rent` 的参数解析与「按名字/id 挑一条」的匹配规则。
|
|
2
|
+
//
|
|
3
|
+
// 目标:任何一步都能用命令行直接指定,不需要交互。两种用法:
|
|
4
|
+
// 1. 全参数 + --yes → 完全非交互,适合脚本/CI;
|
|
5
|
+
// 2. 只给一部分 → 已给的那几步跳过,剩下的照常问(混合模式)。
|
|
6
|
+
//
|
|
7
|
+
// 这里全是纯函数,不联网、不读配置,方便单独测试。
|
|
8
|
+
|
|
9
|
+
export const BILLING_MODES = ['on-demand', 'daily', 'weekly', 'monthly', 'yearly'];
|
|
10
|
+
|
|
11
|
+
// 计费模式的简写别名。用户记不住 on-demand 有没有横杠、daily 还是 day。
|
|
12
|
+
const BILLING_ALIASES = {
|
|
13
|
+
'': 'on-demand',
|
|
14
|
+
ondemand: 'on-demand',
|
|
15
|
+
'on-demand': 'on-demand',
|
|
16
|
+
instant: 'on-demand',
|
|
17
|
+
meter: 'on-demand',
|
|
18
|
+
metered: 'on-demand',
|
|
19
|
+
按量: 'on-demand',
|
|
20
|
+
day: 'daily',
|
|
21
|
+
daily: 'daily',
|
|
22
|
+
日: 'daily',
|
|
23
|
+
包日: 'daily',
|
|
24
|
+
week: 'weekly',
|
|
25
|
+
weekly: 'weekly',
|
|
26
|
+
周: 'weekly',
|
|
27
|
+
包周: 'weekly',
|
|
28
|
+
month: 'monthly',
|
|
29
|
+
monthly: 'monthly',
|
|
30
|
+
月: 'monthly',
|
|
31
|
+
包月: 'monthly',
|
|
32
|
+
year: 'yearly',
|
|
33
|
+
yearly: 'yearly',
|
|
34
|
+
annual: 'yearly',
|
|
35
|
+
年: 'yearly',
|
|
36
|
+
包年: 'yearly',
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// 把这些 flag 当作「带值」,解析时吃掉后面一个 token。
|
|
40
|
+
const VALUE_FLAGS = new Map([
|
|
41
|
+
['--zone', 'zone'],
|
|
42
|
+
['--zone-key', 'zone'],
|
|
43
|
+
['--plan', 'plan'],
|
|
44
|
+
['--plan-id', 'plan'],
|
|
45
|
+
['--image', 'image'],
|
|
46
|
+
['--image-id', 'image'],
|
|
47
|
+
['--ssh-key', 'sshKey'],
|
|
48
|
+
['--ssh', 'sshKey'],
|
|
49
|
+
['--key-id', 'sshKey'],
|
|
50
|
+
['--billing', 'billing'],
|
|
51
|
+
['--billing-mode', 'billing'],
|
|
52
|
+
['--count', 'count'],
|
|
53
|
+
['--periods', 'count'],
|
|
54
|
+
['--commitment-count', 'count'],
|
|
55
|
+
['--user-data', 'userData'],
|
|
56
|
+
['--idem', 'idem'],
|
|
57
|
+
['--idempotency-key', 'idem'],
|
|
58
|
+
]);
|
|
59
|
+
|
|
60
|
+
const BOOL_FLAGS = new Map([
|
|
61
|
+
['--yes', 'yes'],
|
|
62
|
+
['-y', 'yes'],
|
|
63
|
+
['--dry-run', 'dryRun'],
|
|
64
|
+
['--quote-only', 'dryRun'],
|
|
65
|
+
['--no-wait', 'noWait'],
|
|
66
|
+
['--no-poll', 'noWait'],
|
|
67
|
+
['--auto-renew', 'autoRenew'],
|
|
68
|
+
['--no-auto-renew', 'noAutoRenew'],
|
|
69
|
+
['--quick', 'quick'],
|
|
70
|
+
['-q', 'quick'],
|
|
71
|
+
]);
|
|
72
|
+
|
|
73
|
+
export class RentArgError extends Error {
|
|
74
|
+
constructor(message) {
|
|
75
|
+
super(message);
|
|
76
|
+
this.name = 'RentArgError';
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 解析 rent 子命令的参数。
|
|
81
|
+
//
|
|
82
|
+
// 返回:
|
|
83
|
+
// { zone, plan, image, sshKey, billing, count, userData, idem,
|
|
84
|
+
// yes, dryRun, noWait, autoRenew, quick, unknown: [...] }
|
|
85
|
+
//
|
|
86
|
+
// 未出现的字段一律为 undefined —— 「没指定」和「指定成默认值」必须能区分开,
|
|
87
|
+
// 否则混合模式下无法判断该不该跳过那一步。
|
|
88
|
+
export function parseRentArgs(args = []) {
|
|
89
|
+
const out = { unknown: [] };
|
|
90
|
+
const argv = normalizeDashedValues(args);
|
|
91
|
+
|
|
92
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
93
|
+
let a = argv[i];
|
|
94
|
+
|
|
95
|
+
// --flag=value 形式先拆开
|
|
96
|
+
let inlineValue;
|
|
97
|
+
const eq = a.indexOf('=');
|
|
98
|
+
if (a.startsWith('--') && eq > 0) {
|
|
99
|
+
inlineValue = a.slice(eq + 1);
|
|
100
|
+
a = a.slice(0, eq);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (BOOL_FLAGS.has(a)) {
|
|
104
|
+
if (inlineValue !== undefined) {
|
|
105
|
+
// --yes=false 这种写法不常见,但不要静默忽略
|
|
106
|
+
out[BOOL_FLAGS.get(a)] = !/^(0|false|no|off)$/i.test(inlineValue);
|
|
107
|
+
} else {
|
|
108
|
+
out[BOOL_FLAGS.get(a)] = true;
|
|
109
|
+
}
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (VALUE_FLAGS.has(a)) {
|
|
114
|
+
const field = VALUE_FLAGS.get(a);
|
|
115
|
+
const value = inlineValue !== undefined ? inlineValue : argv[i + 1];
|
|
116
|
+
if (value === undefined) {
|
|
117
|
+
throw new RentArgError(`参数 ${a} 后面缺少值`);
|
|
118
|
+
}
|
|
119
|
+
if (inlineValue === undefined) i += 1;
|
|
120
|
+
out[field] = value;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// 不认识的 flag:只记它自己,并把紧跟的值一并吃掉,
|
|
125
|
+
// 否则 `--bogus 1` 会报成「不认识的参数:--bogus 1」,看着像参数名带空格。
|
|
126
|
+
if (a.startsWith('-')) {
|
|
127
|
+
out.unknown.push(a);
|
|
128
|
+
if (inlineValue === undefined && i + 1 < argv.length && !argv[i + 1].startsWith('-')) {
|
|
129
|
+
i += 1;
|
|
130
|
+
}
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
out.unknown.push(a);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (out.count !== undefined) {
|
|
137
|
+
const n = Number.parseInt(out.count, 10);
|
|
138
|
+
if (!Number.isInteger(n) || n < 1) throw new RentArgError('--count 必须是正整数');
|
|
139
|
+
if (n > 99) throw new RentArgError('--count 最多 99 期(服务端上限)');
|
|
140
|
+
out.count = n;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (out.billing !== undefined) {
|
|
144
|
+
const mode = normalizeBilling(out.billing);
|
|
145
|
+
if (!mode) {
|
|
146
|
+
throw new RentArgError(
|
|
147
|
+
`--billing 不认识 ${out.billing},可用:${BILLING_MODES.join(' / ')}`,
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
out.billing = mode;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (out.count !== undefined && out.count > 1 && out.billing === 'on-demand') {
|
|
154
|
+
throw new RentArgError('--count 只对周期计费有效,按量计费没有「期数」');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (out.noAutoRenew) {
|
|
158
|
+
out.autoRenew = false;
|
|
159
|
+
delete out.noAutoRenew;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return out;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// 计费模式归一化(和 Go 侧 gpu.NormalizeBillingMode 保持一致)
|
|
166
|
+
export function normalizeBilling(raw) {
|
|
167
|
+
const key = String(raw ?? '').trim().toLowerCase();
|
|
168
|
+
return BILLING_ALIASES[key] || null;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// PowerShell 会把 `--billing=on-demand` 当整体传过来没问题,
|
|
172
|
+
// 但 `--count 3` 在某些包装脚本里会变成 `--count`s 3`,
|
|
173
|
+
// 这里只做一件事:把 `--flag=` 后面的空值当成缺值,交给上层报错。
|
|
174
|
+
function normalizeDashedValues(args) {
|
|
175
|
+
return args.map((a) => String(a));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// 按「id 或名字」从列表里挑一条。返回 { item } 或 { error }。
|
|
179
|
+
//
|
|
180
|
+
// 匹配顺序:纯数字按 id → 名称精确(忽略大小写)→ 唯一子串(忽略大小写)→ 指纹前缀。
|
|
181
|
+
// 多个候选时**不猜**,把候选列出来让调用方报错——猜错就是拿别的规格下单了。
|
|
182
|
+
export function pickBySpec(items, spec, { idKey = 'id', nameKey = 'name', extraKeys = [] } = {}) {
|
|
183
|
+
const list = Array.isArray(items) ? items : [];
|
|
184
|
+
const raw = String(spec ?? '').trim();
|
|
185
|
+
if (!raw) return { error: '没有指定' };
|
|
186
|
+
if (list.length === 0) return { error: '可选列表为空' };
|
|
187
|
+
|
|
188
|
+
// 1) 纯数字 = id
|
|
189
|
+
if (/^\d+$/.test(raw)) {
|
|
190
|
+
const id = Number.parseInt(raw, 10);
|
|
191
|
+
const hit = list.find((x) => Number(x[idKey]) === id);
|
|
192
|
+
if (hit) return { item: hit };
|
|
193
|
+
return { error: `没有 id=${id} 的项` };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const needle = raw.toLowerCase();
|
|
197
|
+
const nameOf = (x) => String(x[nameKey] ?? '');
|
|
198
|
+
|
|
199
|
+
// 2) 名称精确
|
|
200
|
+
const exact = list.filter((x) => nameOf(x).toLowerCase() === needle);
|
|
201
|
+
if (exact.length === 1) return { item: exact[0] };
|
|
202
|
+
if (exact.length > 1) return { error: `名称「${raw}」对应多条`, candidates: exact };
|
|
203
|
+
|
|
204
|
+
// 3) 名称唯一子串
|
|
205
|
+
const partial = list.filter((x) => nameOf(x).toLowerCase().includes(needle));
|
|
206
|
+
if (partial.length === 1) return { item: partial[0] };
|
|
207
|
+
if (partial.length > 1) return { error: `「${raw}」匹配到多条`, candidates: partial };
|
|
208
|
+
|
|
209
|
+
// 4) 附加字段(指纹等)前缀
|
|
210
|
+
for (const key of extraKeys) {
|
|
211
|
+
const hits = list.filter((x) => String(x[key] ?? '').toLowerCase().startsWith(needle));
|
|
212
|
+
if (hits.length === 1) return { item: hits[0] };
|
|
213
|
+
if (hits.length > 1) return { error: `「${raw}」匹配到多条`, candidates: hits };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return { error: `找不到「${raw}」` };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// 把一个 spec 匹配结果转成给人看的错误消息。
|
|
220
|
+
export function describePickError(label, spec, result) {
|
|
221
|
+
const lines = [`${label}「${spec}」无法唯一确定:${result.error}`];
|
|
222
|
+
const cands = result.candidates || [];
|
|
223
|
+
if (cands.length > 0) {
|
|
224
|
+
lines.push(' 候选:');
|
|
225
|
+
for (const c of cands.slice(0, 10)) {
|
|
226
|
+
lines.push(` id=${c.id} ${c.name || c.rental_no || ''}`);
|
|
227
|
+
}
|
|
228
|
+
if (cands.length > 10) lines.push(` ……还有 ${cands.length - 10} 条`);
|
|
229
|
+
lines.push(' 请改用 id,或写更完整的名字。');
|
|
230
|
+
}
|
|
231
|
+
return lines.join('\n');
|
|
232
|
+
}
|
package/src/rentflow.mjs
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// 把 `rent` 的命令行参数落实成向导能直接用的实体对象。
|
|
2
|
+
//
|
|
3
|
+
// 分工:
|
|
4
|
+
// rentargs.mjs —— 纯文本解析(`--zone z1` → `{ zone: 'z1' }`),可离线单测;
|
|
5
|
+
// rentflow.mjs —— 需要联网的部分(z1 → 真正的 zone 对象)+ 组合校验。
|
|
6
|
+
//
|
|
7
|
+
// 一个关键设计:**只给了部分参数也能跑**。给了 --plan 但没给 --zone 时,
|
|
8
|
+
// 这里会反查这个规格属于哪个可用区,把它补上,而不是让用户再补一遍。
|
|
9
|
+
// 补不出来(同名规格在多个区都有)才报错要求显式指定。
|
|
10
|
+
import { pickBySpec, describePickError, RentArgError, BILLING_MODES } from './rentargs.mjs';
|
|
11
|
+
|
|
12
|
+
// 把 opts 解析成 { zone, plan, image, sshKey, billing, count, userData, idem, autoRenew }。
|
|
13
|
+
// 未出现的字段保持 undefined —— 向导靠这个区分「没指定」和「指定成默认值」。
|
|
14
|
+
export async function buildPreset(client, opts) {
|
|
15
|
+
const preset = {};
|
|
16
|
+
|
|
17
|
+
let zones = null;
|
|
18
|
+
const loadZones = async () => {
|
|
19
|
+
if (zones) return zones;
|
|
20
|
+
zones = (await client.listZones()).items || [];
|
|
21
|
+
return zones;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// ── 可用区 ──
|
|
25
|
+
if (opts.zone !== undefined) {
|
|
26
|
+
preset.zone = matchZone(await loadZones(), opts.zone);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// ── 规格(可能需要反查所属可用区)──
|
|
30
|
+
let planZoneKey = '';
|
|
31
|
+
if (opts.plan !== undefined) {
|
|
32
|
+
const found = await findPlan(client, await loadZones(), opts.plan, preset.zone);
|
|
33
|
+
preset.plan = found.plan;
|
|
34
|
+
planZoneKey = found.zone.zone_key;
|
|
35
|
+
if (!preset.zone) preset.zone = found.zone;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// ── 镜像(同样可能需要反查所属可用区)──
|
|
39
|
+
let imageZoneKey = '';
|
|
40
|
+
if (opts.image !== undefined) {
|
|
41
|
+
const found = await findImage(client, await loadZones(), opts.image, preset.zone);
|
|
42
|
+
preset.image = found.image;
|
|
43
|
+
imageZoneKey = found.zone.zone_key;
|
|
44
|
+
if (!preset.zone) preset.zone = found.zone;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// 规格和镜像若分别落在不同可用区,说明用户给的两项互相矛盾
|
|
48
|
+
if (planZoneKey && imageZoneKey && planZoneKey !== imageZoneKey) {
|
|
49
|
+
throw new RentArgError(
|
|
50
|
+
`规格属于 ${planZoneKey},镜像属于 ${imageZoneKey},两者不在同一个可用区。请加 --zone 指定。`,
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// ── 公钥 ──
|
|
55
|
+
if (opts.sshKey !== undefined) {
|
|
56
|
+
const keys = (await client.listSSHKeys()).items || [];
|
|
57
|
+
if (keys.length === 0) {
|
|
58
|
+
throw new RentArgError('平台上还没有 SSH 公钥,先 `dotop-gpu keys add` 上传一把');
|
|
59
|
+
}
|
|
60
|
+
const r = pickBySpec(keys, opts.sshKey, {
|
|
61
|
+
idKey: 'id',
|
|
62
|
+
nameKey: 'name',
|
|
63
|
+
extraKeys: ['fingerprint'],
|
|
64
|
+
});
|
|
65
|
+
if (!r.item) {
|
|
66
|
+
throw new RentArgError(
|
|
67
|
+
`${describePickError('公钥', opts.sshKey, r)}\n 可用:${keys.map((k) => `${k.id}(${k.name})`).join(' / ')}`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
preset.sshKey = r.item;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ── 直通字段 ──
|
|
74
|
+
if (opts.billing !== undefined) preset.billing = opts.billing;
|
|
75
|
+
if (opts.count !== undefined) preset.count = opts.count;
|
|
76
|
+
if (opts.userData !== undefined) preset.userData = opts.userData;
|
|
77
|
+
if (opts.idem !== undefined) preset.idem = opts.idem;
|
|
78
|
+
if (opts.autoRenew !== undefined) preset.autoRenew = opts.autoRenew;
|
|
79
|
+
|
|
80
|
+
return preset;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// 可用区匹配:zone_key 优先(z1 这种才是主键名),其次名字/id/子串。
|
|
84
|
+
function matchZone(all, spec) {
|
|
85
|
+
const raw = String(spec).trim().toLowerCase();
|
|
86
|
+
const byKey = all.find((z) => String(z.zone_key).toLowerCase() === raw);
|
|
87
|
+
if (byKey) {
|
|
88
|
+
assertEnabled(byKey);
|
|
89
|
+
return byKey;
|
|
90
|
+
}
|
|
91
|
+
const r = pickBySpec(all, spec, { idKey: 'id', nameKey: 'name' });
|
|
92
|
+
if (!r.item) {
|
|
93
|
+
throw new RentArgError(
|
|
94
|
+
`${describePickError('可用区', spec, r)}\n 可用:${all.map((z) => `${z.zone_key}(${z.name})`).join(' / ')}`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
assertEnabled(r.item);
|
|
98
|
+
return r.item;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function assertEnabled(zone) {
|
|
102
|
+
if (zone.state && zone.state !== 'enabled') {
|
|
103
|
+
throw new RentArgError(`可用区 ${zone.zone_key} 当前状态是 ${zone.state},不能下单`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// 在(一个或全部)可用区里找规格。
|
|
108
|
+
//
|
|
109
|
+
// PlanView 里没有 zone_key,只能逐区查 gpu-types。已经知道可用区时只查那一个,
|
|
110
|
+
// 避免「只给 --plan 就打了 N 个请求」。
|
|
111
|
+
async function findPlan(client, zones, spec, knownZone) {
|
|
112
|
+
const scope = knownZone ? [knownZone] : zones;
|
|
113
|
+
const hits = [];
|
|
114
|
+
for (const z of scope) {
|
|
115
|
+
const groups = (await client.listGpuTypes(z.zone_key)).items || [];
|
|
116
|
+
const plans = groups.flatMap((g) => g.plans || []);
|
|
117
|
+
const r = pickBySpec(plans, spec, { idKey: 'id', nameKey: 'name' });
|
|
118
|
+
if (r.item) hits.push({ zone: z, plan: r.item });
|
|
119
|
+
else if (r.candidates) for (const c of r.candidates) hits.push({ zone: z, plan: c });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (hits.length === 1) return hits[0];
|
|
123
|
+
if (hits.length === 0) {
|
|
124
|
+
const where = knownZone ? `可用区 ${knownZone.zone_key} 里` : '任何可用区里';
|
|
125
|
+
const hint = knownZone
|
|
126
|
+
? `\n 该区可用规格:${await listPlanNames(client, knownZone)}`
|
|
127
|
+
: `\n 先 dotop-gpu rent --zone <区> --plan ${spec} 只查一个区更快。`;
|
|
128
|
+
throw new RentArgError(`${where}找不到规格「${spec}」${hint}`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// 同一个区内也匹配到多条 → 是「名字太模糊」,让用户写全或改用 id
|
|
132
|
+
const zoneKeys = new Set(hits.map((h) => h.zone.zone_key));
|
|
133
|
+
if (zoneKeys.size === 1) {
|
|
134
|
+
const list = hits.map((h) => ` id=${h.plan.id} ${h.plan.name}`).join('\n');
|
|
135
|
+
throw new RentArgError(`规格「${spec}」在 ${hits[0].zone.zone_key} 里匹配到多条,改用 id 更准确:\n${list}`);
|
|
136
|
+
}
|
|
137
|
+
const list = hits.map((h) => ` ${h.zone.zone_key} id=${h.plan.id} ${h.plan.name}`).join('\n');
|
|
138
|
+
throw new RentArgError(`规格「${spec}」在多个可用区都存在,请加 --zone 指定:\n${list}`);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// 报错时把该区可选的规格名带上,省得用户再跑一次去查。
|
|
142
|
+
async function listPlanNames(client, zone) {
|
|
143
|
+
const groups = (await client.listGpuTypes(zone.zone_key)).items || [];
|
|
144
|
+
const plans = groups.flatMap((g) => g.plans || []);
|
|
145
|
+
if (plans.length === 0) return '(该区没有可售规格)';
|
|
146
|
+
return plans.map((p) => `${p.id}(${p.name})`).join(' / ');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function findImage(client, zones, spec, knownZone) {
|
|
150
|
+
const scope = knownZone ? [knownZone] : zones;
|
|
151
|
+
const hits = [];
|
|
152
|
+
for (const z of scope) {
|
|
153
|
+
const images = (await client.listImages(z.zone_key)).items || [];
|
|
154
|
+
const r = pickBySpec(images, spec, { idKey: 'id', nameKey: 'name' });
|
|
155
|
+
if (r.item) hits.push({ zone: z, image: r.item });
|
|
156
|
+
else if (r.candidates) for (const c of r.candidates) hits.push({ zone: z, image: c });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (hits.length === 1) return hits[0];
|
|
160
|
+
if (hits.length === 0) {
|
|
161
|
+
const where = knownZone ? `可用区 ${knownZone.zone_key}` : '任何可用区';
|
|
162
|
+
throw new RentArgError(`${where}都找不到镜像「${spec}」`);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const zoneKeys = new Set(hits.map((h) => h.zone.zone_key));
|
|
166
|
+
if (zoneKeys.size === 1) {
|
|
167
|
+
const list = hits.map((h) => ` id=${h.image.id} ${h.image.name}`).join('\n');
|
|
168
|
+
throw new RentArgError(`镜像「${spec}」在 ${hits[0].zone.zone_key} 里匹配到多条,改用 id 更准确:\n${list}`);
|
|
169
|
+
}
|
|
170
|
+
const list = hits.map((h) => ` ${h.zone.zone_key} id=${h.image.id} ${h.image.name}`).join('\n');
|
|
171
|
+
throw new RentArgError(`镜像「${spec}」在多个可用区都存在,请加 --zone 指定:\n${list}`);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// 组合校验:把「只给 --count 没给 --billing」这类错误提前挡掉,
|
|
175
|
+
// 而不是让用户在向导里做一半才发现。
|
|
176
|
+
export function validateCombo(opts) {
|
|
177
|
+
if (opts.count !== undefined && opts.billing === undefined) {
|
|
178
|
+
throw new RentArgError('给了 --count 就必须同时给 --billing');
|
|
179
|
+
}
|
|
180
|
+
if (opts.count !== undefined && opts.billing === 'on-demand') {
|
|
181
|
+
throw new RentArgError('按量计费没有「期数」,去掉 --count');
|
|
182
|
+
}
|
|
183
|
+
if (opts.billing !== undefined && !BILLING_MODES.includes(opts.billing)) {
|
|
184
|
+
throw new RentArgError(`--billing 只能是 ${BILLING_MODES.join(' / ')}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
package/src/sshkeys.mjs
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// 本机 SSH 公钥发现与上传。
|
|
2
|
+
//
|
|
3
|
+
// 只读 ~/.ssh 下的 *.pub,绝不读私钥,也绝不把内容写到任何地方(除上传给平台)。
|
|
4
|
+
import { readdirSync, readFileSync, existsSync } from 'node:fs';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
const SSH_DIR_CANDIDATES = [
|
|
9
|
+
process.env.SSH_DIR,
|
|
10
|
+
join(homedir(), '.ssh'),
|
|
11
|
+
].filter(Boolean);
|
|
12
|
+
|
|
13
|
+
export function sshDir() {
|
|
14
|
+
for (const dir of SSH_DIR_CANDIDATES) {
|
|
15
|
+
if (existsSync(dir)) return dir;
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// 返回 [{ file, name, publicKey, comment }]
|
|
21
|
+
export function scanLocalKeys() {
|
|
22
|
+
const dir = sshDir();
|
|
23
|
+
if (!dir) return [];
|
|
24
|
+
let entries;
|
|
25
|
+
try {
|
|
26
|
+
entries = readdirSync(dir);
|
|
27
|
+
} catch {
|
|
28
|
+
return [];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const out = [];
|
|
32
|
+
for (const file of entries) {
|
|
33
|
+
if (!file.endsWith('.pub')) continue;
|
|
34
|
+
const full = join(dir, file);
|
|
35
|
+
let text;
|
|
36
|
+
try {
|
|
37
|
+
text = readFileSync(full, 'utf8');
|
|
38
|
+
} catch {
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const line = text.split(/\r?\n/).find((l) => l.trim() && !l.trim().startsWith('#')) || '';
|
|
42
|
+
const trimmed = line.trim();
|
|
43
|
+
if (!trimmed) continue;
|
|
44
|
+
if (!/^(ssh-|ecdsa-|sk-)/.test(trimmed)) continue;
|
|
45
|
+
const parts = trimmed.split(/\s+/);
|
|
46
|
+
out.push({
|
|
47
|
+
file: full,
|
|
48
|
+
name: file.replace(/\.pub$/, ''),
|
|
49
|
+
publicKey: trimmed,
|
|
50
|
+
comment: parts.slice(2).join(' ') || '',
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// OpenSSH 指纹:SHA256:<base64(sha256(blob))>,与平台返回的格式一致
|
|
57
|
+
import { createHash } from 'node:crypto';
|
|
58
|
+
|
|
59
|
+
export function fingerprintOf(publicKey) {
|
|
60
|
+
const parts = String(publicKey || '').trim().split(/\s+/);
|
|
61
|
+
if (parts.length < 2) return '';
|
|
62
|
+
try {
|
|
63
|
+
const blob = Buffer.from(parts[1], 'base64');
|
|
64
|
+
const digest = createHash('sha256').update(blob).digest('base64').replace(/=+$/, '');
|
|
65
|
+
return `SHA256:${digest}`;
|
|
66
|
+
} catch {
|
|
67
|
+
return '';
|
|
68
|
+
}
|
|
69
|
+
}
|