@dongnanyang/deploy-cli 0.8.1 → 0.10.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/api.js +2 -0
- package/dist/bin.js +28 -6
- package/dist/{cli-BcnQXZsp.js → cli-CR04-WjM.js} +62 -665
- package/dist/export-helper-CIEcxb5I.js +8 -0
- package/dist/main.js +4 -10
- package/dist/project-BzJoAv1l.js +714 -0
- package/dist/tui/main.js +359 -0
- package/package.json +5 -1
- package/dist/{config-DuBKPLi2.js → config-xUl8Oa3T.js} +1 -1
|
@@ -1,649 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { dirname as dirname$1, join as join$1, resolve as resolve$1 } from "node:path";
|
|
1
|
+
import { _ as certbotProbeCommand, a as generateCompose, b as execFailureMessage, c as loadProject, d as removeProject, g as acmeProbeCommand, h as ACME_BIN, m as PROJECT_LABEL, o as hasComposeMarker, p as COMPOSE_SERVICE_LABEL, r as addProject, s as listProjects, t as COMPOSE_MARKER, v as createNginx, x as run, y as resolveNginxPaths } from "./project-BzJoAv1l.js";
|
|
2
|
+
import { n as loadConfig, r as saveConfig, t as expandPath } from "./config-xUl8Oa3T.js";
|
|
3
|
+
import { accessSync, constants, existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
5
|
import { fileURLToPath } from "node:url";
|
|
7
|
-
import { parse, stringify } from "yaml";
|
|
8
|
-
import { execFileSync, spawn } from "node:child_process";
|
|
9
|
-
//#region src/core/exec.ts
|
|
10
|
-
/**
|
|
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 匹配集补齐)。
|
|
14
|
-
*/
|
|
15
|
-
function stderrSummary(stderr) {
|
|
16
|
-
const lines = stderr.trim().split("\n").filter((line) => line.trim() !== "");
|
|
17
|
-
const errors = lines.filter((line) => /error|fatal|failed|emerg|alert|crit/i.test(line));
|
|
18
|
-
return (errors.length > 0 ? errors.slice(-3) : lines.slice(-3)).join(" ");
|
|
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
|
-
}
|
|
28
|
-
/** 仅 spawn 失败(ENOENT)与超时抛出 */
|
|
29
|
-
var ExecError = class extends Error {
|
|
30
|
-
result;
|
|
31
|
-
constructor(message, result) {
|
|
32
|
-
super(message);
|
|
33
|
-
this.name = "ExecError";
|
|
34
|
-
this.result = result;
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
/** 超时 SIGTERM 后等待子进程退出的宽限时长,超过则 SIGKILL */
|
|
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
|
-
}
|
|
72
|
-
/** 按 \n 切行缓冲,结束时补发无结尾换行的残行 */
|
|
73
|
-
function createLineBuffer(stream, onLine) {
|
|
74
|
-
let buffer = "";
|
|
75
|
-
let text = "";
|
|
76
|
-
/** 回调抛异常跳过该次调用即可,不得影响数据捕获与后续行回调 */
|
|
77
|
-
const emit = (line) => {
|
|
78
|
-
try {
|
|
79
|
-
onLine?.(line, stream);
|
|
80
|
-
} catch {}
|
|
81
|
-
};
|
|
82
|
-
return {
|
|
83
|
-
push(chunk) {
|
|
84
|
-
text += chunk;
|
|
85
|
-
buffer += chunk;
|
|
86
|
-
let index = buffer.indexOf("\n");
|
|
87
|
-
while (index !== -1) {
|
|
88
|
-
const line = buffer.slice(0, index);
|
|
89
|
-
buffer = buffer.slice(index + 1);
|
|
90
|
-
emit(line);
|
|
91
|
-
index = buffer.indexOf("\n");
|
|
92
|
-
}
|
|
93
|
-
},
|
|
94
|
-
/** flush 残行并返回累计全文 */
|
|
95
|
-
flush() {
|
|
96
|
-
if (buffer.length > 0) {
|
|
97
|
-
emit(buffer);
|
|
98
|
-
buffer = "";
|
|
99
|
-
}
|
|
100
|
-
return text;
|
|
101
|
-
}
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
/** 执行命令并捕获退出码与输出 */
|
|
105
|
-
async function run(cmd, args, opts = {}) {
|
|
106
|
-
const cmdLine = [cmd, ...args].join(" ");
|
|
107
|
-
return new Promise((resolve, reject) => {
|
|
108
|
-
const child = spawn(cmd, args, {
|
|
109
|
-
cwd: opts.cwd,
|
|
110
|
-
env: opts.env,
|
|
111
|
-
stdio: [
|
|
112
|
-
"ignore",
|
|
113
|
-
"pipe",
|
|
114
|
-
"pipe"
|
|
115
|
-
]
|
|
116
|
-
});
|
|
117
|
-
const out = createLineBuffer("stdout", opts.onLine);
|
|
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
|
-
};
|
|
128
|
-
let settled = false;
|
|
129
|
-
let timedOut = false;
|
|
130
|
-
let timeoutNote = "";
|
|
131
|
-
let killTimer;
|
|
132
|
-
const timeoutTimer = opts.timeoutMs ? setTimeout(() => {
|
|
133
|
-
timedOut = true;
|
|
134
|
-
timeoutNote = `timeout: ${cmdLine}\n`;
|
|
135
|
-
killTree("SIGTERM");
|
|
136
|
-
killTimer = setTimeout(() => killTree("SIGKILL"), KILL_GRACE_MS);
|
|
137
|
-
}, opts.timeoutMs) : void 0;
|
|
138
|
-
child.stdout?.setEncoding("utf-8");
|
|
139
|
-
child.stderr?.setEncoding("utf-8");
|
|
140
|
-
child.stdout?.on("data", (chunk) => out.push(chunk));
|
|
141
|
-
child.stderr?.on("data", (chunk) => err.push(chunk));
|
|
142
|
-
child.on("error", (error) => {
|
|
143
|
-
if (settled) return;
|
|
144
|
-
settled = true;
|
|
145
|
-
clearTimeout(timeoutTimer);
|
|
146
|
-
clearTimeout(killTimer);
|
|
147
|
-
const message = `spawn 失败: ${cmdLine}: ${error.message}`;
|
|
148
|
-
reject(new ExecError(message, {
|
|
149
|
-
code: 127,
|
|
150
|
-
stdout: out.flush(),
|
|
151
|
-
stderr: `${message}\n`
|
|
152
|
-
}));
|
|
153
|
-
});
|
|
154
|
-
child.on("close", (code) => {
|
|
155
|
-
if (settled) return;
|
|
156
|
-
settled = true;
|
|
157
|
-
clearTimeout(timeoutTimer);
|
|
158
|
-
clearTimeout(killTimer);
|
|
159
|
-
const stderr = err.flush();
|
|
160
|
-
const result = {
|
|
161
|
-
code: code ?? (timedOut ? 124 : 1),
|
|
162
|
-
stdout: out.flush(),
|
|
163
|
-
stderr: stderr + timeoutNote
|
|
164
|
-
};
|
|
165
|
-
if (timedOut) {
|
|
166
|
-
const summary = stderrSummary(stderr);
|
|
167
|
-
reject(new ExecError(`timeout: ${cmdLine}${summary ? `: ${summary}` : ""}`, result));
|
|
168
|
-
return;
|
|
169
|
-
}
|
|
170
|
-
resolve(result);
|
|
171
|
-
});
|
|
172
|
-
});
|
|
173
|
-
}
|
|
174
|
-
//#endregion
|
|
175
|
-
//#region src/core/nginx.ts
|
|
176
|
-
/** conf 命名空间前缀:文件名恒为 deploy-cli-<slug>.conf,前缀由模块拼接,调用方无法绕过 */
|
|
177
|
-
const CONF_PREFIX = "deploy-cli-";
|
|
178
|
-
const CONF_SUFFIX = ".conf";
|
|
179
|
-
/** slug 合法形状(M2-T2 #6 收紧):小写字母数字与连字符、不得连字符开头;项目 name 同用作 slug(F4 前移校验共用) */
|
|
180
|
-
const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
|
|
181
|
-
/** 渲染进 conf 的字段形状校验(防 conf 注入):域名 / 绝对路径 / host:port,统一排除 conf 元字符与空白 */
|
|
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])?)*$/;
|
|
183
|
-
const ABS_PATH_RE = /^\/[A-Za-z0-9._/-]*$/;
|
|
184
|
-
const UPSTREAM_RE = /^(\[[0-9a-fA-F:.]+\]|[A-Za-z0-9.-]+):([0-9]{1,5})$/;
|
|
185
|
-
const DEFAULT_SITES_AVAILABLE = "/etc/nginx/sites-available";
|
|
186
|
-
const DEFAULT_SITES_ENABLED = "/etc/nginx/sites-enabled";
|
|
187
|
-
const DEFAULT_CONF_D = "/etc/nginx/conf.d";
|
|
188
|
-
/** acme.sh 用户级安装目录(R6 约定),requestCert 返回其下证书路径 */
|
|
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
|
-
}
|
|
206
|
-
/** acme.sh --issue 在证书未到期时的跳过退出码(RENEW_SKIP),视同成功 */
|
|
207
|
-
const ACME_RENEW_SKIP = 2;
|
|
208
|
-
/** lstat 判断存在性:坏软链(existsSync 为 false)也算存在,避免 EEXIST */
|
|
209
|
-
function pathExists(path) {
|
|
210
|
-
try {
|
|
211
|
-
lstatSync(path);
|
|
212
|
-
return true;
|
|
213
|
-
} catch {
|
|
214
|
-
return false;
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
/** slug 合法性(防路径穿越与共享 conf 误伤),任何写/删操作前最先校验 */
|
|
218
|
-
function validateSlug(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);
|
|
224
|
-
}
|
|
225
|
-
function validateSpec(spec) {
|
|
226
|
-
validateSlug(spec.slug);
|
|
227
|
-
if (!spec.serverName?.trim()) throw new Error("NginxSiteSpec 缺少 serverName");
|
|
228
|
-
if (!DOMAIN_RE.test(spec.serverName)) throw new Error(`NginxSiteSpec.serverName 非法: ${JSON.stringify(spec.serverName)},仅允许域名字符(字母数字.-,可选 *. 前缀;禁止 conf 元字符与空白)`);
|
|
229
|
-
if ((spec.root !== void 0 && spec.root !== "") === (spec.upstream !== void 0 && spec.upstream !== "")) throw new Error("NginxSiteSpec 需要且仅需要 root(static 型)或 upstream(代理型)之一");
|
|
230
|
-
if (spec.root !== void 0 && spec.root !== "") validateAbsPath("root", spec.root);
|
|
231
|
-
if (spec.upstream !== void 0 && spec.upstream !== "") {
|
|
232
|
-
const match = spec.upstream.match(UPSTREAM_RE);
|
|
233
|
-
if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) throw new Error(`NginxSiteSpec.upstream 非法: ${JSON.stringify(spec.upstream)},须为 host:port(端口 1-65535;禁止 conf 元字符与空白)`);
|
|
234
|
-
}
|
|
235
|
-
if (spec.ssl === "custom" && (!spec.certPath || !spec.keyPath)) throw new Error("ssl:custom 需要 certPath 与 keyPath");
|
|
236
|
-
if (spec.certPath) validateAbsPath("certPath", spec.certPath);
|
|
237
|
-
if (spec.keyPath) validateAbsPath("keyPath", spec.keyPath);
|
|
238
|
-
}
|
|
239
|
-
function validateAbsPath(field, value) {
|
|
240
|
-
if (!ABS_PATH_RE.test(value)) throw new Error(`NginxSiteSpec.${field} 非法: ${JSON.stringify(value)},须为绝对路径且不含 conf 元字符与空白`);
|
|
241
|
-
}
|
|
242
|
-
/** 失败信息:统一走 core/exec 文案模板(M2-T2 #2 壳统一,R12 与 docker.ts 同口径),可附提示,包裹为 ExecError 附完整结果 */
|
|
243
|
-
function execFailure(cmd, args, result, note) {
|
|
244
|
-
return new ExecError(`${note ? `${note}: ` : ""}${execFailureMessage(cmd, args, result)}`, result);
|
|
245
|
-
}
|
|
246
|
-
/**
|
|
247
|
-
* 回滚单项守护(R13):逐项执行,单项失败记 stderr 继续恢复其余项;回滚自身绝不抛错——
|
|
248
|
-
* 不得让回滚异常掩盖 nginx -t / 写盘段的原始错误。
|
|
249
|
-
*/
|
|
250
|
-
function guardedRestore(items) {
|
|
251
|
-
for (const item of items) try {
|
|
252
|
-
item.fn();
|
|
253
|
-
} catch (error) {
|
|
254
|
-
console.error(`[nginx] 回滚 ${item.what} 失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
/** reload 失败统一包装(R13 Minor 4):reject 通道与 code!==0 同 F6 条件化文案;ExecError 保留 result 透传 */
|
|
258
|
-
function wrapReloadFailure(error, note) {
|
|
259
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
260
|
-
if (error instanceof ExecError) return new ExecError(`${note}: ${reason}`, error.result);
|
|
261
|
-
return new Error(`${note}: ${reason}`, { cause: error });
|
|
262
|
-
}
|
|
263
|
-
/**
|
|
264
|
-
* 路径探测:sites-available 与 sites-enabled 同时存在 → sites 模式(软链);否则 conf.d 模式(无软链)。
|
|
265
|
-
* 仅凭 sites-available 存在不足以走 sites 模式:无 sites-enabled 时(nginx.conf 直接 include sites-available/*)
|
|
266
|
-
* 软链无处落地,且 .bak/.new 会被 `include ...*` 通配吸入,破坏回滚与删除的生效性。
|
|
267
|
-
*/
|
|
268
|
-
function resolveNginxPaths(exists = existsSync$1) {
|
|
269
|
-
if (exists(DEFAULT_SITES_AVAILABLE) && exists(DEFAULT_SITES_ENABLED)) return {
|
|
270
|
-
sitesAvailable: DEFAULT_SITES_AVAILABLE,
|
|
271
|
-
sitesEnabled: DEFAULT_SITES_ENABLED
|
|
272
|
-
};
|
|
273
|
-
return { sitesAvailable: DEFAULT_CONF_D };
|
|
274
|
-
}
|
|
275
|
-
/** 渲染 server 块;withSsl 时要求 certPath/keyPath(acme 需先 requestCert 取得) */
|
|
276
|
-
function renderBlock(spec, withSsl) {
|
|
277
|
-
validateSpec(spec);
|
|
278
|
-
if (withSsl && (!spec.certPath || !spec.keyPath)) throw new Error(`ssl:${spec.ssl} 需要 certPath 与 keyPath(acme 需先 requestCert 取得)`);
|
|
279
|
-
const lines = [];
|
|
280
|
-
lines.push(`# ${CONF_PREFIX}${spec.slug}${CONF_SUFFIX} — 由 deploy-cli 管理,请勿手动修改`);
|
|
281
|
-
lines.push("server {");
|
|
282
|
-
lines.push(" listen 80;");
|
|
283
|
-
if (withSsl) lines.push(" listen 443 ssl;");
|
|
284
|
-
lines.push(` server_name ${spec.serverName};`);
|
|
285
|
-
lines.push("");
|
|
286
|
-
if (withSsl) {
|
|
287
|
-
lines.push(` ssl_certificate ${spec.certPath};`);
|
|
288
|
-
lines.push(` ssl_certificate_key ${spec.keyPath};`);
|
|
289
|
-
lines.push("");
|
|
290
|
-
}
|
|
291
|
-
if (spec.root) {
|
|
292
|
-
lines.push(` root ${spec.root};`);
|
|
293
|
-
lines.push("");
|
|
294
|
-
lines.push(" location / {");
|
|
295
|
-
lines.push(" try_files $uri $uri/ =404;");
|
|
296
|
-
lines.push(" }");
|
|
297
|
-
} else {
|
|
298
|
-
lines.push(" location / {");
|
|
299
|
-
lines.push(` proxy_pass http://${spec.upstream};`);
|
|
300
|
-
lines.push(" proxy_set_header Host $host;");
|
|
301
|
-
lines.push(" proxy_set_header X-Real-IP $remote_addr;");
|
|
302
|
-
lines.push(" proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;");
|
|
303
|
-
lines.push(" proxy_set_header X-Forwarded-Proto $scheme;");
|
|
304
|
-
lines.push(" }");
|
|
305
|
-
}
|
|
306
|
-
lines.push("}");
|
|
307
|
-
return lines.join("\n") + "\n";
|
|
308
|
-
}
|
|
309
|
-
function createNginx(runner = run, paths) {
|
|
310
|
-
const resolved = paths ?? resolveNginxPaths();
|
|
311
|
-
const sitesAvailable = resolved.sitesAvailable;
|
|
312
|
-
const sitesEnabled = resolved.sitesEnabled;
|
|
313
|
-
const confName = (slug) => `${CONF_PREFIX}${slug}${CONF_SUFFIX}`;
|
|
314
|
-
const tmpName = (slug) => `.${confName(slug)}.new`;
|
|
315
|
-
const bakName = (slug) => `.${confName(slug)}.bak`;
|
|
316
|
-
/**
|
|
317
|
-
* 写盘/回滚流程:新内容写隐藏 .conf.new → 旧 conf 备份隐藏 .bak → .new 原子改名 → 建 sites-enabled 软链 → nginx -t;
|
|
318
|
-
* 失败:恢复 .bak(或删新文件)、移除本次新建的软链、抛 ExecError;成功:nginx -s reload、清 .bak。
|
|
319
|
-
* 写盘段(写 .new/改名/软链)与 nginx -t 同一回滚口径(M2-T2 #8):段内任一 fs 操作失败即整体恢复再抛出。
|
|
320
|
-
*/
|
|
321
|
-
async function writeSite(slug, content) {
|
|
322
|
-
const conf = join$1(sitesAvailable, confName(slug));
|
|
323
|
-
const tmp = join$1(sitesAvailable, tmpName(slug));
|
|
324
|
-
const bak = join$1(sitesAvailable, bakName(slug));
|
|
325
|
-
const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
|
|
326
|
-
const existed = pathExists(conf);
|
|
327
|
-
const linkCreated = link ? !pathExists(link) : false;
|
|
328
|
-
/** 统一回滚:恢复/清除 conf、软链、.new 临时文件(R13:逐项守护,单项失败记 stderr 继续,回滚不抛) */
|
|
329
|
-
const rollback = () => {
|
|
330
|
-
guardedRestore([
|
|
331
|
-
{
|
|
332
|
-
what: "站点 conf",
|
|
333
|
-
fn: () => {
|
|
334
|
-
if (existed) renameSync(bak, conf);
|
|
335
|
-
else if (pathExists(conf)) unlinkSync(conf);
|
|
336
|
-
}
|
|
337
|
-
},
|
|
338
|
-
{
|
|
339
|
-
what: "软链",
|
|
340
|
-
fn: () => {
|
|
341
|
-
if (link && linkCreated && pathExists(link)) unlinkSync(link);
|
|
342
|
-
}
|
|
343
|
-
},
|
|
344
|
-
{
|
|
345
|
-
what: "临时文件",
|
|
346
|
-
fn: () => {
|
|
347
|
-
if (pathExists(tmp)) unlinkSync(tmp);
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
]);
|
|
351
|
-
};
|
|
352
|
-
try {
|
|
353
|
-
writeFileSync$1(tmp, content, "utf-8");
|
|
354
|
-
if (existed) renameSync(conf, bak);
|
|
355
|
-
renameSync(tmp, conf);
|
|
356
|
-
if (link && linkCreated) symlinkSync(conf, link);
|
|
357
|
-
} catch (error) {
|
|
358
|
-
rollback();
|
|
359
|
-
throw error;
|
|
360
|
-
}
|
|
361
|
-
let test;
|
|
362
|
-
try {
|
|
363
|
-
test = await runner("nginx", ["-t"]);
|
|
364
|
-
} catch (error) {
|
|
365
|
-
rollback();
|
|
366
|
-
throw error;
|
|
367
|
-
}
|
|
368
|
-
if (test.code !== 0) {
|
|
369
|
-
rollback();
|
|
370
|
-
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚站点配置 ${conf}`);
|
|
371
|
-
}
|
|
372
|
-
const reloadNote = existed ? `nginx reload 失败,保留备份 ${bak} 供人工恢复` : `nginx reload 失败(新建站点无备份可回退),conf 已写入 ${conf},可手工 nginx -s reload 重试或删除该 conf`;
|
|
373
|
-
let reload;
|
|
374
|
-
try {
|
|
375
|
-
reload = await runner("nginx", ["-s", "reload"]);
|
|
376
|
-
} catch (error) {
|
|
377
|
-
throw wrapReloadFailure(error, reloadNote);
|
|
378
|
-
}
|
|
379
|
-
if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, reloadNote);
|
|
380
|
-
if (existed) unlinkSync(bak);
|
|
381
|
-
}
|
|
382
|
-
async function requestCert(domain) {
|
|
383
|
-
if (!DOMAIN_RE.test(domain)) throw new Error(`requestCert domain 非法: ${JSON.stringify(domain)},仅允许域名字符(字母数字.-,可选 *. 前缀;禁止元字符与空白)`);
|
|
384
|
-
const acme = acmeProbeCommand();
|
|
385
|
-
if ((await runner(acme.cmd, acme.args)).code === 0) {
|
|
386
|
-
const args = [
|
|
387
|
-
"--issue",
|
|
388
|
-
"--nginx",
|
|
389
|
-
"-d",
|
|
390
|
-
domain
|
|
391
|
-
];
|
|
392
|
-
const result = await runner(ACME_BIN, args);
|
|
393
|
-
if (result.code !== 0 && result.code !== ACME_RENEW_SKIP) throw execFailure(ACME_BIN, args, result, `acme.sh 签发失败: ${domain}`);
|
|
394
|
-
const candidates = [{
|
|
395
|
-
certPath: `${ACME_HOME}/${domain}/fullchain.cer`,
|
|
396
|
-
keyPath: `${ACME_HOME}/${domain}/${domain}.key`
|
|
397
|
-
}, {
|
|
398
|
-
certPath: `${ACME_HOME}/${domain}_ecc/fullchain.cer`,
|
|
399
|
-
keyPath: `${ACME_HOME}/${domain}_ecc/${domain}.key`
|
|
400
|
-
}];
|
|
401
|
-
for (const candidate of candidates) if ((await runner("sh", ["-c", `test -f "${candidate.certPath}"`])).code === 0) return {
|
|
402
|
-
tool: "acme.sh",
|
|
403
|
-
...candidate
|
|
404
|
-
};
|
|
405
|
-
throw new Error(`acme.sh 签发完成但未找到证书文件(已探测 ${candidates.map((c) => c.certPath).join(" 与 ")}),请检查 acme.sh 安装证书目录`);
|
|
406
|
-
}
|
|
407
|
-
const certbot = certbotProbeCommand();
|
|
408
|
-
if ((await runner(certbot.cmd, certbot.args)).code === 0) {
|
|
409
|
-
const args = [
|
|
410
|
-
"--nginx",
|
|
411
|
-
"-d",
|
|
412
|
-
domain,
|
|
413
|
-
"--non-interactive",
|
|
414
|
-
"--agree-tos",
|
|
415
|
-
"--register-unsafely-without-email"
|
|
416
|
-
];
|
|
417
|
-
const result = await runner("certbot", args);
|
|
418
|
-
if (result.code !== 0) throw execFailure("certbot", args, result, `certbot 签发失败: ${domain}`);
|
|
419
|
-
return {
|
|
420
|
-
tool: "certbot",
|
|
421
|
-
certPath: `/etc/letsencrypt/live/${domain}/fullchain.pem`,
|
|
422
|
-
keyPath: `/etc/letsencrypt/live/${domain}/privkey.pem`
|
|
423
|
-
};
|
|
424
|
-
}
|
|
425
|
-
throw new Error(`未找到 acme.sh 或 certbot,无法签发证书(${domain})。请先安装其一(acme.sh: curl https://get.acme.sh | sh)`);
|
|
426
|
-
}
|
|
427
|
-
return {
|
|
428
|
-
async applySite(spec) {
|
|
429
|
-
validateSpec(spec);
|
|
430
|
-
if (spec.ssl === "acme") {
|
|
431
|
-
await writeSite(spec.slug, renderBlock(spec, false));
|
|
432
|
-
let cert;
|
|
433
|
-
try {
|
|
434
|
-
cert = await requestCert(spec.serverName);
|
|
435
|
-
} catch (error) {
|
|
436
|
-
const message = `${error instanceof Error ? error.message : String(error)};注意:HTTP 块已上线(deploy-cli-${spec.slug}.conf 已生效,站点当前仅 HTTP)`;
|
|
437
|
-
if (error instanceof ExecError) throw new ExecError(message, error.result);
|
|
438
|
-
throw new Error(message, { cause: error });
|
|
439
|
-
}
|
|
440
|
-
await writeSite(spec.slug, renderBlock({
|
|
441
|
-
...spec,
|
|
442
|
-
certPath: cert.certPath,
|
|
443
|
-
keyPath: cert.keyPath
|
|
444
|
-
}, true));
|
|
445
|
-
return;
|
|
446
|
-
}
|
|
447
|
-
await writeSite(spec.slug, renderBlock(spec, spec.ssl !== "none"));
|
|
448
|
-
},
|
|
449
|
-
async removeSite(slug) {
|
|
450
|
-
validateSlug(slug);
|
|
451
|
-
const conf = join$1(sitesAvailable, confName(slug));
|
|
452
|
-
if (!pathExists(conf)) throw new Error(`未找到站点配置: ${conf}`);
|
|
453
|
-
const bak = join$1(sitesAvailable, bakName(slug));
|
|
454
|
-
const link = sitesEnabled ? join$1(sitesEnabled, confName(slug)) : void 0;
|
|
455
|
-
const hadLink = link ? pathExists(link) : false;
|
|
456
|
-
/**
|
|
457
|
-
* 与 applySite 同等回滚对等(R2)+ 写盘段同款收口(R13):逐项守护(单项失败记 stderr 继续恢复其余项),
|
|
458
|
-
* 回滚自身绝不抛错;软链仅在缺失时重建(unlink 失败的半删场景下软链仍在,不得 EEXIST 二次伤害)。
|
|
459
|
-
*/
|
|
460
|
-
const rollback = () => {
|
|
461
|
-
guardedRestore([{
|
|
462
|
-
what: "站点 conf",
|
|
463
|
-
fn: () => renameSync(bak, conf)
|
|
464
|
-
}, {
|
|
465
|
-
what: "软链",
|
|
466
|
-
fn: () => {
|
|
467
|
-
if (link && hadLink && !pathExists(link)) symlinkSync(conf, link);
|
|
468
|
-
}
|
|
469
|
-
}]);
|
|
470
|
-
};
|
|
471
|
-
try {
|
|
472
|
-
renameSync(conf, bak);
|
|
473
|
-
if (link && hadLink) unlinkSync(link);
|
|
474
|
-
} catch (error) {
|
|
475
|
-
rollback();
|
|
476
|
-
throw error;
|
|
477
|
-
}
|
|
478
|
-
let test;
|
|
479
|
-
try {
|
|
480
|
-
test = await runner("nginx", ["-t"]);
|
|
481
|
-
} catch (error) {
|
|
482
|
-
rollback();
|
|
483
|
-
throw error;
|
|
484
|
-
}
|
|
485
|
-
if (test.code !== 0) {
|
|
486
|
-
rollback();
|
|
487
|
-
throw execFailure("nginx", ["-t"], test, `nginx -t 校验失败,已回滚删除操作 ${conf}`);
|
|
488
|
-
}
|
|
489
|
-
const reloadNote = `nginx reload 失败,保留备份 ${bak} 供人工恢复`;
|
|
490
|
-
let reload;
|
|
491
|
-
try {
|
|
492
|
-
reload = await runner("nginx", ["-s", "reload"]);
|
|
493
|
-
} catch (error) {
|
|
494
|
-
throw wrapReloadFailure(error, reloadNote);
|
|
495
|
-
}
|
|
496
|
-
if (reload.code !== 0) throw execFailure("nginx", ["-s", "reload"], reload, reloadNote);
|
|
497
|
-
unlinkSync(bak);
|
|
498
|
-
},
|
|
499
|
-
async listSites() {
|
|
500
|
-
return readdirSync$1(sitesAvailable).filter((name) => name.startsWith(CONF_PREFIX) && name.endsWith(CONF_SUFFIX)).map((name) => name.slice(11, -5)).filter((slug) => SLUG_RE.test(slug)).sort();
|
|
501
|
-
},
|
|
502
|
-
requestCert
|
|
503
|
-
};
|
|
504
|
-
}
|
|
505
|
-
//#endregion
|
|
506
|
-
//#region src/core/project.ts
|
|
507
|
-
const VALID_TYPES = [
|
|
508
|
-
"compose",
|
|
509
|
-
"image",
|
|
510
|
-
"static"
|
|
511
|
-
];
|
|
512
|
-
const DEFAULT_COMPOSE_FILE = "docker-compose.yml";
|
|
513
|
-
const VALID_SSL = [
|
|
514
|
-
"none",
|
|
515
|
-
"acme",
|
|
516
|
-
"custom"
|
|
517
|
-
];
|
|
518
|
-
const VALID_UPDATE = ["git-pull", "none"];
|
|
519
|
-
/** deploy.yaml 配置错误;field 指向出问题的字段(如 'type'、'image'、'nginx.domain') */
|
|
520
|
-
var ProjectConfigError = class extends Error {
|
|
521
|
-
field;
|
|
522
|
-
constructor(message, field) {
|
|
523
|
-
super(message);
|
|
524
|
-
this.name = "ProjectConfigError";
|
|
525
|
-
this.field = field;
|
|
526
|
-
}
|
|
527
|
-
};
|
|
528
|
-
/** 读取 <dir>/deploy.yaml 并校验,失败抛 ProjectConfigError */
|
|
529
|
-
function loadProject(dir) {
|
|
530
|
-
const yamlPath = resolve(dir, "deploy.yaml");
|
|
531
|
-
let raw;
|
|
532
|
-
try {
|
|
533
|
-
raw = readFileSync(yamlPath, "utf-8");
|
|
534
|
-
} catch (error) {
|
|
535
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
536
|
-
if (error?.code === "ENOENT") throw new ProjectConfigError(`缺少 deploy.yaml: ${yamlPath}`);
|
|
537
|
-
throw new ProjectConfigError(`读取 deploy.yaml 失败: ${yamlPath}: ${reason}`);
|
|
538
|
-
}
|
|
539
|
-
let parsed;
|
|
540
|
-
try {
|
|
541
|
-
parsed = parse(raw);
|
|
542
|
-
} catch (error) {
|
|
543
|
-
throw new ProjectConfigError(`deploy.yaml 解析失败: ${yamlPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
544
|
-
}
|
|
545
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new ProjectConfigError(`deploy.yaml 应为 YAML 对象: ${yamlPath}`);
|
|
546
|
-
return validate(parsed);
|
|
547
|
-
}
|
|
548
|
-
/** 校验并规范化 deploy.yaml 模型:name(含 slug 形状)→ type 合法性 → 类型必填字段 → nginx.domain 非空 → deploy 段值域 */
|
|
549
|
-
function validate(raw) {
|
|
550
|
-
const name = raw.name;
|
|
551
|
-
if (typeof name !== "string" || name.trim() === "") throw new ProjectConfigError("缺少必填字段: name(项目名不能为空)", "name");
|
|
552
|
-
if (!isValidSlug(name)) throw new ProjectConfigError(`name 非法: ${JSON.stringify(name)},仅允许小写字母、数字与连字符且以字母数字开头(name 将用作 nginx 站点 slug)`, "name");
|
|
553
|
-
const type = raw.type;
|
|
554
|
-
if (type === void 0 || type === null) throw new ProjectConfigError("缺少必填字段: type", "type");
|
|
555
|
-
if (typeof type !== "string" || !VALID_TYPES.includes(type)) throw new ProjectConfigError(`type 非法: ${JSON.stringify(type)},合法值: compose | image | static`, "type");
|
|
556
|
-
if (type === "image" && (typeof raw.image !== "string" || raw.image.trim() === "")) throw new ProjectConfigError("image 型缺少必填字段: image", "image");
|
|
557
|
-
if (type === "static" && (typeof raw.root !== "string" || raw.root.trim() === "")) throw new ProjectConfigError("static 型缺少必填字段: root", "root");
|
|
558
|
-
if (raw.nginx !== void 0 && raw.nginx !== null) {
|
|
559
|
-
const nginx = raw.nginx;
|
|
560
|
-
if (typeof nginx !== "object" || Array.isArray(nginx)) throw new ProjectConfigError("nginx 应为对象", "nginx");
|
|
561
|
-
const n = nginx;
|
|
562
|
-
if (typeof n.domain !== "string" || n.domain.trim() === "") throw new ProjectConfigError("nginx.domain 不能为空", "nginx.domain");
|
|
563
|
-
if (typeof n.ssl !== "string" || !VALID_SSL.includes(n.ssl)) throw new ProjectConfigError("nginx.ssl 缺失或非法,合法值: none | acme | custom", "nginx.ssl");
|
|
564
|
-
}
|
|
565
|
-
if (raw.deploy !== void 0 && raw.deploy !== null) {
|
|
566
|
-
const deploy = raw.deploy;
|
|
567
|
-
if (typeof deploy !== "object" || Array.isArray(deploy)) throw new ProjectConfigError("deploy 应为对象", "deploy");
|
|
568
|
-
const dp = deploy;
|
|
569
|
-
if (dp.update !== void 0 && dp.update !== null) {
|
|
570
|
-
if (typeof dp.update !== "string" || !VALID_UPDATE.includes(dp.update)) throw new ProjectConfigError(`deploy.update 非法: ${JSON.stringify(dp.update)},合法值: git-pull | none(不设=不自动更新)`, "deploy.update");
|
|
571
|
-
}
|
|
572
|
-
if (dp.build !== void 0 && dp.build !== null && typeof dp.build !== "string") throw new ProjectConfigError("deploy.build 应为字符串(构建命令)", "deploy.build");
|
|
573
|
-
for (const hook of ["pre", "post"]) {
|
|
574
|
-
const hooks = dp[hook];
|
|
575
|
-
if (hooks !== void 0 && hooks !== null && (!Array.isArray(hooks) || hooks.some((c) => typeof c !== "string"))) throw new ProjectConfigError(`deploy.${hook} 应为字符串数组(命令列表)`, `deploy.${hook}`);
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
const d = raw;
|
|
579
|
-
if (d.type === "compose" && (d.composeFile === void 0 || d.composeFile === null)) d.composeFile = DEFAULT_COMPOSE_FILE;
|
|
580
|
-
return d;
|
|
581
|
-
}
|
|
582
|
-
/** 列出注册表项目;单个坏配置降级 {config:null,error},不中断其余项目 */
|
|
583
|
-
function listProjects(cfg) {
|
|
584
|
-
return cfg.projects.map((project) => {
|
|
585
|
-
try {
|
|
586
|
-
return {
|
|
587
|
-
name: project.name,
|
|
588
|
-
path: project.path,
|
|
589
|
-
config: loadProject(project.path)
|
|
590
|
-
};
|
|
591
|
-
} catch (error) {
|
|
592
|
-
return {
|
|
593
|
-
name: project.name,
|
|
594
|
-
path: project.path,
|
|
595
|
-
config: null,
|
|
596
|
-
error: error instanceof Error ? error.message : String(error)
|
|
597
|
-
};
|
|
598
|
-
}
|
|
599
|
-
});
|
|
600
|
-
}
|
|
601
|
-
/** 读 <dir>/deploy.yaml 取 name 注册进 cfg.projects(不落盘,由调用方 saveConfig);dir 在核心层 resolve 归一(M2-T2 #9) */
|
|
602
|
-
function addProject(cfg, dir) {
|
|
603
|
-
const normalized = resolve(dir);
|
|
604
|
-
const config = loadProject(normalized);
|
|
605
|
-
const byName = cfg.projects.find((p) => p.name === config.name);
|
|
606
|
-
if (byName) throw new Error(`项目已注册: ${config.name}(${byName.path}),请先 remove 再 add`);
|
|
607
|
-
const byPath = cfg.projects.find((p) => resolve(p.path) === normalized);
|
|
608
|
-
if (byPath) throw new Error(`路径已注册为项目 ${byPath.name}: ${normalized}`);
|
|
609
|
-
const entry = {
|
|
610
|
-
name: config.name,
|
|
611
|
-
path: normalized,
|
|
612
|
-
deployDir: "deploy"
|
|
613
|
-
};
|
|
614
|
-
return {
|
|
615
|
-
...cfg,
|
|
616
|
-
projects: [...cfg.projects, entry]
|
|
617
|
-
};
|
|
618
|
-
}
|
|
619
|
-
/** 从 cfg.projects 注销指定项目(不落盘,由调用方 saveConfig) */
|
|
620
|
-
function removeProject(cfg, name) {
|
|
621
|
-
const projects = cfg.projects.filter((p) => p.name !== name);
|
|
622
|
-
if (projects.length === cfg.projects.length) throw new Error(`未找到项目: ${name}`);
|
|
623
|
-
return {
|
|
624
|
-
...cfg,
|
|
625
|
-
projects
|
|
626
|
-
};
|
|
627
|
-
}
|
|
628
|
-
/** image 型生成的 docker-compose.yml 标记头(护栏 marker):既有同名文件无此头则拒绝覆盖(终审 M1:防绑架项目文件) */
|
|
629
|
-
const COMPOSE_MARKER = "# generated by deploy-cli — do not edit";
|
|
630
|
-
/** marker 判定扫描窗口(A2):不再死盯首行——运维头注释把 marker 挤到前几行仍认;窗口外不认 */
|
|
631
|
-
const MARKER_SCAN_LINES = 10;
|
|
632
|
-
/** 既有文件内容是否带 COMPOSE_MARKER 头(前 10 行内任一行,M2-T2 A2:不再信任首行) */
|
|
633
|
-
function hasComposeMarker(content) {
|
|
634
|
-
return content.split("\n").slice(0, MARKER_SCAN_LINES).some((line) => line.trim() === COMPOSE_MARKER);
|
|
635
|
-
}
|
|
636
|
-
/** image 型 → docker-compose.yml 文本(compose 中 env 的键名为 environment),首行带 COMPOSE_MARKER 标记头 */
|
|
637
|
-
function generateCompose(d) {
|
|
638
|
-
if (d.type !== "image") throw new ProjectConfigError(`generateCompose 仅支持 image 型项目(当前 type: ${d.type})`, "type");
|
|
639
|
-
if (typeof d.image !== "string" || d.image.trim() === "") throw new ProjectConfigError("image 型缺少必填字段: image", "image");
|
|
640
|
-
const service = { image: d.image };
|
|
641
|
-
if (d.ports && d.ports.length > 0) service.ports = d.ports;
|
|
642
|
-
if (d.volumes && d.volumes.length > 0) service.volumes = d.volumes;
|
|
643
|
-
if (d.env && Object.keys(d.env).length > 0) service.environment = d.env;
|
|
644
|
-
return `${COMPOSE_MARKER}\n${stringify({ services: { [d.name]: service } })}`;
|
|
645
|
-
}
|
|
646
|
-
//#endregion
|
|
647
6
|
//#region src/core/docker.ts
|
|
648
7
|
/** docker 调用默认超时(F5:docker daemon 挂起不得永久挂死 CLI),与流水线 600s 长步档同口径;--follow 流式豁免 */
|
|
649
8
|
const DOCKER_TIMEOUT_MS = 6e5;
|
|
@@ -659,6 +18,17 @@ function logsArgs(idOrName, o) {
|
|
|
659
18
|
function adaptOnLine(onLine) {
|
|
660
19
|
return onLine ? (line, stream) => onLine(line, stream) : void 0;
|
|
661
20
|
}
|
|
21
|
+
/** docker ps 的 Labels 字段 → 标签表(M2-T3):模板渲染为逗号分隔 "k=v" 串,个别版本输出对象;空/缺失 → undefined */
|
|
22
|
+
function parseLabels(raw) {
|
|
23
|
+
const out = {};
|
|
24
|
+
if (typeof raw === "string") for (const pair of raw.split(",")) {
|
|
25
|
+
const eq = pair.indexOf("=");
|
|
26
|
+
if (eq <= 0) continue;
|
|
27
|
+
out[pair.slice(0, eq)] = pair.slice(eq + 1);
|
|
28
|
+
}
|
|
29
|
+
else if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) for (const [key, value] of Object.entries(raw)) out[key] = String(value);
|
|
30
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
31
|
+
}
|
|
662
32
|
/** docker ps 一行 json → ContainerInfo;兼容真实 docker 的 ID 大写键与 brief 的 Id */
|
|
663
33
|
function parseContainerLine(line) {
|
|
664
34
|
let raw;
|
|
@@ -674,7 +44,8 @@ function parseContainerLine(line) {
|
|
|
674
44
|
image: String(raw.Image ?? ""),
|
|
675
45
|
state: String(raw.State ?? ""),
|
|
676
46
|
status: String(raw.Status ?? ""),
|
|
677
|
-
ports: String(raw.Ports ?? "")
|
|
47
|
+
ports: String(raw.Ports ?? ""),
|
|
48
|
+
labels: parseLabels(raw.Labels)
|
|
678
49
|
};
|
|
679
50
|
}
|
|
680
51
|
/** 以 shell-out 方式实现的 docker 操作集合 */
|
|
@@ -789,13 +160,18 @@ async function httpProbe(url, timeoutMs = 5e3) {
|
|
|
789
160
|
}
|
|
790
161
|
}
|
|
791
162
|
/**
|
|
792
|
-
*
|
|
793
|
-
*
|
|
794
|
-
*
|
|
795
|
-
*
|
|
163
|
+
* 容器归属判定(M2-T3 归属 label 化):
|
|
164
|
+
* 1. **label 优先**——容器带 `deploy-cli.project` 归属 label 时只认 label(generateCompose 生成的容器都带),
|
|
165
|
+
* 同名段碰撞根治(`happy-app-1` 段匹配会撞上项目 `app`,label 指名 `happy-app` 后不再误配);
|
|
166
|
+
* 2. **无 label 回退**精确名后过滤(历史兼容):docker `--filter name=` 是子串匹配(`app` 会误伤 `myapp`/`application`),
|
|
167
|
+
* 这里要求项目名以完整连字符分段连续出现在容器名中(兼容 compose 的 `<前缀>-<服务名>-<序号>` 命名)。
|
|
168
|
+
* 末段 `-<数字>` 是 compose 副本号而非名字成分,先剥掉再匹配——否则 `...-test-2`(test 的 2 号副本)
|
|
169
|
+
* 会误配名为 `test-2` 的项目;恰以项目名命名的容器(container_name)走全等判定不受剥离影响。
|
|
796
170
|
*/
|
|
797
|
-
function containerBelongsToProject(containerName, projectName) {
|
|
171
|
+
function containerBelongsToProject(containerName, projectName, labels) {
|
|
798
172
|
if (projectName === "") return false;
|
|
173
|
+
const owned = labels?.[PROJECT_LABEL];
|
|
174
|
+
if (owned) return owned === projectName;
|
|
799
175
|
if (containerName === projectName) return true;
|
|
800
176
|
const segments = containerName.replace(/-\d+$/, "").split("-");
|
|
801
177
|
const want = projectName.split("-");
|
|
@@ -803,14 +179,22 @@ function containerBelongsToProject(containerName, projectName) {
|
|
|
803
179
|
return false;
|
|
804
180
|
}
|
|
805
181
|
/**
|
|
806
|
-
* 项目容器集合:docker name 过滤(子串)+
|
|
182
|
+
* 项目容器集合:docker name 过滤(子串)+ label 优先归属过滤(无 label 回退精确名后过滤)。
|
|
807
183
|
* all 语义可选(M2-T2 #14,与 ps --all 口径一致):缺省 true=含已停止容器(status/deploy 现口径不变),
|
|
808
184
|
* false=只查运行中(ps 不带 --all 的口径)。
|
|
185
|
+
* services 过滤(R14/F10):非空时只留 `com.docker.compose.service` 命中声明服务的容器(缺省/空=全部)。
|
|
809
186
|
*/
|
|
810
187
|
async function findProjectContainers(docker, projectName, opts = {}) {
|
|
811
188
|
const listOpts = { name: projectName };
|
|
812
189
|
if (opts.all ?? true) listOpts.all = true;
|
|
813
|
-
|
|
190
|
+
const all = await docker.listContainers(listOpts);
|
|
191
|
+
const wanted = opts.services ?? [];
|
|
192
|
+
return all.filter((c) => {
|
|
193
|
+
if (!containerBelongsToProject(c.name, projectName, c.labels)) return false;
|
|
194
|
+
if (wanted.length === 0) return true;
|
|
195
|
+
const service = c.labels?.[COMPOSE_SERVICE_LABEL];
|
|
196
|
+
return service !== void 0 && wanted.includes(service);
|
|
197
|
+
});
|
|
814
198
|
}
|
|
815
199
|
/** deploy-cli 管理的站点 conf 是否在位;nginx 目录不可读(未装/无权限)→ undefined(未知) */
|
|
816
200
|
async function probeNginxSite(slug, api) {
|
|
@@ -823,7 +207,7 @@ async function probeNginxSite(slug, api) {
|
|
|
823
207
|
/** 项目健康聚合:容器状态 + HTTP 探测 + nginx conf 在位;nginx 判定可注入(M2-T2 #11 测试接缝,缺省 createNginx) */
|
|
824
208
|
async function checkProjectHealth(project, opts) {
|
|
825
209
|
const runner = opts.runner ?? run;
|
|
826
|
-
const containers = await findProjectContainers(opts.docker ?? createDocker(runner), project.name);
|
|
210
|
+
const containers = await findProjectContainers(opts.docker ?? createDocker(runner), project.name, { services: project.services });
|
|
827
211
|
const http = project.healthUrl ? await httpProbe(project.healthUrl) : void 0;
|
|
828
212
|
const nginxPresent = await probeNginxSite(project.name, opts.nginx ?? createNginx(runner));
|
|
829
213
|
return {
|
|
@@ -949,9 +333,9 @@ async function runDeploy(project, opts) {
|
|
|
949
333
|
const upFile = project.type === "image" ? "docker-compose.yml" : composeFile;
|
|
950
334
|
const stopped = await step("up", `docker compose -f ${upFile} up -d`, async () => {
|
|
951
335
|
if (project.type === "image") {
|
|
952
|
-
const target = resolve
|
|
953
|
-
if (existsSync
|
|
954
|
-
writeFileSync
|
|
336
|
+
const target = resolve(opts.cwd, upFile);
|
|
337
|
+
if (existsSync(target) && !hasComposeMarker(readFileSync(target, "utf-8"))) throw new Error(`${upFile} 已存在且非 deploy-cli 生成(缺 marker 头 "${COMPOSE_MARKER}"),拒绝覆盖;请改名/移走该文件,或改用 compose 型项目`);
|
|
338
|
+
writeFileSync(target, generateCompose(project), "utf-8");
|
|
955
339
|
}
|
|
956
340
|
expectOk(await docker.composeUp(opts.cwd, upFile), "docker", [
|
|
957
341
|
"compose",
|
|
@@ -976,7 +360,7 @@ async function runDeploy(project, opts) {
|
|
|
976
360
|
if (!probe.ok) throw new Error(`健康探测失败: ${project.healthUrl}: ${probe.error ?? `HTTP ${probe.status}`}`);
|
|
977
361
|
}
|
|
978
362
|
if (project.type !== "static") {
|
|
979
|
-
if (!(await findProjectContainers(docker, project.name)).some((c) => c.state === "running")) throw new Error(`无运行中容器: ${project.name}(docker ps 未见 running 状态容器)`);
|
|
363
|
+
if (!(await findProjectContainers(docker, project.name, { services: project.services })).some((c) => c.state === "running")) throw new Error(`无运行中容器: ${project.name}(docker ps 未见 running 状态容器)`);
|
|
980
364
|
}
|
|
981
365
|
});
|
|
982
366
|
if (stopped) return stopped;
|
|
@@ -1136,7 +520,8 @@ async function doctor(options = {}) {
|
|
|
1136
520
|
const nginx = await probe(runner, "nginx", ["-v"]);
|
|
1137
521
|
if (nginx.ok) pass(`nginx 可用(${nginx.detail})`);
|
|
1138
522
|
else fail(`nginx 不可用(nginx -v 失败): ${nginx.detail}`);
|
|
1139
|
-
const
|
|
523
|
+
const exists = options.exists ?? existsSync;
|
|
524
|
+
const paths = resolveNginxPaths(exists);
|
|
1140
525
|
if (canWrite(paths.sitesAvailable)) pass(`${paths.sitesAvailable} 可写`);
|
|
1141
526
|
else fail(`${paths.sitesAvailable} 不可写`);
|
|
1142
527
|
if (paths.sitesEnabled) if (canWrite(paths.sitesEnabled)) pass(`${paths.sitesEnabled} 可写`);
|
|
@@ -1417,6 +802,15 @@ async function project(args, options = {}) {
|
|
|
1417
802
|
}
|
|
1418
803
|
//#endregion
|
|
1419
804
|
//#region src/cli/commands/ps.ts
|
|
805
|
+
/** R15①:services 真相源=项目 deploy.yaml(spec 6.1);读不到/坏配置降级不过滤(ps 是诊断工具,不因坏配置拒列容器) */
|
|
806
|
+
function declaredServices(project, options) {
|
|
807
|
+
if (options.servicesOf) return options.servicesOf(project);
|
|
808
|
+
try {
|
|
809
|
+
return loadProject(project.path).services;
|
|
810
|
+
} catch {
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
}
|
|
1420
814
|
const USAGE$2 = `用法: deploy-cli ps [--all] [--project <项目名>]
|
|
1421
815
|
|
|
1422
816
|
选项:
|
|
@@ -1465,7 +859,10 @@ async function ps(args, options = {}) {
|
|
|
1465
859
|
error(`未找到项目: ${projectName}(请检查 ~/.deploy-cli/config.json 的 projects 注册表)`);
|
|
1466
860
|
return 1;
|
|
1467
861
|
}
|
|
1468
|
-
const rows = await findProjectContainers(docker, project.name, {
|
|
862
|
+
const rows = await findProjectContainers(docker, project.name, {
|
|
863
|
+
all,
|
|
864
|
+
services: declaredServices(project, options)
|
|
865
|
+
});
|
|
1469
866
|
log("NAME IMAGE STATE PORTS");
|
|
1470
867
|
for (const container of rows) log(`${container.name}\t${container.image}\t${container.state}\t${container.ports}`);
|
|
1471
868
|
return 0;
|
|
@@ -1581,14 +978,14 @@ const USAGE = `用法:
|
|
|
1581
978
|
const PKG_NAME = "@dongnanyang/deploy-cli";
|
|
1582
979
|
/** 读取 package.json version(M2-T2 #13):自当前模块逐级向上找本包 package.json(构建产物 dist/ 与测试 src/ 均成立) */
|
|
1583
980
|
function readVersion() {
|
|
1584
|
-
let dir = dirname
|
|
981
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
1585
982
|
for (let i = 0; i < 6; i++) {
|
|
1586
|
-
const file = join
|
|
1587
|
-
if (existsSync
|
|
1588
|
-
const pkg = JSON.parse(readFileSync
|
|
983
|
+
const file = join(dir, "package.json");
|
|
984
|
+
if (existsSync(file)) try {
|
|
985
|
+
const pkg = JSON.parse(readFileSync(file, "utf-8"));
|
|
1589
986
|
if (pkg.name === PKG_NAME && typeof pkg.version === "string") return pkg.version;
|
|
1590
987
|
} catch {}
|
|
1591
|
-
const parent = dirname
|
|
988
|
+
const parent = dirname(dir);
|
|
1592
989
|
if (parent === dir) break;
|
|
1593
990
|
dir = parent;
|
|
1594
991
|
}
|