@dongnanyang/deploy-cli 0.7.0 → 0.8.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/dist/bin.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
const argv = process.argv.slice(2);
|
|
3
3
|
if (argv.length === 0 || argv[0] === "tui") await import("./main.js");
|
|
4
4
|
else {
|
|
5
|
-
const cli = await import("./cli-
|
|
5
|
+
const cli = await import("./cli-CP-jnPz3.js");
|
|
6
6
|
process.exitCode = await cli.main(argv);
|
|
7
7
|
}
|
|
8
8
|
//#endregion
|
|
@@ -1,157 +1,30 @@
|
|
|
1
|
-
import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-
|
|
1
|
+
import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-DuBKPLi2.js";
|
|
2
2
|
import { readFileSync } from "fs";
|
|
3
3
|
import { resolve } from "path";
|
|
4
|
-
import { parse, stringify } from "yaml";
|
|
5
4
|
import { accessSync, constants, existsSync as existsSync$1, lstatSync, readFileSync as readFileSync$1, readdirSync as readdirSync$1, renameSync, symlinkSync, unlinkSync, writeFileSync as writeFileSync$1 } from "node:fs";
|
|
6
|
-
import { join as join$1, resolve as resolve$1 } from "node:path";
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
"compose",
|
|
11
|
-
"image",
|
|
12
|
-
"static"
|
|
13
|
-
];
|
|
14
|
-
const DEFAULT_COMPOSE_FILE = "docker-compose.yml";
|
|
15
|
-
const VALID_SSL = [
|
|
16
|
-
"none",
|
|
17
|
-
"acme",
|
|
18
|
-
"custom"
|
|
19
|
-
];
|
|
20
|
-
const VALID_UPDATE = ["git-pull", "none"];
|
|
21
|
-
/** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
|
|
22
|
-
var ProjectConfigError = class extends Error {
|
|
23
|
-
field;
|
|
24
|
-
constructor(message, field) {
|
|
25
|
-
super(message);
|
|
26
|
-
this.name = "ProjectConfigError";
|
|
27
|
-
this.field = field;
|
|
28
|
-
}
|
|
29
|
-
};
|
|
30
|
-
/** 读取 <dir>/deploy.yaml 并校验,失败抛 ProjectConfigError */
|
|
31
|
-
function loadProject(dir) {
|
|
32
|
-
const yamlPath = resolve(dir, "deploy.yaml");
|
|
33
|
-
let raw;
|
|
34
|
-
try {
|
|
35
|
-
raw = readFileSync(yamlPath, "utf-8");
|
|
36
|
-
} catch (error) {
|
|
37
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
38
|
-
if (error?.code === "ENOENT") throw new ProjectConfigError(`缺少 deploy.yaml: ${yamlPath}`);
|
|
39
|
-
throw new ProjectConfigError(`读取 deploy.yaml 失败: ${yamlPath}: ${reason}`);
|
|
40
|
-
}
|
|
41
|
-
let parsed;
|
|
42
|
-
try {
|
|
43
|
-
parsed = parse(raw);
|
|
44
|
-
} catch (error) {
|
|
45
|
-
throw new ProjectConfigError(`deploy.yaml 解析失败: ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
46
|
-
}
|
|
47
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
|
|
48
|
-
return validate(parsed);
|
|
49
|
-
}
|
|
50
|
-
/** 校验并规范化 deploy.yaml 模型:name → type 合法性 → 类型必填字段 → nginx.domain 非空 → deploy 段值域 */
|
|
51
|
-
function validate(raw) {
|
|
52
|
-
const name = raw.name;
|
|
53
|
-
if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
|
|
54
|
-
const type = raw.type;
|
|
55
|
-
if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
|
|
56
|
-
if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
|
|
57
|
-
if (type === "image" && (typeof raw.image !== "string" || raw.image.trim() === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
|
|
58
|
-
if (type === "static" && (typeof raw.root !== "string" || raw.root.trim() === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
|
|
59
|
-
if (raw.nginx !== void 0 && raw.nginx !== null) {
|
|
60
|
-
const nginx = raw.nginx;
|
|
61
|
-
if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
|
|
62
|
-
const n = nginx;
|
|
63
|
-
if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
|
|
64
|
-
if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
|
|
65
|
-
}
|
|
66
|
-
if (raw.deploy !== void 0 && raw.deploy !== null) {
|
|
67
|
-
const deploy = raw.deploy;
|
|
68
|
-
if (typeof deploy !== "object" || Array.isArray(deploy)) throw new ProjectConfigError("deploy 应为对象", "deploy");
|
|
69
|
-
const dp = deploy;
|
|
70
|
-
if (dp.update !== void 0 && dp.update !== null) {
|
|
71
|
-
if (typeof dp.update !== "string" || !VALID_UPDATE.includes(dp.update)) throw new ProjectConfigError(`deploy.update 非法: ${JSON.stringify(dp.update)},合法值: git-pull | none(不设=不自动更新)`, "deploy.update");
|
|
72
|
-
}
|
|
73
|
-
if (dp.build !== void 0 && dp.build !== null && typeof dp.build !== "string") throw new ProjectConfigError("deploy.build 应为字符串(构建命令)", "deploy.build");
|
|
74
|
-
for (const hook of ["pre", "post"]) {
|
|
75
|
-
const hooks = dp[hook];
|
|
76
|
-
if (hooks !== void 0 && hooks !== null && (!Array.isArray(hooks) || hooks.some((c) => typeof c !== "string"))) throw new ProjectConfigError(`deploy.${hook} 应为字符串数组(命令列表)`, `deploy.${hook}`);
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
const d = raw;
|
|
80
|
-
if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
|
|
81
|
-
return d;
|
|
82
|
-
}
|
|
83
|
-
/** 列出注册表项目;单个坏配置降级 {config:null,error},不中断其余项目 */
|
|
84
|
-
function listProjects(cfg) {
|
|
85
|
-
return cfg.projects.map((project) => {
|
|
86
|
-
try {
|
|
87
|
-
return {
|
|
88
|
-
name: project.name,
|
|
89
|
-
path: project.path,
|
|
90
|
-
config: loadProject(project.path)
|
|
91
|
-
};
|
|
92
|
-
} catch (error) {
|
|
93
|
-
return {
|
|
94
|
-
name: project.name,
|
|
95
|
-
path: project.path,
|
|
96
|
-
config: null,
|
|
97
|
-
error: error instanceof Error ? error.message : String(error)
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
/** 读 <dir>/deploy.yaml 取 name 注册进 cfg.projects(不落盘,由调用方 saveConfig) */
|
|
103
|
-
function addProject(cfg, dir) {
|
|
104
|
-
const config = loadProject(dir);
|
|
105
|
-
const byName = cfg.projects.find((p) => p.name === config.name);
|
|
106
|
-
if (byName) throw new Error(`项目已注册: ${config.name}(${byName.path}),请先 remove 再 add`);
|
|
107
|
-
const byPath = cfg.projects.find((p) => p.path === dir);
|
|
108
|
-
if (byPath) throw new Error(`路径已注册为项目 ${byPath.name}: ${dir}`);
|
|
109
|
-
const entry = {
|
|
110
|
-
name: config.name,
|
|
111
|
-
path: dir,
|
|
112
|
-
deployDir: "deploy"
|
|
113
|
-
};
|
|
114
|
-
return {
|
|
115
|
-
...cfg,
|
|
116
|
-
projects: [...cfg.projects, entry]
|
|
117
|
-
};
|
|
118
|
-
}
|
|
119
|
-
/** 从 cfg.projects 注销指定项目(不落盘,由调用方 saveConfig) */
|
|
120
|
-
function removeProject(cfg, name) {
|
|
121
|
-
const projects = cfg.projects.filter((p) => p.name !== name);
|
|
122
|
-
if (projects.length === cfg.projects.length) throw new Error(`未找到项目: ${name}`);
|
|
123
|
-
return {
|
|
124
|
-
...cfg,
|
|
125
|
-
projects
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
/** image 型生成的 docker-compose.yml 标记头(护栏 marker):既有同名文件无此头则拒绝覆盖(终审 M1:防绑架项目文件) */
|
|
129
|
-
const COMPOSE_MARKER = "# generated by deploy-cli — do not edit";
|
|
130
|
-
/** 既有文件内容是否带 COMPOSE_MARKER 头(首行) */
|
|
131
|
-
function hasComposeMarker(content) {
|
|
132
|
-
return content.split("\n", 1)[0]?.trim() === COMPOSE_MARKER;
|
|
133
|
-
}
|
|
134
|
-
/** image 型 → docker-compose.yml 文本(compose 中 env 的键名为 environment),首行带 COMPOSE_MARKER 标记头 */
|
|
135
|
-
function generateCompose(d) {
|
|
136
|
-
if (d.type !== "image") throw new ProjectConfigError(`generateCompose 仅支持 image 型项目(当前 type: ${d.type})`, "type");
|
|
137
|
-
if (typeof d.image !== "string" || d.image.trim() === "") throw new ProjectConfigError("image 型缺少必填字段: image", "image");
|
|
138
|
-
const service = { image: d.image };
|
|
139
|
-
if (d.ports && d.ports.length > 0) service.ports = d.ports;
|
|
140
|
-
if (d.volumes && d.volumes.length > 0) service.volumes = d.volumes;
|
|
141
|
-
if (d.env && Object.keys(d.env).length > 0) service.environment = d.env;
|
|
142
|
-
return `${COMPOSE_MARKER}\n${stringify({ services: { [d.name]: service } })}`;
|
|
143
|
-
}
|
|
144
|
-
//#endregion
|
|
5
|
+
import { dirname as dirname$1, join as join$1, resolve as resolve$1 } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { parse, stringify } from "yaml";
|
|
8
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
145
9
|
//#region src/core/exec.ts
|
|
146
10
|
/**
|
|
147
|
-
* stderr 摘要(失败信息用):优先命中 /error|fatal|failed/i 的行(至多尾 3 条),无命中取尾部 3 行。
|
|
148
|
-
* docker compose / nginx 等工具把进度打在 stderr 前部,取前部会挤掉真错误行(M1-T5 评审修复,R12
|
|
11
|
+
* stderr 摘要(失败信息用):优先命中 /error|fatal|failed|emerg|alert|crit/i 的行(至多尾 3 条),无命中取尾部 3 行。
|
|
12
|
+
* docker compose / nginx 等工具把进度打在 stderr 前部,取前部会挤掉真错误行(M1-T5 评审修复,R12 同缺陷同修);
|
|
13
|
+
* nginx 的 [emerg]/[alert]/[crit] 级别行同为错误行(M2-T2 #1 匹配集补齐)。
|
|
149
14
|
*/
|
|
150
15
|
function stderrSummary(stderr) {
|
|
151
16
|
const lines = stderr.trim().split("\n").filter((line) => line.trim() !== "");
|
|
152
|
-
const errors = lines.filter((line) => /error|fatal|failed/i.test(line));
|
|
17
|
+
const errors = lines.filter((line) => /error|fatal|failed|emerg|alert|crit/i.test(line));
|
|
153
18
|
return (errors.length > 0 ? errors.slice(-3) : lines.slice(-3)).join(" ");
|
|
154
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* 失败信息统一文案模板(M2-T2 #2 壳统一):命令原文 + exit 码 + stderr 摘要(无输出时注明)。
|
|
22
|
+
* docker.ts(execFailureMessage 复用/再导出)与 nginx.ts(execFailure 包裹 ExecError)共用本模板,R12 同口径。
|
|
23
|
+
*/
|
|
24
|
+
function execFailureMessage(cmd, args, result) {
|
|
25
|
+
const summary = stderrSummary(result.stderr);
|
|
26
|
+
return `命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`;
|
|
27
|
+
}
|
|
155
28
|
/** 仅 spawn 失败(ENOENT)与超时抛出 */
|
|
156
29
|
var ExecError = class extends Error {
|
|
157
30
|
result;
|
|
@@ -163,6 +36,39 @@ var ExecError = class extends Error {
|
|
|
163
36
|
};
|
|
164
37
|
/** 超时 SIGTERM 后等待子进程退出的宽限时长,超过则 SIGKILL */
|
|
165
38
|
const KILL_GRACE_MS = 3e3;
|
|
39
|
+
/** pid 的全部后代进程(ps pid/ppid 祖先链);ps 不可用时退化为空数组(只杀直接子进程,F8 尽力而为) */
|
|
40
|
+
function descendantPids(pid) {
|
|
41
|
+
let table;
|
|
42
|
+
try {
|
|
43
|
+
table = execFileSync("ps", ["-axo", "pid=,ppid="], { encoding: "utf-8" });
|
|
44
|
+
} catch {
|
|
45
|
+
return [];
|
|
46
|
+
}
|
|
47
|
+
const childrenOf = /* @__PURE__ */ new Map();
|
|
48
|
+
for (const line of table.split("\n")) {
|
|
49
|
+
const [p, pp] = line.trim().split(/\s+/);
|
|
50
|
+
const child = Number(p);
|
|
51
|
+
const parent = Number(pp);
|
|
52
|
+
if (!Number.isInteger(child) || !Number.isInteger(parent)) continue;
|
|
53
|
+
const list = childrenOf.get(parent);
|
|
54
|
+
if (list) list.push(child);
|
|
55
|
+
else childrenOf.set(parent, [child]);
|
|
56
|
+
}
|
|
57
|
+
const out = [];
|
|
58
|
+
const seen = /* @__PURE__ */ new Set([pid]);
|
|
59
|
+
const queue = [pid];
|
|
60
|
+
while (queue.length > 0) {
|
|
61
|
+
const current = queue.pop();
|
|
62
|
+
if (current === void 0) break;
|
|
63
|
+
for (const child of childrenOf.get(current) ?? []) {
|
|
64
|
+
if (seen.has(child)) continue;
|
|
65
|
+
seen.add(child);
|
|
66
|
+
out.push(child);
|
|
67
|
+
queue.push(child);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
166
72
|
/** 按 \n 切行缓冲,结束时补发无结尾换行的残行 */
|
|
167
73
|
function createLineBuffer(stream, onLine) {
|
|
168
74
|
let buffer = "";
|
|
@@ -210,6 +116,15 @@ async function run(cmd, args, opts = {}) {
|
|
|
210
116
|
});
|
|
211
117
|
const out = createLineBuffer("stdout", opts.onLine);
|
|
212
118
|
const err = createLineBuffer("stderr", opts.onLine);
|
|
119
|
+
/** 超时终止整个进程树(F8):bash -c 钩子/构建的孙进程随子进程一并 SIGTERM/SIGKILL,避免孤儿继续跑 */
|
|
120
|
+
const killTree = (signal) => {
|
|
121
|
+
if (child.pid !== void 0) for (const pid of descendantPids(child.pid)) try {
|
|
122
|
+
process.kill(pid, signal);
|
|
123
|
+
} catch {}
|
|
124
|
+
try {
|
|
125
|
+
child.kill(signal);
|
|
126
|
+
} catch {}
|
|
127
|
+
};
|
|
213
128
|
let settled = false;
|
|
214
129
|
let timedOut = false;
|
|
215
130
|
let timeoutNote = "";
|
|
@@ -217,8 +132,8 @@ async function run(cmd, args, opts = {}) {
|
|
|
217
132
|
const timeoutTimer = opts.timeoutMs ? setTimeout(() => {
|
|
218
133
|
timedOut = true;
|
|
219
134
|
timeoutNote = `timeout: ${cmdLine}\n`;
|
|
220
|
-
|
|
221
|
-
killTimer = setTimeout(() =>
|
|
135
|
+
killTree("SIGTERM");
|
|
136
|
+
killTimer = setTimeout(() => killTree("SIGKILL"), KILL_GRACE_MS);
|
|
222
137
|
}, opts.timeoutMs) : void 0;
|
|
223
138
|
child.stdout?.setEncoding("utf-8");
|
|
224
139
|
child.stderr?.setEncoding("utf-8");
|
|
@@ -257,113 +172,12 @@ async function run(cmd, args, opts = {}) {
|
|
|
257
172
|
});
|
|
258
173
|
}
|
|
259
174
|
//#endregion
|
|
260
|
-
//#region src/core/docker.ts
|
|
261
|
-
/** docker logs 的完整参数(CLI 报错展示与实际执行共用同一构造,保证命令原文一致) */
|
|
262
|
-
function logsArgs(idOrName, o) {
|
|
263
|
-
const args = ["logs"];
|
|
264
|
-
if (o?.tail !== void 0) args.push("--tail", String(o.tail));
|
|
265
|
-
if (o?.follow) args.push("--follow");
|
|
266
|
-
args.push(idOrName);
|
|
267
|
-
return args;
|
|
268
|
-
}
|
|
269
|
-
/** 失败信息:命令原文 + exit 码 + stderr 摘要(stderrSummary:优先错误行、否则尾部——docker compose 等工具把进度打在 stderr 前部) */
|
|
270
|
-
function execFailureMessage(cmd, args, result) {
|
|
271
|
-
const summary = stderrSummary(result.stderr);
|
|
272
|
-
return `命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`;
|
|
273
|
-
}
|
|
274
|
-
/** 把 Runner 的 (line, stream) 回调适配为 DockerApi 的 (l) => void */
|
|
275
|
-
function adaptOnLine(onLine) {
|
|
276
|
-
return onLine ? (line) => onLine(line) : void 0;
|
|
277
|
-
}
|
|
278
|
-
/** docker ps 一行 json → ContainerInfo;兼容真实 docker 的 ID 大写键与 brief 的 Id */
|
|
279
|
-
function parseContainerLine(line) {
|
|
280
|
-
let raw;
|
|
281
|
-
try {
|
|
282
|
-
raw = JSON.parse(line);
|
|
283
|
-
} catch (error) {
|
|
284
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
285
|
-
throw new Error(`解析 docker ps 输出失败: ${line}: ${reason}`);
|
|
286
|
-
}
|
|
287
|
-
return {
|
|
288
|
-
id: String(raw.ID ?? raw.Id ?? ""),
|
|
289
|
-
name: String(raw.Names ?? ""),
|
|
290
|
-
image: String(raw.Image ?? ""),
|
|
291
|
-
state: String(raw.State ?? ""),
|
|
292
|
-
status: String(raw.Status ?? ""),
|
|
293
|
-
ports: String(raw.Ports ?? "")
|
|
294
|
-
};
|
|
295
|
-
}
|
|
296
|
-
/** 以 shell-out 方式实现的 docker 操作集合 */
|
|
297
|
-
function createDocker(runner = run) {
|
|
298
|
-
return {
|
|
299
|
-
async listContainers(o) {
|
|
300
|
-
const args = ["ps"];
|
|
301
|
-
if (o?.all) args.push("-a");
|
|
302
|
-
if (o?.name) args.push("--filter", `name=${o.name}`);
|
|
303
|
-
args.push("--format", "{{json .}}");
|
|
304
|
-
const result = await runner("docker", args);
|
|
305
|
-
if (result.code !== 0) throw new Error(execFailureMessage("docker", args, result));
|
|
306
|
-
return result.stdout.split("\n").filter((line) => line.trim() !== "").map(parseContainerLine);
|
|
307
|
-
},
|
|
308
|
-
async logs(idOrName, o) {
|
|
309
|
-
return await runner("docker", logsArgs(idOrName, o), { onLine: adaptOnLine(o?.onLine) });
|
|
310
|
-
},
|
|
311
|
-
async composeUp(cwd, composeFile, o) {
|
|
312
|
-
const args = [
|
|
313
|
-
"compose",
|
|
314
|
-
"-f",
|
|
315
|
-
composeFile,
|
|
316
|
-
"up",
|
|
317
|
-
"-d"
|
|
318
|
-
];
|
|
319
|
-
if (o?.build) args.push("--build");
|
|
320
|
-
return await runner("docker", args, {
|
|
321
|
-
cwd,
|
|
322
|
-
onLine: adaptOnLine(o?.onLine)
|
|
323
|
-
});
|
|
324
|
-
},
|
|
325
|
-
async composeDown(cwd, composeFile, o) {
|
|
326
|
-
return await runner("docker", [
|
|
327
|
-
"compose",
|
|
328
|
-
"-f",
|
|
329
|
-
composeFile,
|
|
330
|
-
"down"
|
|
331
|
-
], {
|
|
332
|
-
cwd,
|
|
333
|
-
onLine: adaptOnLine(o?.onLine)
|
|
334
|
-
});
|
|
335
|
-
},
|
|
336
|
-
async composeBuild(cwd, composeFile, o) {
|
|
337
|
-
return await runner("docker", [
|
|
338
|
-
"compose",
|
|
339
|
-
"-f",
|
|
340
|
-
composeFile,
|
|
341
|
-
"build"
|
|
342
|
-
], {
|
|
343
|
-
cwd,
|
|
344
|
-
onLine: adaptOnLine(o?.onLine)
|
|
345
|
-
});
|
|
346
|
-
},
|
|
347
|
-
async restart(idOrName) {
|
|
348
|
-
return await runner("docker", ["restart", idOrName]);
|
|
349
|
-
},
|
|
350
|
-
async stop(idOrName) {
|
|
351
|
-
return await runner("docker", ["stop", idOrName]);
|
|
352
|
-
},
|
|
353
|
-
async remove(idOrName, o) {
|
|
354
|
-
const args = ["rm"];
|
|
355
|
-
if (o?.force) args.push("--force");
|
|
356
|
-
args.push(idOrName);
|
|
357
|
-
return await runner("docker", args);
|
|
358
|
-
}
|
|
359
|
-
};
|
|
360
|
-
}
|
|
361
|
-
//#endregion
|
|
362
175
|
//#region src/core/nginx.ts
|
|
363
176
|
/** conf 命名空间前缀:文件名恒为 deploy-cli-<slug>.conf,前缀由模块拼接,调用方无法绕过 */
|
|
364
177
|
const CONF_PREFIX = "deploy-cli-";
|
|
365
178
|
const CONF_SUFFIX = ".conf";
|
|
366
|
-
|
|
179
|
+
/** slug 合法形状(M2-T2 #6 收紧):小写字母数字与连字符、不得连字符开头;项目 name 同用作 slug(F4 前移校验共用) */
|
|
180
|
+
const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
|
|
367
181
|
/** 渲染进 conf 的字段形状校验(防 conf 注入):域名 / 绝对路径 / host:port,统一排除 conf 元字符与空白 */
|
|
368
182
|
const DOMAIN_RE = /^(\*\.)?[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$/;
|
|
369
183
|
const ABS_PATH_RE = /^\/[A-Za-z0-9._/-]*$/;
|
|
@@ -373,6 +187,22 @@ const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
|
|
|
373
187
|
const DEFAULT_CONF_D = "/etc/nginx/conf.d";
|
|
374
188
|
/** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
|
|
375
189
|
const ACME_HOME = "/root/.acme.sh";
|
|
190
|
+
/** acme.sh 实际二进制路径(R6 约定);doctor 与 requestCert 共用同一路径探测(F1 对齐) */
|
|
191
|
+
const ACME_BIN = `${ACME_HOME}/acme.sh`;
|
|
192
|
+
/** acme.sh 在场探测命令(F1:doctor 与 requestCert 共用,勿各自另写探测) */
|
|
193
|
+
function acmeProbeCommand() {
|
|
194
|
+
return {
|
|
195
|
+
cmd: "sh",
|
|
196
|
+
args: ["-c", `test -x ${ACME_BIN}`]
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/** certbot 在场探测命令(F1:doctor 与 requestCert 共用) */
|
|
200
|
+
function certbotProbeCommand() {
|
|
201
|
+
return {
|
|
202
|
+
cmd: "sh",
|
|
203
|
+
args: ["-c", "command -v certbot"]
|
|
204
|
+
};
|
|
205
|
+
}
|
|
376
206
|
/** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
|
|
377
207
|
const ACME_RENEW_SKIP = 2;
|
|
378
208
|
/** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
|
|
@@ -386,7 +216,11 @@ function pathExists(path) {
|
|
|
386
216
|
}
|
|
387
217
|
/** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
|
|
388
218
|
function validateSlug(slug) {
|
|
389
|
-
if (!SLUG_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)}
|
|
219
|
+
if (!SLUG_RE.test(slug)) throw new Error(`非法 slug: ${JSON.stringify(slug)},仅允许小写字母、数字与连字符且以字母数字开头(禁止路径字符与大写)`);
|
|
220
|
+
}
|
|
221
|
+
/** slug 合法判定(F4:项目 name 用作 conf slug,loadProject 以同一正则前移校验,防部署到 nginx 步才被拒) */
|
|
222
|
+
function isValidSlug(slug) {
|
|
223
|
+
return SLUG_RE.test(slug);
|
|
390
224
|
}
|
|
391
225
|
function validateSpec(spec) {
|
|
392
226
|
validateSlug(spec.slug);
|
|
@@ -405,10 +239,9 @@ function validateSpec(spec) {
|
|
|
405
239
|
function validateAbsPath(field, value) {
|
|
406
240
|
if (!ABS_PATH_RE.test(value)) throw new Error(`NginxSiteSpec.${field} 非法: ${JSON.stringify(value)},须为绝对路径且不含 conf 元字符与空白`);
|
|
407
241
|
}
|
|
408
|
-
/**
|
|
242
|
+
/** 失败信息:统一走 core/exec 文案模板(M2-T2 #2 壳统一,R12 与 docker.ts 同口径),可附提示,包裹为 ExecError 附完整结果 */
|
|
409
243
|
function execFailure(cmd, args, result, note) {
|
|
410
|
-
|
|
411
|
-
return new ExecError(`${note ? `${note}: ` : ""}命令失败: ${[cmd, ...args].join(" ")}(exit ${result.code})${summary ? `: ${summary}` : "(stderr 无输出)"}`, result);
|
|
244
|
+
return new ExecError(`${note ? `${note}: ` : ""}${execFailureMessage(cmd, args, result)}`, result);
|
|
412
245
|
}
|
|
413
246
|
/**
|
|
414
247
|
* 路径探测:sites-available 与 sites-enabled 同时存在 → sites 模式(软链);否则 conf.d 模式(无软链)。
|
|
@@ -466,23 +299,37 @@ function createNginx(runner = run, paths) {
|
|
|
466
299
|
/**
|
|
467
300
|
* 写盘/回滚流程:新内容写隐藏 .conf.new → 旧 conf 备份隐藏 .bak → .new 原子改名 → 建 sites-enabled 软链 → nginx -t;
|
|
468
301
|
* 失败:恢复 .bak(或删新文件)、移除本次新建的软链、抛 ExecError;成功:nginx -s reload、清 .bak。
|
|
302
|
+
* 写盘段(写 .new/改名/软链)与 nginx -t 同一回滚口径(M2-T2 #8):段内任一 fs 操作失败即整体恢复再抛出。
|
|
469
303
|
*/
|
|
470
304
|
async function writeSite(slug, content) {
|
|
471
305
|
const conf = join$1(sitesAvailable, confName(slug));
|
|
472
306
|
const tmp = join$1(sitesAvailable, tmpName(slug));
|
|
473
307
|
const bak = join$1(sitesAvailable, bakName(slug));
|
|
474
|
-
writeFileSync$1(tmp, content, "utf-8");
|
|
475
|
-
const existed = pathExists(conf);
|
|
476
|
-
if (existed) renameSync(conf, bak);
|
|
477
|
-
renameSync(tmp, conf);
|
|
478
308
|
const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
|
|
309
|
+
const existed = pathExists(conf);
|
|
479
310
|
const linkCreated = link ? !pathExists(link) : false;
|
|
480
|
-
|
|
311
|
+
/** 统一回滚:恢复/清除 conf、软链、.new 临时文件(逐项守护,回滚自身不得再抛) */
|
|
481
312
|
const rollback = () => {
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
313
|
+
try {
|
|
314
|
+
if (existed) renameSync(bak, conf);
|
|
315
|
+
else if (pathExists(conf)) unlinkSync(conf);
|
|
316
|
+
} catch {}
|
|
317
|
+
try {
|
|
318
|
+
if (link && linkCreated && pathExists(link)) unlinkSync(link);
|
|
319
|
+
} catch {}
|
|
320
|
+
try {
|
|
321
|
+
if (pathExists(tmp)) unlinkSync(tmp);
|
|
322
|
+
} catch {}
|
|
485
323
|
};
|
|
324
|
+
try {
|
|
325
|
+
writeFileSync$1(tmp, content, "utf-8");
|
|
326
|
+
if (existed) renameSync(conf, bak);
|
|
327
|
+
renameSync(tmp, conf);
|
|
328
|
+
if (link && linkCreated) symlinkSync(conf, link);
|
|
329
|
+
} catch (error) {
|
|
330
|
+
rollback();
|
|
331
|
+
throw error;
|
|
332
|
+
}
|
|
486
333
|
let test;
|
|
487
334
|
try {
|
|
488
335
|
test = await runner("nginx", ["-t"]);
|
|
@@ -500,27 +347,39 @@ function createNginx(runner = run, paths) {
|
|
|
500
347
|
} catch (error) {
|
|
501
348
|
throw error;
|
|
502
349
|
}
|
|
503
|
-
if (reload.code !== 0)
|
|
350
|
+
if (reload.code !== 0) {
|
|
351
|
+
const note = existed ? `nginx reload 失败,保留备份 ${bak} 供人工恢复` : `nginx reload 失败(新建站点无备份可回退),conf 已写入 ${conf},可手工 nginx -s reload 重试或删除该 conf`;
|
|
352
|
+
throw execFailure("nginx", ["-s", "reload"], reload, note);
|
|
353
|
+
}
|
|
504
354
|
if (existed) unlinkSync(bak);
|
|
505
355
|
}
|
|
506
356
|
async function requestCert(domain) {
|
|
507
|
-
|
|
508
|
-
|
|
357
|
+
if (!DOMAIN_RE.test(domain)) throw new Error(`requestCert domain 非法: ${JSON.stringify(domain)},仅允许域名字符(字母数字.-,可选 *. 前缀;禁止元字符与空白)`);
|
|
358
|
+
const acme = acmeProbeCommand();
|
|
359
|
+
if ((await runner(acme.cmd, acme.args)).code === 0) {
|
|
509
360
|
const args = [
|
|
510
361
|
"--issue",
|
|
511
362
|
"--nginx",
|
|
512
363
|
"-d",
|
|
513
364
|
domain
|
|
514
365
|
];
|
|
515
|
-
const result = await runner(
|
|
516
|
-
if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(
|
|
517
|
-
|
|
518
|
-
tool: "acme.sh",
|
|
366
|
+
const result = await runner(ACME_BIN, args);
|
|
367
|
+
if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(ACME_BIN, args, result, `acme.sh 签发失败: ${domain}`);
|
|
368
|
+
const candidates = [{
|
|
519
369
|
certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
|
|
520
370
|
keyPath: `${ACME_HOME}/${domain}/${domain}.key`
|
|
371
|
+
}, {
|
|
372
|
+
certPath: `${ACME_HOME}/${domain}_ecc/fullchain.cer`,
|
|
373
|
+
keyPath: `${ACME_HOME}/${domain}_ecc/${domain}.key`
|
|
374
|
+
}];
|
|
375
|
+
for (const candidate of candidates) if ((await runner("sh", ["-c", `test -f ${candidate.certPath}`])).code === 0) return {
|
|
376
|
+
tool: "acme.sh",
|
|
377
|
+
...candidate
|
|
521
378
|
};
|
|
379
|
+
throw new Error(`acme.sh 签发完成但未找到证书文件(已探测 ${candidates.map((c) => c.certPath).join(" 与 ")}),请检查 acme.sh 安装证书目录`);
|
|
522
380
|
}
|
|
523
|
-
|
|
381
|
+
const certbot = certbotProbeCommand();
|
|
382
|
+
if ((await runner(certbot.cmd, certbot.args)).code === 0) {
|
|
524
383
|
const args = [
|
|
525
384
|
"--nginx",
|
|
526
385
|
"-d",
|
|
@@ -544,7 +403,13 @@ function createNginx(runner = run, paths) {
|
|
|
544
403
|
validateSpec(spec);
|
|
545
404
|
if (spec.ssl === "acme") {
|
|
546
405
|
await writeSite(spec.slug, renderBlock(spec, false));
|
|
547
|
-
|
|
406
|
+
let cert;
|
|
407
|
+
try {
|
|
408
|
+
cert = await requestCert(spec.serverName);
|
|
409
|
+
} catch (error) {
|
|
410
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
411
|
+
throw new Error(`${reason};注意:HTTP 块已上线(deploy-cli-${spec.slug}.conf 已生效,站点当前仅 HTTP)`, { cause: error });
|
|
412
|
+
}
|
|
548
413
|
await writeSite(spec.slug, renderBlock({
|
|
549
414
|
...spec,
|
|
550
415
|
certPath: cert.certPath,
|
|
@@ -594,6 +459,254 @@ function createNginx(runner = run, paths) {
|
|
|
594
459
|
};
|
|
595
460
|
}
|
|
596
461
|
//#endregion
|
|
462
|
+
//#region src/core/project.ts
|
|
463
|
+
const VALID_TYPES = [
|
|
464
|
+
"compose",
|
|
465
|
+
"image",
|
|
466
|
+
"static"
|
|
467
|
+
];
|
|
468
|
+
const DEFAULT_COMPOSE_FILE = "docker-compose.yml";
|
|
469
|
+
const VALID_SSL = [
|
|
470
|
+
"none",
|
|
471
|
+
"acme",
|
|
472
|
+
"custom"
|
|
473
|
+
];
|
|
474
|
+
const VALID_UPDATE = ["git-pull", "none"];
|
|
475
|
+
/** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
|
|
476
|
+
var ProjectConfigError = class extends Error {
|
|
477
|
+
field;
|
|
478
|
+
constructor(message, field) {
|
|
479
|
+
super(message);
|
|
480
|
+
this.name = "ProjectConfigError";
|
|
481
|
+
this.field = field;
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
/** 读取 <dir>/deploy.yaml 并校验,失败抛 ProjectConfigError */
|
|
485
|
+
function loadProject(dir) {
|
|
486
|
+
const yamlPath = resolve(dir, "deploy.yaml");
|
|
487
|
+
let raw;
|
|
488
|
+
try {
|
|
489
|
+
raw = readFileSync(yamlPath, "utf-8");
|
|
490
|
+
} catch (error) {
|
|
491
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
492
|
+
if (error?.code === "ENOENT") throw new ProjectConfigError(`缺少 deploy.yaml: ${yamlPath}`);
|
|
493
|
+
throw new ProjectConfigError(`读取 deploy.yaml 失败: ${yamlPath}: ${reason}`);
|
|
494
|
+
}
|
|
495
|
+
let parsed;
|
|
496
|
+
try {
|
|
497
|
+
parsed = parse(raw);
|
|
498
|
+
} catch (error) {
|
|
499
|
+
throw new ProjectConfigError(`deploy.yaml 解析失败: ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
500
|
+
}
|
|
501
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
|
|
502
|
+
return validate(parsed);
|
|
503
|
+
}
|
|
504
|
+
/** 校验并规范化 deploy.yaml 模型:name(含 slug 形状)→ type 合法性 → 类型必填字段 → nginx.domain 非空 → deploy 段值域 */
|
|
505
|
+
function validate(raw) {
|
|
506
|
+
const name = raw.name;
|
|
507
|
+
if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
|
|
508
|
+
if (!isValidSlug(name)) throw new ProjectConfigError(`name 非法: ${JSON.stringify(name)},仅允许小写字母、数字与连字符且以字母数字开头(name 将用作 nginx 站点 slug)`, "name");
|
|
509
|
+
const type = raw.type;
|
|
510
|
+
if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
|
|
511
|
+
if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
|
|
512
|
+
if (type === "image" && (typeof raw.image !== "string" || raw.image.trim() === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
|
|
513
|
+
if (type === "static" && (typeof raw.root !== "string" || raw.root.trim() === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
|
|
514
|
+
if (raw.nginx !== void 0 && raw.nginx !== null) {
|
|
515
|
+
const nginx = raw.nginx;
|
|
516
|
+
if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
|
|
517
|
+
const n = nginx;
|
|
518
|
+
if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
|
|
519
|
+
if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
|
|
520
|
+
}
|
|
521
|
+
if (raw.deploy !== void 0 && raw.deploy !== null) {
|
|
522
|
+
const deploy = raw.deploy;
|
|
523
|
+
if (typeof deploy !== "object" || Array.isArray(deploy)) throw new ProjectConfigError("deploy 应为对象", "deploy");
|
|
524
|
+
const dp = deploy;
|
|
525
|
+
if (dp.update !== void 0 && dp.update !== null) {
|
|
526
|
+
if (typeof dp.update !== "string" || !VALID_UPDATE.includes(dp.update)) throw new ProjectConfigError(`deploy.update 非法: ${JSON.stringify(dp.update)},合法值: git-pull | none(不设=不自动更新)`, "deploy.update");
|
|
527
|
+
}
|
|
528
|
+
if (dp.build !== void 0 && dp.build !== null && typeof dp.build !== "string") throw new ProjectConfigError("deploy.build 应为字符串(构建命令)", "deploy.build");
|
|
529
|
+
for (const hook of ["pre", "post"]) {
|
|
530
|
+
const hooks = dp[hook];
|
|
531
|
+
if (hooks !== void 0 && hooks !== null && (!Array.isArray(hooks) || hooks.some((c) => typeof c !== "string"))) throw new ProjectConfigError(`deploy.${hook} 应为字符串数组(命令列表)`, `deploy.${hook}`);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
const d = raw;
|
|
535
|
+
if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
|
|
536
|
+
return d;
|
|
537
|
+
}
|
|
538
|
+
/** 列出注册表项目;单个坏配置降级 {config:null,error},不中断其余项目 */
|
|
539
|
+
function listProjects(cfg) {
|
|
540
|
+
return cfg.projects.map((project) => {
|
|
541
|
+
try {
|
|
542
|
+
return {
|
|
543
|
+
name: project.name,
|
|
544
|
+
path: project.path,
|
|
545
|
+
config: loadProject(project.path)
|
|
546
|
+
};
|
|
547
|
+
} catch (error) {
|
|
548
|
+
return {
|
|
549
|
+
name: project.name,
|
|
550
|
+
path: project.path,
|
|
551
|
+
config: null,
|
|
552
|
+
error: error instanceof Error ? error.message : String(error)
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
/** 读 <dir>/deploy.yaml 取 name 注册进 cfg.projects(不落盘,由调用方 saveConfig);dir 在核心层 resolve 归一(M2-T2 #9) */
|
|
558
|
+
function addProject(cfg, dir) {
|
|
559
|
+
const normalized = resolve(dir);
|
|
560
|
+
const config = loadProject(normalized);
|
|
561
|
+
const byName = cfg.projects.find((p) => p.name === config.name);
|
|
562
|
+
if (byName) throw new Error(`项目已注册: ${config.name}(${byName.path}),请先 remove 再 add`);
|
|
563
|
+
const byPath = cfg.projects.find((p) => resolve(p.path) === normalized);
|
|
564
|
+
if (byPath) throw new Error(`路径已注册为项目 ${byPath.name}: ${normalized}`);
|
|
565
|
+
const entry = {
|
|
566
|
+
name: config.name,
|
|
567
|
+
path: normalized,
|
|
568
|
+
deployDir: "deploy"
|
|
569
|
+
};
|
|
570
|
+
return {
|
|
571
|
+
...cfg,
|
|
572
|
+
projects: [...cfg.projects, entry]
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
/** 从 cfg.projects 注销指定项目(不落盘,由调用方 saveConfig) */
|
|
576
|
+
function removeProject(cfg, name) {
|
|
577
|
+
const projects = cfg.projects.filter((p) => p.name !== name);
|
|
578
|
+
if (projects.length === cfg.projects.length) throw new Error(`未找到项目: ${name}`);
|
|
579
|
+
return {
|
|
580
|
+
...cfg,
|
|
581
|
+
projects
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
/** image 型生成的 docker-compose.yml 标记头(护栏 marker):既有同名文件无此头则拒绝覆盖(终审 M1:防绑架项目文件) */
|
|
585
|
+
const COMPOSE_MARKER = "# generated by deploy-cli — do not edit";
|
|
586
|
+
/** marker 判定扫描窗口(A2):不再死盯首行——运维头注释把 marker 挤到前几行仍认;窗口外不认 */
|
|
587
|
+
const MARKER_SCAN_LINES = 10;
|
|
588
|
+
/** 既有文件内容是否带 COMPOSE_MARKER 头(前 10 行内任一行,M2-T2 A2:不再信任首行) */
|
|
589
|
+
function hasComposeMarker(content) {
|
|
590
|
+
return content.split("\n").slice(0, MARKER_SCAN_LINES).some((line) => line.trim() === COMPOSE_MARKER);
|
|
591
|
+
}
|
|
592
|
+
/** image 型 → docker-compose.yml 文本(compose 中 env 的键名为 environment),首行带 COMPOSE_MARKER 标记头 */
|
|
593
|
+
function generateCompose(d) {
|
|
594
|
+
if (d.type !== "image") throw new ProjectConfigError(`generateCompose 仅支持 image 型项目(当前 type: ${d.type})`, "type");
|
|
595
|
+
if (typeof d.image !== "string" || d.image.trim() === "") throw new ProjectConfigError("image 型缺少必填字段: image", "image");
|
|
596
|
+
const service = { image: d.image };
|
|
597
|
+
if (d.ports && d.ports.length > 0) service.ports = d.ports;
|
|
598
|
+
if (d.volumes && d.volumes.length > 0) service.volumes = d.volumes;
|
|
599
|
+
if (d.env && Object.keys(d.env).length > 0) service.environment = d.env;
|
|
600
|
+
return `${COMPOSE_MARKER}\n${stringify({ services: { [d.name]: service } })}`;
|
|
601
|
+
}
|
|
602
|
+
//#endregion
|
|
603
|
+
//#region src/core/docker.ts
|
|
604
|
+
/** docker 调用默认超时(F5:docker daemon 挂起不得永久挂死 CLI),与流水线 600s 长步档同口径;--follow 流式豁免 */
|
|
605
|
+
const DOCKER_TIMEOUT_MS = 6e5;
|
|
606
|
+
/** docker logs 的完整参数(CLI 报错展示与实际执行共用同一构造,保证命令原文一致) */
|
|
607
|
+
function logsArgs(idOrName, o) {
|
|
608
|
+
const args = ["logs"];
|
|
609
|
+
if (o?.tail !== void 0) args.push("--tail", String(o.tail));
|
|
610
|
+
if (o?.follow) args.push("--follow");
|
|
611
|
+
args.push(idOrName);
|
|
612
|
+
return args;
|
|
613
|
+
}
|
|
614
|
+
/** 把 Runner 的 (line, stream) 回调适配为 DockerApi 的 onLine(M2-T2 #3:stream 标签透传,不再丢弃) */
|
|
615
|
+
function adaptOnLine(onLine) {
|
|
616
|
+
return onLine ? (line, stream) => onLine(line, stream) : void 0;
|
|
617
|
+
}
|
|
618
|
+
/** docker ps 一行 json → ContainerInfo;兼容真实 docker 的 ID 大写键与 brief 的 Id */
|
|
619
|
+
function parseContainerLine(line) {
|
|
620
|
+
let raw;
|
|
621
|
+
try {
|
|
622
|
+
raw = JSON.parse(line);
|
|
623
|
+
} catch (error) {
|
|
624
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
625
|
+
throw new Error(`解析 docker ps 输出失败: ${line}: ${reason}`);
|
|
626
|
+
}
|
|
627
|
+
return {
|
|
628
|
+
id: String(raw.ID ?? raw.Id ?? ""),
|
|
629
|
+
name: String(raw.Names ?? ""),
|
|
630
|
+
image: String(raw.Image ?? ""),
|
|
631
|
+
state: String(raw.State ?? ""),
|
|
632
|
+
status: String(raw.Status ?? ""),
|
|
633
|
+
ports: String(raw.Ports ?? "")
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
/** 以 shell-out 方式实现的 docker 操作集合 */
|
|
637
|
+
function createDocker(runner = run) {
|
|
638
|
+
/** F5 防挂起:docker 调用默认挂 DOCKER_TIMEOUT_MS;调用方显式 timeoutMs 优先 */
|
|
639
|
+
const withTimeout = (cmd, args, o = {}) => runner(cmd, args, {
|
|
640
|
+
...o,
|
|
641
|
+
timeoutMs: o.timeoutMs ?? 6e5
|
|
642
|
+
});
|
|
643
|
+
return {
|
|
644
|
+
async listContainers(o) {
|
|
645
|
+
const args = ["ps"];
|
|
646
|
+
if (o?.all) args.push("-a");
|
|
647
|
+
if (o?.name) args.push("--filter", `name=${o.name}`);
|
|
648
|
+
args.push("--format", "{{json .}}");
|
|
649
|
+
const result = await withTimeout("docker", args);
|
|
650
|
+
if (result.code !== 0) throw new Error(execFailureMessage("docker", args, result));
|
|
651
|
+
return result.stdout.split("\n").filter((line) => line.trim() !== "").map(parseContainerLine);
|
|
652
|
+
},
|
|
653
|
+
async logs(idOrName, o) {
|
|
654
|
+
return await runner("docker", logsArgs(idOrName, o), {
|
|
655
|
+
onLine: adaptOnLine(o?.onLine),
|
|
656
|
+
...o?.follow ? {} : { timeoutMs: DOCKER_TIMEOUT_MS }
|
|
657
|
+
});
|
|
658
|
+
},
|
|
659
|
+
async composeUp(cwd, composeFile, o) {
|
|
660
|
+
const args = [
|
|
661
|
+
"compose",
|
|
662
|
+
"-f",
|
|
663
|
+
composeFile,
|
|
664
|
+
"up",
|
|
665
|
+
"-d"
|
|
666
|
+
];
|
|
667
|
+
if (o?.build) args.push("--build");
|
|
668
|
+
return await withTimeout("docker", args, {
|
|
669
|
+
cwd,
|
|
670
|
+
onLine: adaptOnLine(o?.onLine)
|
|
671
|
+
});
|
|
672
|
+
},
|
|
673
|
+
async composeDown(cwd, composeFile, o) {
|
|
674
|
+
return await withTimeout("docker", [
|
|
675
|
+
"compose",
|
|
676
|
+
"-f",
|
|
677
|
+
composeFile,
|
|
678
|
+
"down"
|
|
679
|
+
], {
|
|
680
|
+
cwd,
|
|
681
|
+
onLine: adaptOnLine(o?.onLine)
|
|
682
|
+
});
|
|
683
|
+
},
|
|
684
|
+
async composeBuild(cwd, composeFile, o) {
|
|
685
|
+
return await withTimeout("docker", [
|
|
686
|
+
"compose",
|
|
687
|
+
"-f",
|
|
688
|
+
composeFile,
|
|
689
|
+
"build"
|
|
690
|
+
], {
|
|
691
|
+
cwd,
|
|
692
|
+
onLine: adaptOnLine(o?.onLine)
|
|
693
|
+
});
|
|
694
|
+
},
|
|
695
|
+
async restart(idOrName) {
|
|
696
|
+
return await withTimeout("docker", ["restart", idOrName]);
|
|
697
|
+
},
|
|
698
|
+
async stop(idOrName) {
|
|
699
|
+
return await withTimeout("docker", ["stop", idOrName]);
|
|
700
|
+
},
|
|
701
|
+
async remove(idOrName, o) {
|
|
702
|
+
const args = ["rm"];
|
|
703
|
+
if (o?.force) args.push("--force");
|
|
704
|
+
args.push(idOrName);
|
|
705
|
+
return await withTimeout("docker", args);
|
|
706
|
+
}
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
//#endregion
|
|
597
710
|
//#region src/core/health.ts
|
|
598
711
|
/** 把 fetch 失败原因(含 cause / AggregateError 链)摊平成含关键码的单行摘要 */
|
|
599
712
|
function describeFetchError(error, timeoutMs) {
|
|
@@ -645,27 +758,30 @@ function containerBelongsToProject(containerName, projectName) {
|
|
|
645
758
|
for (let i = 0; i + want.length <= segments.length; i++) if (want.every((w, j) => segments[i + j] === w)) return true;
|
|
646
759
|
return false;
|
|
647
760
|
}
|
|
648
|
-
/**
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
761
|
+
/**
|
|
762
|
+
* 项目容器集合:docker name 过滤(子串)+ 精确名后过滤。
|
|
763
|
+
* all 语义可选(M2-T2 #14,与 ps --all 口径一致):缺省 true=含已停止容器(status/deploy 现口径不变),
|
|
764
|
+
* false=只查运行中(ps 不带 --all 的口径)。
|
|
765
|
+
*/
|
|
766
|
+
async function findProjectContainers(docker, projectName, opts = {}) {
|
|
767
|
+
const listOpts = { name: projectName };
|
|
768
|
+
if (opts.all ?? true) listOpts.all = true;
|
|
769
|
+
return (await docker.listContainers(listOpts)).filter((c) => containerBelongsToProject(c.name, projectName));
|
|
654
770
|
}
|
|
655
771
|
/** deploy-cli 管理的站点 conf 是否在位;nginx 目录不可读(未装/无权限)→ undefined(未知) */
|
|
656
|
-
async function probeNginxSite(slug,
|
|
772
|
+
async function probeNginxSite(slug, api) {
|
|
657
773
|
try {
|
|
658
|
-
return (await
|
|
774
|
+
return (await api.listSites()).includes(slug);
|
|
659
775
|
} catch {
|
|
660
776
|
return;
|
|
661
777
|
}
|
|
662
778
|
}
|
|
663
|
-
/** 项目健康聚合:容器状态 + HTTP 探测 + nginx conf
|
|
779
|
+
/** 项目健康聚合:容器状态 + HTTP 探测 + nginx conf 在位;nginx 判定可注入(M2-T2 #11 测试接缝,缺省 createNginx) */
|
|
664
780
|
async function checkProjectHealth(project, opts) {
|
|
665
781
|
const runner = opts.runner ?? run;
|
|
666
782
|
const containers = await findProjectContainers(opts.docker ?? createDocker(runner), project.name);
|
|
667
783
|
const http = project.healthUrl ? await httpProbe(project.healthUrl) : void 0;
|
|
668
|
-
const nginxPresent = await probeNginxSite(project.name, runner);
|
|
784
|
+
const nginxPresent = await probeNginxSite(project.name, opts.nginx ?? createNginx(runner));
|
|
669
785
|
return {
|
|
670
786
|
name: project.name,
|
|
671
787
|
containers,
|
|
@@ -768,6 +884,11 @@ async function runDeploy(project, opts) {
|
|
|
768
884
|
}
|
|
769
885
|
const composeFile = project.composeFile ?? "docker-compose.yml";
|
|
770
886
|
const customBuild = project.deploy?.build;
|
|
887
|
+
if (project.type === "static" && customBuild !== void 0) emit({
|
|
888
|
+
step: "build",
|
|
889
|
+
status: "warn",
|
|
890
|
+
line: "static 型项目不执行 build,deploy.build 已忽略;如需构建步骤请改用 deploy.pre 钩子"
|
|
891
|
+
});
|
|
771
892
|
if (project.type !== "static" && (customBuild !== void 0 || project.type === "compose")) {
|
|
772
893
|
const stopped = await step("build", customBuild ?? `docker compose -f ${composeFile} build`, async () => {
|
|
773
894
|
if (customBuild !== void 0) expectOk(await runner("bash", ["-c", customBuild]), "bash", ["-c", customBuild]);
|
|
@@ -835,14 +956,19 @@ const USAGE$6 = `用法: deploy-cli deploy <project> [--yes] [--no-nginx]
|
|
|
835
956
|
|
|
836
957
|
流水线: update(git pull) → pre 钩子 → build → up → nginx → health → post 钩子(失败即停)
|
|
837
958
|
|
|
959
|
+
说明:
|
|
960
|
+
deploy 不支持 --no-ssl(nginx 步按 deploy.yaml 的 nginx.ssl 执行);如需 HTTP-only,请用 deploy-cli nginx apply <project> --no-ssl
|
|
961
|
+
static 型不执行 build/up(deploy.build 会被忽略并提示);如需构建步骤请用 deploy.pre 钩子
|
|
962
|
+
|
|
838
963
|
示例:
|
|
839
964
|
deploy-cli deploy my-app
|
|
840
965
|
deploy-cli deploy my-app --yes
|
|
841
966
|
deploy-cli deploy my-app --yes --no-nginx`;
|
|
842
|
-
/** 流水线事件 → 输出行:start=命令原文/开始、ok=✓、fail
|
|
967
|
+
/** 流水线事件 → 输出行:start=命令原文/开始、ok=✓、fail=✗+失败信息、warn=⚠+提示(M2-T2 #12) */
|
|
843
968
|
function formatEvent(e) {
|
|
844
969
|
if (e.status === "ok") return `[${e.step}] ✓`;
|
|
845
970
|
if (e.status === "fail") return `[${e.step}] ✗ ${e.line ?? ""}`;
|
|
971
|
+
if (e.status === "warn") return `[${e.step}] ⚠ ${e.line ?? ""}`;
|
|
846
972
|
return `[${e.step}] ${e.line ?? "开始"}`;
|
|
847
973
|
}
|
|
848
974
|
/** 部署流水线命令:deploy <project> [--yes] [--no-nginx];返回退出码 */
|
|
@@ -914,7 +1040,6 @@ async function deploy(args, options = {}) {
|
|
|
914
1040
|
}
|
|
915
1041
|
//#endregion
|
|
916
1042
|
//#region src/cli/commands/doctor.ts
|
|
917
|
-
const SITES_AVAILABLE = "/etc/nginx/sites-available";
|
|
918
1043
|
const MIN_NODE_MAJOR = 20;
|
|
919
1044
|
/** 单项检查超时,防 docker/nginx 卡死挂死 doctor */
|
|
920
1045
|
const PROBE_TIMEOUT_MS = 1e4;
|
|
@@ -967,11 +1092,16 @@ async function doctor(options = {}) {
|
|
|
967
1092
|
const nginx = await probe(runner, "nginx", ["-v"]);
|
|
968
1093
|
if (nginx.ok) pass(`nginx 可用(${nginx.detail})`);
|
|
969
1094
|
else fail(`nginx 不可用(nginx -v 失败): ${nginx.detail}`);
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
1095
|
+
const paths = resolveNginxPaths(options.exists ?? existsSync$1);
|
|
1096
|
+
if (canWrite(paths.sitesAvailable)) pass(`${paths.sitesAvailable} 可写`);
|
|
1097
|
+
else fail(`${paths.sitesAvailable} 不可写`);
|
|
1098
|
+
if (paths.sitesEnabled) if (canWrite(paths.sitesEnabled)) pass(`${paths.sitesEnabled} 可写`);
|
|
1099
|
+
else fail(`${paths.sitesEnabled} 不可写(sites-enabled 软链无法创建)`);
|
|
1100
|
+
const acmeCmd = acmeProbeCommand();
|
|
1101
|
+
const certbotCmd = certbotProbeCommand();
|
|
1102
|
+
const acme = await probe(runner, acmeCmd.cmd, acmeCmd.args);
|
|
1103
|
+
const certbot = await probe(runner, certbotCmd.cmd, certbotCmd.args);
|
|
1104
|
+
const certTools = [acme.ok && `acme.sh(${ACME_BIN})`, certbot.ok && "certbot"].filter(Boolean).join(" / ");
|
|
975
1105
|
if (certTools) pass(`证书工具可用(${certTools})`);
|
|
976
1106
|
else warn("未检测到 acme.sh / certbot,HTTPS 证书签发/续期不可用(仅警告,不影响退出码)");
|
|
977
1107
|
return failed ? 1 : 0;
|
|
@@ -1036,7 +1166,7 @@ async function logs(args, options = {}) {
|
|
|
1036
1166
|
try {
|
|
1037
1167
|
const result = await docker.logs(name, {
|
|
1038
1168
|
...logOpts,
|
|
1039
|
-
onLine: (line) => log(line)
|
|
1169
|
+
onLine: (line, stream) => stream === "stderr" ? error(line) : log(line)
|
|
1040
1170
|
});
|
|
1041
1171
|
if (result.code !== 0) {
|
|
1042
1172
|
error(execFailureMessage("docker", logsArgs(name, logOpts), result));
|
|
@@ -1078,6 +1208,10 @@ async function nginx(args, options = {}) {
|
|
|
1078
1208
|
error(USAGE$4);
|
|
1079
1209
|
return 1;
|
|
1080
1210
|
}
|
|
1211
|
+
if (rest.includes("-h") || rest.includes("--help")) {
|
|
1212
|
+
log(USAGE$4);
|
|
1213
|
+
return 0;
|
|
1214
|
+
}
|
|
1081
1215
|
try {
|
|
1082
1216
|
switch (sub) {
|
|
1083
1217
|
case "apply": {
|
|
@@ -1110,6 +1244,12 @@ async function nginx(args, options = {}) {
|
|
|
1110
1244
|
return 0;
|
|
1111
1245
|
}
|
|
1112
1246
|
case "remove": {
|
|
1247
|
+
const dash = rest.filter((a) => a.startsWith("-"));
|
|
1248
|
+
if (dash.length > 0) {
|
|
1249
|
+
error(`未知参数: ${dash.join(" ")}`);
|
|
1250
|
+
error(USAGE$4);
|
|
1251
|
+
return 1;
|
|
1252
|
+
}
|
|
1113
1253
|
const name = rest[0];
|
|
1114
1254
|
if (name === void 0 || rest.length > 1) {
|
|
1115
1255
|
error("remove 需要且仅需要一个 <project> 参数");
|
|
@@ -1170,6 +1310,10 @@ async function project(args, options = {}) {
|
|
|
1170
1310
|
error(USAGE$3);
|
|
1171
1311
|
return 1;
|
|
1172
1312
|
}
|
|
1313
|
+
if (rest.includes("-h") || rest.includes("--help")) {
|
|
1314
|
+
log(USAGE$3);
|
|
1315
|
+
return 0;
|
|
1316
|
+
}
|
|
1173
1317
|
try {
|
|
1174
1318
|
switch (sub) {
|
|
1175
1319
|
case "list": {
|
|
@@ -1180,7 +1324,10 @@ async function project(args, options = {}) {
|
|
|
1180
1324
|
}
|
|
1181
1325
|
const rows = listProjects(load());
|
|
1182
1326
|
log("NAME PATH TYPE ERROR");
|
|
1183
|
-
for (const row of rows)
|
|
1327
|
+
for (const row of rows) {
|
|
1328
|
+
const errorText = (row.error ?? "").replace(/\s+/g, " ").trim();
|
|
1329
|
+
log(`${row.name}\t${row.path}\t${row.config?.type ?? "-"}\t${errorText}`);
|
|
1330
|
+
}
|
|
1184
1331
|
return 0;
|
|
1185
1332
|
}
|
|
1186
1333
|
case "add": {
|
|
@@ -1198,6 +1345,12 @@ async function project(args, options = {}) {
|
|
|
1198
1345
|
return 0;
|
|
1199
1346
|
}
|
|
1200
1347
|
case "remove": {
|
|
1348
|
+
const dash = rest.filter((a) => a.startsWith("-"));
|
|
1349
|
+
if (dash.length > 0) {
|
|
1350
|
+
error(`未知参数: ${dash.join(" ")}`);
|
|
1351
|
+
error(USAGE$3);
|
|
1352
|
+
return 1;
|
|
1353
|
+
}
|
|
1201
1354
|
const name = rest[0];
|
|
1202
1355
|
if (name === void 0 || rest.length > 1) {
|
|
1203
1356
|
error("remove 需要且仅需要一个 <name> 参数");
|
|
@@ -1262,22 +1415,22 @@ async function ps(args, options = {}) {
|
|
|
1262
1415
|
}
|
|
1263
1416
|
const docker = options.docker ?? createDocker();
|
|
1264
1417
|
try {
|
|
1265
|
-
let nameFilter;
|
|
1266
1418
|
if (projectName !== void 0) {
|
|
1267
1419
|
const project = (options.projects ?? (() => loadConfig().projects))().find((p) => p.name === projectName);
|
|
1268
1420
|
if (!project) {
|
|
1269
1421
|
error(`未找到项目: ${projectName}(请检查 ~/.deploy-cli/config.json 的 projects 注册表)`);
|
|
1270
1422
|
return 1;
|
|
1271
1423
|
}
|
|
1272
|
-
|
|
1424
|
+
const rows = await findProjectContainers(docker, project.name, { all });
|
|
1425
|
+
log("NAME IMAGE STATE PORTS");
|
|
1426
|
+
for (const container of rows) log(`${container.name}\t${container.image}\t${container.state}\t${container.ports}`);
|
|
1427
|
+
return 0;
|
|
1273
1428
|
}
|
|
1274
1429
|
const listOpts = {};
|
|
1275
1430
|
if (all) listOpts.all = true;
|
|
1276
|
-
if (nameFilter) listOpts.name = nameFilter;
|
|
1277
1431
|
const containers = await docker.listContainers(listOpts);
|
|
1278
|
-
const rows = projectName === void 0 ? containers : containers.filter((c) => containerBelongsToProject(c.name, projectName));
|
|
1279
1432
|
log("NAME IMAGE STATE PORTS");
|
|
1280
|
-
for (const container of
|
|
1433
|
+
for (const container of containers) log(`${container.name}\t${container.image}\t${container.state}\t${container.ports}`);
|
|
1281
1434
|
return 0;
|
|
1282
1435
|
} catch (err) {
|
|
1283
1436
|
error(err instanceof Error ? err.message : String(err));
|
|
@@ -1346,10 +1499,17 @@ async function status(args, options = {}) {
|
|
|
1346
1499
|
log(`${row.name}\t配置不可用\t-\t-`);
|
|
1347
1500
|
continue;
|
|
1348
1501
|
}
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1502
|
+
try {
|
|
1503
|
+
log(formatRow(await checkProjectHealth(row.config, {
|
|
1504
|
+
docker: options.docker,
|
|
1505
|
+
runner: options.runner,
|
|
1506
|
+
nginx: options.nginx
|
|
1507
|
+
})));
|
|
1508
|
+
} catch (err) {
|
|
1509
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
1510
|
+
error(`项目健康检查失败: ${row.name}: ${reason}`);
|
|
1511
|
+
log(`${row.name}\t检查失败\t-\t-`);
|
|
1512
|
+
}
|
|
1353
1513
|
}
|
|
1354
1514
|
return 0;
|
|
1355
1515
|
} catch (err) {
|
|
@@ -1368,7 +1528,24 @@ const USAGE = `用法:
|
|
|
1368
1528
|
deploy-cli project 项目注册表:list / add / remove(--help 看示例)
|
|
1369
1529
|
deploy-cli nginx 站点配置:apply / remove / list(--help 看示例)
|
|
1370
1530
|
deploy-cli deploy 执行部署流水线(--help 看示例)
|
|
1371
|
-
deploy-cli status 项目健康状态聚合(--help
|
|
1531
|
+
deploy-cli status 项目健康状态聚合(--help 看示例)
|
|
1532
|
+
deploy-cli --version 输出版本号`;
|
|
1533
|
+
const PKG_NAME = "@dongnanyang/deploy-cli";
|
|
1534
|
+
/** 读取 package.json version(M2-T2 #13):自当前模块逐级向上找本包 package.json(构建产物 dist/ 与测试 src/ 均成立) */
|
|
1535
|
+
function readVersion() {
|
|
1536
|
+
let dir = dirname$1(fileURLToPath(import.meta.url));
|
|
1537
|
+
for (let i = 0; i < 6; i++) {
|
|
1538
|
+
const file = join$1(dir, "package.json");
|
|
1539
|
+
if (existsSync$1(file)) try {
|
|
1540
|
+
const pkg = JSON.parse(readFileSync$1(file, "utf-8"));
|
|
1541
|
+
if (pkg.name === PKG_NAME && typeof pkg.version === "string") return pkg.version;
|
|
1542
|
+
} catch {}
|
|
1543
|
+
const parent = dirname$1(dir);
|
|
1544
|
+
if (parent === dir) break;
|
|
1545
|
+
dir = parent;
|
|
1546
|
+
}
|
|
1547
|
+
return "unknown";
|
|
1548
|
+
}
|
|
1372
1549
|
/** CLI 子命令分发,返回退出码 */
|
|
1373
1550
|
async function main(argv) {
|
|
1374
1551
|
const [command] = argv;
|
|
@@ -1380,6 +1557,10 @@ async function main(argv) {
|
|
|
1380
1557
|
case "nginx": return await nginx(argv.slice(1));
|
|
1381
1558
|
case "deploy": return await deploy(argv.slice(1));
|
|
1382
1559
|
case "status": return await status(argv.slice(1));
|
|
1560
|
+
case "--version":
|
|
1561
|
+
case "-V":
|
|
1562
|
+
console.log(readVersion());
|
|
1563
|
+
return 0;
|
|
1383
1564
|
case "help":
|
|
1384
1565
|
case "--help":
|
|
1385
1566
|
case "-h":
|
|
@@ -9,12 +9,13 @@ const DEFAULT_CONFIG = {
|
|
|
9
9
|
tunnels: [],
|
|
10
10
|
projects: []
|
|
11
11
|
};
|
|
12
|
-
/** 读取配置,不存在则创建默认配置;projects 缺 deployDir 时补默认值 'deploy'
|
|
13
|
-
|
|
12
|
+
/** 读取配置,不存在则创建默认配置;projects 缺 deployDir 时补默认值 'deploy'。
|
|
13
|
+
* 首建提示走可注入 log sink(M2-T2 #4),缺省仍打 console.log。 */
|
|
14
|
+
function loadConfig(log = (line) => console.log(line)) {
|
|
14
15
|
if (!existsSync(CONFIG_PATH)) {
|
|
15
16
|
mkdirSync(CONFIG_DIR, { recursive: true });
|
|
16
17
|
saveConfig(DEFAULT_CONFIG);
|
|
17
|
-
|
|
18
|
+
log(`[config] 已创建默认配置: ${CONFIG_PATH}`);
|
|
18
19
|
return {
|
|
19
20
|
servers: [],
|
|
20
21
|
tunnels: [],
|
package/dist/main.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-
|
|
1
|
+
import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-DuBKPLi2.js";
|
|
2
2
|
import { Box, Text, createApp, useApp, useInput } from "@vue-tui/runtime";
|
|
3
3
|
import { Fragment, createBlock, createCommentVNode, createElementBlock, createTextVNode, createVNode, defineComponent, nextTick, onMounted, onUnmounted, openBlock, ref, renderList, shallowRef, toDisplayString, watch, withCtx } from "vue";
|
|
4
4
|
import { ScrollBox } from "@vue-tui/components";
|