@nmakarov/cli-toolkit 0.29.0 → 0.33.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 +55 -0
- package/dist/aws.cjs +271 -0
- package/dist/aws.cjs.map +1 -0
- package/dist/aws.js +262 -0
- package/dist/aws.js.map +1 -0
- package/dist/deploy.cjs +1166 -0
- package/dist/deploy.cjs.map +1 -0
- package/dist/deploy.js +1096 -0
- package/dist/deploy.js.map +1 -0
- package/dist/index.cjs +1421 -36
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1370 -16
- package/dist/index.js.map +1 -1
- package/package.json +17 -2
- package/scripts/aws/discover.js +60 -0
- package/scripts/deploy/cli.js +181 -0
package/dist/deploy.js
ADDED
|
@@ -0,0 +1,1096 @@
|
|
|
1
|
+
// src/deploy/service.js
|
|
2
|
+
function deriveRepoDirName(repoUrl) {
|
|
3
|
+
const tail = String(repoUrl ?? "").split("/").pop() ?? "repo";
|
|
4
|
+
return tail.replace(/\.git$/, "") || "repo";
|
|
5
|
+
}
|
|
6
|
+
function defineService(service) {
|
|
7
|
+
if (!service?.name) throw new Error("service manifest needs a `name`");
|
|
8
|
+
if (!service.appsRoot) throw new Error(`service "${service.name}" needs an appsRoot`);
|
|
9
|
+
if (!service.repoUrl) throw new Error(`service "${service.name}" needs a repoUrl`);
|
|
10
|
+
if (!service.pm2?.script) throw new Error(`service "${service.name}" needs pm2.script`);
|
|
11
|
+
const pm2 = {
|
|
12
|
+
appName: service.name,
|
|
13
|
+
args: "",
|
|
14
|
+
...service.pm2
|
|
15
|
+
};
|
|
16
|
+
const nginx = service.nginx ? { siteName: service.name, ...service.nginx } : null;
|
|
17
|
+
return {
|
|
18
|
+
repoDirName: deriveRepoDirName(service.repoUrl),
|
|
19
|
+
repoSubdir: "",
|
|
20
|
+
keepReleases: 3,
|
|
21
|
+
testCommand: null,
|
|
22
|
+
envScrubPatterns: [],
|
|
23
|
+
legacyRepoEnv: null,
|
|
24
|
+
buildInfoPath: "build-info.json",
|
|
25
|
+
deployKey: null,
|
|
26
|
+
requireEnv: false,
|
|
27
|
+
...service,
|
|
28
|
+
pm2,
|
|
29
|
+
nginx
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/deploy/paths.js
|
|
34
|
+
import { join } from "path";
|
|
35
|
+
function servicePaths(service) {
|
|
36
|
+
const root = service.appsRoot;
|
|
37
|
+
const repoDirName = service.repoDirName ?? "repo";
|
|
38
|
+
const repoSubdir = service.repoSubdir ?? "";
|
|
39
|
+
const repo = join(root, repoDirName);
|
|
40
|
+
const repoRun = repoSubdir ? join(repo, repoSubdir) : repo;
|
|
41
|
+
return {
|
|
42
|
+
root,
|
|
43
|
+
repo,
|
|
44
|
+
repoRun,
|
|
45
|
+
repoEnv: join(repoRun, ".env"),
|
|
46
|
+
releases: join(root, "releases"),
|
|
47
|
+
shared: join(root, "shared"),
|
|
48
|
+
logs: join(root, "logs"),
|
|
49
|
+
current: join(root, "current"),
|
|
50
|
+
sharedEnv: join(root, "shared", ".env"),
|
|
51
|
+
ecosystem: join(root, "shared", "ecosystem.config.cjs"),
|
|
52
|
+
deployLog: join(root, "logs", "deploy.log"),
|
|
53
|
+
lockHashFile: join(root, "shared", ".package-lock.sha256")
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function releaseStamp(date = /* @__PURE__ */ new Date()) {
|
|
57
|
+
return date.toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
58
|
+
}
|
|
59
|
+
function releaseDir(releasesRoot, stamp) {
|
|
60
|
+
return join(releasesRoot, stamp);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/deploy/run.js
|
|
64
|
+
import { spawn } from "child_process";
|
|
65
|
+
function npmEnv(baseEnv = process.env) {
|
|
66
|
+
const env = { ...baseEnv };
|
|
67
|
+
delete env.NODE_ENV;
|
|
68
|
+
return env;
|
|
69
|
+
}
|
|
70
|
+
function npmInstallEnv(baseEnv = process.env) {
|
|
71
|
+
return {
|
|
72
|
+
...npmEnv(baseEnv),
|
|
73
|
+
NPM_CONFIG_PRODUCTION: "false",
|
|
74
|
+
npm_config_production: "false"
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function run(cmd, args, options = {}) {
|
|
78
|
+
const { cwd, env, logger } = options;
|
|
79
|
+
return new Promise((resolve2, reject) => {
|
|
80
|
+
logger?.info?.(`$ ${cmd} ${args.join(" ")}${cwd ? ` (cwd=${cwd})` : ""}`);
|
|
81
|
+
const child = spawn(cmd, args, {
|
|
82
|
+
cwd,
|
|
83
|
+
env: env ?? process.env,
|
|
84
|
+
stdio: "inherit"
|
|
85
|
+
});
|
|
86
|
+
child.on("error", reject);
|
|
87
|
+
child.on("close", (code) => {
|
|
88
|
+
if (code === 0) resolve2();
|
|
89
|
+
else reject(new Error(`${cmd} exited with code ${code}`));
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
function runShell(command, options = {}) {
|
|
94
|
+
return run("bash", ["-lc", command], options);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// src/deploy/log.js
|
|
98
|
+
import { appendFile, mkdir } from "fs/promises";
|
|
99
|
+
async function appendDeployLog(deployLogPath, message) {
|
|
100
|
+
await mkdir(deployLogPath.replace(/\/[^/]+$/, ""), { recursive: true });
|
|
101
|
+
const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}
|
|
102
|
+
`;
|
|
103
|
+
await appendFile(deployLogPath, line);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// src/deploy/git.js
|
|
107
|
+
import { access } from "fs/promises";
|
|
108
|
+
async function pathExists(path) {
|
|
109
|
+
try {
|
|
110
|
+
await access(path);
|
|
111
|
+
return true;
|
|
112
|
+
} catch {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function cloneRepo(service, options = {}) {
|
|
117
|
+
const { dryRun = false, logger = console } = options;
|
|
118
|
+
const paths = servicePaths(service);
|
|
119
|
+
if (await pathExists(paths.repo)) {
|
|
120
|
+
throw new Error(`Repo already exists at ${paths.repo} \u2014 use git pull instead`);
|
|
121
|
+
}
|
|
122
|
+
if (dryRun) {
|
|
123
|
+
logger.info(`[dryRun] would git clone ${service.repoUrl} ${paths.repo}`);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
await run("git", ["clone", service.repoUrl, paths.repo], { logger });
|
|
127
|
+
logger.info(`cloned ${service.repoUrl} \u2192 ${paths.repo}`);
|
|
128
|
+
}
|
|
129
|
+
async function pullRepo(service, options = {}) {
|
|
130
|
+
const { dryRun = false, logger = console } = options;
|
|
131
|
+
const paths = servicePaths(service);
|
|
132
|
+
if (!await pathExists(paths.repo)) {
|
|
133
|
+
throw new Error(`Repo missing at ${paths.repo} \u2014 run provision first`);
|
|
134
|
+
}
|
|
135
|
+
if (dryRun) {
|
|
136
|
+
logger.info(`[dryRun] would git -C ${paths.repo} pull --ff-only`);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
await run("git", ["-C", paths.repo, "pull", "--ff-only"], { logger });
|
|
140
|
+
logger.info(`pulled ${paths.repo}`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// src/deploy/release.js
|
|
144
|
+
import { cp, mkdir as mkdir2, readlink, readdir, stat } from "fs/promises";
|
|
145
|
+
import { join as join2, dirname as pathDirname, sep } from "path";
|
|
146
|
+
var SKIP_TOP = /* @__PURE__ */ new Set(["node_modules", ".git"]);
|
|
147
|
+
function shouldCopyEntry(srcPath) {
|
|
148
|
+
const parts = srcPath.split(sep);
|
|
149
|
+
if (parts.some((p) => p === "node_modules" || p === ".git")) return false;
|
|
150
|
+
const top = parts.at(-1);
|
|
151
|
+
if (parts.length === 1 && SKIP_TOP.has(top)) return false;
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
async function createRelease(service, options = {}) {
|
|
155
|
+
const { stamp = releaseStamp(), dryRun = false, logger = console } = options;
|
|
156
|
+
const paths = servicePaths(service);
|
|
157
|
+
const dest = releaseDir(paths.releases, stamp);
|
|
158
|
+
if (dryRun) {
|
|
159
|
+
logger.info(`[dryRun] would copy ${paths.repoRun} \u2192 ${dest}`);
|
|
160
|
+
return { stamp, path: dest };
|
|
161
|
+
}
|
|
162
|
+
await mkdir2(paths.releases, { recursive: true });
|
|
163
|
+
await cp(paths.repoRun, dest, {
|
|
164
|
+
recursive: true,
|
|
165
|
+
filter: (src) => shouldCopyEntry(src)
|
|
166
|
+
});
|
|
167
|
+
logger.info(`release ${stamp} created at ${dest}`);
|
|
168
|
+
return { stamp, path: dest };
|
|
169
|
+
}
|
|
170
|
+
async function readCurrentRelease(paths) {
|
|
171
|
+
try {
|
|
172
|
+
const target = await readlink(paths.current);
|
|
173
|
+
return target.startsWith("/") ? target : join2(pathDirname(paths.current), target);
|
|
174
|
+
} catch {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function listReleases(paths) {
|
|
179
|
+
let names;
|
|
180
|
+
try {
|
|
181
|
+
names = await readdir(paths.releases);
|
|
182
|
+
} catch {
|
|
183
|
+
return [];
|
|
184
|
+
}
|
|
185
|
+
const entries = [];
|
|
186
|
+
for (const name of names) {
|
|
187
|
+
const full = releaseDir(paths.releases, name);
|
|
188
|
+
const s = await stat(full);
|
|
189
|
+
if (s.isDirectory()) entries.push({ name, path: full, mtime: s.mtime });
|
|
190
|
+
}
|
|
191
|
+
entries.sort((a, b) => b.name.localeCompare(a.name));
|
|
192
|
+
return entries;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// src/deploy/activate.js
|
|
196
|
+
import { symlink, unlink } from "fs/promises";
|
|
197
|
+
import { join as join3 } from "path";
|
|
198
|
+
async function activateRelease(releasePath, paths, options = {}) {
|
|
199
|
+
const { dryRun = false, logger = console } = options;
|
|
200
|
+
if (dryRun) {
|
|
201
|
+
logger.info(`[dryRun] would activate ${releasePath} \u2192 ${paths.current}`);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
try {
|
|
205
|
+
await unlink(paths.current);
|
|
206
|
+
} catch {
|
|
207
|
+
}
|
|
208
|
+
await symlink(releasePath, paths.current);
|
|
209
|
+
const envLink = join3(releasePath, ".env");
|
|
210
|
+
try {
|
|
211
|
+
await unlink(envLink);
|
|
212
|
+
} catch {
|
|
213
|
+
}
|
|
214
|
+
await symlink(paths.sharedEnv, envLink);
|
|
215
|
+
logger.info(`active release: ${releasePath}`);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// src/deploy/deps.js
|
|
219
|
+
import { createHash } from "crypto";
|
|
220
|
+
import { access as access2, cp as cp2, mkdir as mkdir3, readFile, rm, writeFile } from "fs/promises";
|
|
221
|
+
import { join as join4 } from "path";
|
|
222
|
+
async function pathExists2(path) {
|
|
223
|
+
try {
|
|
224
|
+
await access2(path);
|
|
225
|
+
return true;
|
|
226
|
+
} catch {
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
async function lockfileHash(releasePath) {
|
|
231
|
+
const lockPath = join4(releasePath, "package-lock.json");
|
|
232
|
+
try {
|
|
233
|
+
const buf = await readFile(lockPath);
|
|
234
|
+
return createHash("sha256").update(buf).digest("hex");
|
|
235
|
+
} catch {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async function readHashFile(path) {
|
|
240
|
+
try {
|
|
241
|
+
return (await readFile(path, "utf8")).trim();
|
|
242
|
+
} catch {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
async function npmInstall(releasePath, hasLock, logger) {
|
|
247
|
+
await rm(join4(releasePath, "node_modules"), { recursive: true, force: true });
|
|
248
|
+
const cmd = hasLock ? ["ci", "--include=dev"] : ["install", "--include=dev", "--no-audit", "--no-fund"];
|
|
249
|
+
logger.info(`running npm ${cmd.join(" ")} in ${releasePath}`);
|
|
250
|
+
await run("npm", cmd, { cwd: releasePath, logger, env: npmInstallEnv() });
|
|
251
|
+
}
|
|
252
|
+
async function installDeps(service, releasePath, paths, options = {}) {
|
|
253
|
+
const { dryRun = false, logger = console } = options;
|
|
254
|
+
if (dryRun) {
|
|
255
|
+
logger.info(`[dryRun] would install deps in ${releasePath}`);
|
|
256
|
+
return { hash: null, copied: false };
|
|
257
|
+
}
|
|
258
|
+
const hash = await lockfileHash(releasePath);
|
|
259
|
+
const hasLock = hash !== null;
|
|
260
|
+
const hashMarker = join4(releasePath, ".deploy-package-lock.sha256");
|
|
261
|
+
const currentPath = await readCurrentRelease(paths);
|
|
262
|
+
let copied = false;
|
|
263
|
+
if (hasLock && currentPath && await pathExists2(join4(currentPath, "node_modules"))) {
|
|
264
|
+
const currentHash = await readHashFile(join4(currentPath, ".deploy-package-lock.sha256"));
|
|
265
|
+
if (currentHash === hash) {
|
|
266
|
+
logger.info("lockfile unchanged \u2014 copying node_modules from current release");
|
|
267
|
+
await cp2(join4(currentPath, "node_modules"), join4(releasePath, "node_modules"), {
|
|
268
|
+
recursive: true,
|
|
269
|
+
force: true
|
|
270
|
+
});
|
|
271
|
+
copied = true;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (!copied) {
|
|
275
|
+
await npmInstall(releasePath, hasLock, logger);
|
|
276
|
+
}
|
|
277
|
+
if (hasLock) {
|
|
278
|
+
await writeFile(hashMarker, `${hash}
|
|
279
|
+
`, "utf8");
|
|
280
|
+
await mkdir3(paths.shared, { recursive: true });
|
|
281
|
+
await writeFile(paths.lockHashFile, `${hash}
|
|
282
|
+
`, "utf8");
|
|
283
|
+
}
|
|
284
|
+
return { hash, copied };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// src/deploy/test.js
|
|
288
|
+
import { symlink as symlink2, unlink as unlink2 } from "fs/promises";
|
|
289
|
+
import { join as join5 } from "path";
|
|
290
|
+
async function runReleaseTests(service, releasePath, paths, options = {}) {
|
|
291
|
+
const { dryRun = false, logger = console } = options;
|
|
292
|
+
if (!service.testCommand) {
|
|
293
|
+
logger.info("no testCommand configured \u2014 skipping tests");
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
if (dryRun) {
|
|
297
|
+
logger.info(`[dryRun] would run "${service.testCommand}" in ${releasePath}`);
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
const envLink = join5(releasePath, ".env");
|
|
301
|
+
try {
|
|
302
|
+
await unlink2(envLink);
|
|
303
|
+
} catch {
|
|
304
|
+
}
|
|
305
|
+
await symlink2(paths.sharedEnv, envLink);
|
|
306
|
+
logger.info(`running "${service.testCommand}" in ${releasePath}`);
|
|
307
|
+
await runShell(service.testCommand, { cwd: releasePath, logger, env: npmInstallEnv() });
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// src/deploy/prune.js
|
|
311
|
+
import { rm as rm2, readlink as readlink2 } from "fs/promises";
|
|
312
|
+
async function pruneReleases(service, paths, options = {}) {
|
|
313
|
+
const { dryRun = false, logger = console } = options;
|
|
314
|
+
const keep = service.keepReleases ?? 3;
|
|
315
|
+
const releases = await listReleases(paths);
|
|
316
|
+
let activeName = null;
|
|
317
|
+
try {
|
|
318
|
+
const target = await readlink2(paths.current);
|
|
319
|
+
activeName = target.split("/").pop();
|
|
320
|
+
} catch {
|
|
321
|
+
}
|
|
322
|
+
const keepSet = /* @__PURE__ */ new Set();
|
|
323
|
+
for (const rel of releases) {
|
|
324
|
+
if (keepSet.size < keep) keepSet.add(rel.name);
|
|
325
|
+
}
|
|
326
|
+
if (activeName) keepSet.add(activeName);
|
|
327
|
+
const toRemove = releases.filter((rel) => !keepSet.has(rel.name));
|
|
328
|
+
for (const rel of toRemove) {
|
|
329
|
+
if (dryRun) {
|
|
330
|
+
logger.info(`[dryRun] would rm -rf ${rel.path}`);
|
|
331
|
+
} else {
|
|
332
|
+
await rm2(rel.path, { recursive: true, force: true });
|
|
333
|
+
logger.info(`pruned ${rel.path}`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return { removed: toRemove.map((r) => r.name) };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// src/deploy/pm2.js
|
|
340
|
+
async function reloadPm2(paths, options = {}) {
|
|
341
|
+
const { dryRun = false, logger = console } = options;
|
|
342
|
+
if (dryRun) {
|
|
343
|
+
logger.info(`[dryRun] would pm2 startOrReload ${paths.ecosystem} --update-env`);
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
await runShell(`pm2 startOrReload "${paths.ecosystem}" --update-env`, { logger });
|
|
347
|
+
logger.info("pm2 reloaded");
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// src/deploy/nginx.js
|
|
351
|
+
import { writeFile as writeFile2 } from "fs/promises";
|
|
352
|
+
import { tmpdir } from "os";
|
|
353
|
+
import { join as join6 } from "path";
|
|
354
|
+
async function hasTlsCert(certPath) {
|
|
355
|
+
try {
|
|
356
|
+
await runShell(`sudo test -f '${certPath}'`, {});
|
|
357
|
+
return true;
|
|
358
|
+
} catch {
|
|
359
|
+
return false;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
function proxyBlock(port) {
|
|
363
|
+
return ` location / {
|
|
364
|
+
proxy_pass http://127.0.0.1:${port};
|
|
365
|
+
proxy_http_version 1.1;
|
|
366
|
+
proxy_set_header Host $host;
|
|
367
|
+
proxy_set_header X-Real-IP $remote_addr;
|
|
368
|
+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
369
|
+
proxy_set_header X-Forwarded-Proto $scheme;
|
|
370
|
+
proxy_read_timeout 120s;
|
|
371
|
+
}`;
|
|
372
|
+
}
|
|
373
|
+
function buildNginxConfig(service) {
|
|
374
|
+
const { nginx, pm2 } = service;
|
|
375
|
+
const certDir = `/etc/letsencrypt/live/${nginx.fqdn}`;
|
|
376
|
+
return `# ${nginx.siteName} \u2014 managed by cli-toolkit deploy (proxy mode)
|
|
377
|
+
# ${nginx.fqdn} \u2192 127.0.0.1:${pm2.port}
|
|
378
|
+
|
|
379
|
+
server {
|
|
380
|
+
listen 80;
|
|
381
|
+
listen [::]:80;
|
|
382
|
+
server_name ${nginx.fqdn};
|
|
383
|
+
location / { return 301 https://$host$request_uri; }
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
server {
|
|
387
|
+
listen 443 ssl;
|
|
388
|
+
listen [::]:443 ssl;
|
|
389
|
+
server_name ${nginx.fqdn};
|
|
390
|
+
|
|
391
|
+
ssl_certificate ${certDir}/fullchain.pem;
|
|
392
|
+
ssl_certificate_key ${certDir}/privkey.pem;
|
|
393
|
+
include /etc/letsencrypt/options-ssl-nginx.conf;
|
|
394
|
+
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
|
|
395
|
+
|
|
396
|
+
client_max_body_size 25m;
|
|
397
|
+
|
|
398
|
+
${proxyBlock(pm2.port)}
|
|
399
|
+
}
|
|
400
|
+
`;
|
|
401
|
+
}
|
|
402
|
+
function buildNginxConfigHttpOnly(service) {
|
|
403
|
+
const { nginx, pm2 } = service;
|
|
404
|
+
return `# ${nginx.siteName} \u2014 managed by cli-toolkit deploy (HTTP proxy, no TLS cert yet)
|
|
405
|
+
|
|
406
|
+
server {
|
|
407
|
+
listen 80;
|
|
408
|
+
listen [::]:80;
|
|
409
|
+
server_name ${nginx.fqdn};
|
|
410
|
+
|
|
411
|
+
client_max_body_size 25m;
|
|
412
|
+
|
|
413
|
+
${proxyBlock(pm2.port)}
|
|
414
|
+
}
|
|
415
|
+
`;
|
|
416
|
+
}
|
|
417
|
+
async function enableNginxUpstream(service, options = {}) {
|
|
418
|
+
const { dryRun = false, logger = console } = options;
|
|
419
|
+
const { nginx } = service;
|
|
420
|
+
if (!nginx) {
|
|
421
|
+
logger.info("no nginx config on service \u2014 skipping nginx step");
|
|
422
|
+
return { skipped: true };
|
|
423
|
+
}
|
|
424
|
+
const siteAvailable = `/etc/nginx/sites-available/${nginx.siteName}`;
|
|
425
|
+
const siteEnabled = `/etc/nginx/sites-enabled/${nginx.siteName}`;
|
|
426
|
+
const cert = `/etc/letsencrypt/live/${nginx.fqdn}/fullchain.pem`;
|
|
427
|
+
if (dryRun) {
|
|
428
|
+
logger.info(`[dryRun] would write ${siteAvailable} (proxy \u2192 127.0.0.1:${service.pm2.port}) and reload nginx`);
|
|
429
|
+
return { hasCert: null };
|
|
430
|
+
}
|
|
431
|
+
const hasCert = await hasTlsCert(cert);
|
|
432
|
+
const config = hasCert ? buildNginxConfig(service) : buildNginxConfigHttpOnly(service);
|
|
433
|
+
const tmp = join6(tmpdir(), `${service.name}-nginx.conf`);
|
|
434
|
+
await writeFile2(tmp, config);
|
|
435
|
+
await runShell(
|
|
436
|
+
`sudo cp '${tmp}' '${siteAvailable}' && sudo ln -sf '${siteAvailable}' '${siteEnabled}' && sudo nginx -t && sudo systemctl reload nginx`,
|
|
437
|
+
{ logger }
|
|
438
|
+
);
|
|
439
|
+
logger.info(`nginx upstream enabled for ${nginx.fqdn} \u2192 127.0.0.1:${service.pm2.port} (tls=${hasCert})`);
|
|
440
|
+
return { hasCert };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// src/deploy/sync-env.js
|
|
444
|
+
import { access as access3, mkdir as mkdir4, readFile as readFile2, writeFile as writeFile3 } from "fs/promises";
|
|
445
|
+
function scrubEnvContent(content, patterns = []) {
|
|
446
|
+
const regexes = patterns.map((p) => p instanceof RegExp ? p : new RegExp(p));
|
|
447
|
+
if (regexes.length === 0) return content;
|
|
448
|
+
return content.split("\n").filter((line) => !regexes.some((re) => re.test(line.trim()))).join("\n");
|
|
449
|
+
}
|
|
450
|
+
async function pathExists3(path) {
|
|
451
|
+
try {
|
|
452
|
+
await access3(path);
|
|
453
|
+
return true;
|
|
454
|
+
} catch {
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
async function syncEnv(service, options = {}) {
|
|
459
|
+
const { dryRun = false, logger = console } = options;
|
|
460
|
+
const paths = servicePaths(service);
|
|
461
|
+
const patterns = service.envScrubPatterns ?? [];
|
|
462
|
+
if (dryRun) {
|
|
463
|
+
logger.info(`[dryRun] would sync ${paths.repoEnv} \u2192 ${paths.sharedEnv}`);
|
|
464
|
+
return { source: paths.repoEnv, dest: paths.sharedEnv };
|
|
465
|
+
}
|
|
466
|
+
let source = paths.repoEnv;
|
|
467
|
+
if (!await pathExists3(source) && service.legacyRepoEnv && await pathExists3(service.legacyRepoEnv)) {
|
|
468
|
+
logger.info(`using legacy env: ${service.legacyRepoEnv}`);
|
|
469
|
+
source = service.legacyRepoEnv;
|
|
470
|
+
}
|
|
471
|
+
await mkdir4(paths.shared, { recursive: true });
|
|
472
|
+
if (!await pathExists3(source)) {
|
|
473
|
+
if (service.requireEnv) {
|
|
474
|
+
throw new Error(
|
|
475
|
+
`No .env found at ${paths.repoEnv}` + (service.legacyRepoEnv ? ` or ${service.legacyRepoEnv}` : "") + " \u2014 place .env on the host or run the remote deploy from a laptop with a local .env (auto-scp)"
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
if (!await pathExists3(paths.sharedEnv)) {
|
|
479
|
+
await writeFile3(paths.sharedEnv, "", { mode: 384 });
|
|
480
|
+
}
|
|
481
|
+
logger.warn(`no .env found (source ${source}) \u2014 using empty ${paths.sharedEnv}`);
|
|
482
|
+
return { source: null, dest: paths.sharedEnv };
|
|
483
|
+
}
|
|
484
|
+
const raw = await readFile2(source, "utf8");
|
|
485
|
+
await writeFile3(paths.sharedEnv, scrubEnvContent(raw, patterns), { mode: 384 });
|
|
486
|
+
logger.info(`synced ${source} \u2192 ${paths.sharedEnv}`);
|
|
487
|
+
return { source, dest: paths.sharedEnv };
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// src/deploy/build-info.js
|
|
491
|
+
import { readFile as readFile3, writeFile as writeFile4, mkdir as mkdir5 } from "fs/promises";
|
|
492
|
+
import { join as join7, dirname } from "path";
|
|
493
|
+
import { execFile } from "child_process";
|
|
494
|
+
import { promisify } from "util";
|
|
495
|
+
var execFileAsync = promisify(execFile);
|
|
496
|
+
function bumpPatchVersion(version) {
|
|
497
|
+
const parts = String(version).trim().split(".");
|
|
498
|
+
const major = Number.parseInt(parts[0], 10) || 0;
|
|
499
|
+
const minor = Number.parseInt(parts[1], 10) || 0;
|
|
500
|
+
const patch = Number.parseInt(parts[2], 10) || 0;
|
|
501
|
+
return `${major}.${minor}.${patch + 1}`;
|
|
502
|
+
}
|
|
503
|
+
async function readJson(path) {
|
|
504
|
+
try {
|
|
505
|
+
return JSON.parse(await readFile3(path, "utf8"));
|
|
506
|
+
} catch {
|
|
507
|
+
return null;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
async function gitShortCommit(repoPath) {
|
|
511
|
+
try {
|
|
512
|
+
const { stdout } = await execFileAsync("git", ["-C", repoPath, "rev-parse", "--short", "HEAD"], {
|
|
513
|
+
encoding: "utf8"
|
|
514
|
+
});
|
|
515
|
+
return stdout.trim() || null;
|
|
516
|
+
} catch {
|
|
517
|
+
return null;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
async function resolveNextVersion(service, paths, pkgPath) {
|
|
521
|
+
const pkg = await readJson(pkgPath) ?? {};
|
|
522
|
+
const baseVersion = pkg.version || "0.1.0";
|
|
523
|
+
const currentPath = await readCurrentRelease(paths);
|
|
524
|
+
if (currentPath) {
|
|
525
|
+
const active = await readJson(join7(currentPath, service.buildInfoPath));
|
|
526
|
+
if (active?.version) return bumpPatchVersion(active.version);
|
|
527
|
+
}
|
|
528
|
+
return baseVersion;
|
|
529
|
+
}
|
|
530
|
+
async function readReleaseBuildInfo(service, releasePath) {
|
|
531
|
+
return readJson(join7(releasePath, service.buildInfoPath));
|
|
532
|
+
}
|
|
533
|
+
async function writeReleaseBuildInfo(service, releasePath, { stamp, dryRun = false, logger = console }) {
|
|
534
|
+
const paths = servicePaths(service);
|
|
535
|
+
const pkgPath = join7(paths.repoRun, "package.json");
|
|
536
|
+
const version = await resolveNextVersion(service, paths, pkgPath);
|
|
537
|
+
const gitCommit = await gitShortCommit(paths.repo);
|
|
538
|
+
const buildInfo = {
|
|
539
|
+
version,
|
|
540
|
+
release: stamp,
|
|
541
|
+
deployedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
542
|
+
gitCommit,
|
|
543
|
+
service: service.name
|
|
544
|
+
};
|
|
545
|
+
const dest = join7(releasePath, service.buildInfoPath);
|
|
546
|
+
if (dryRun) {
|
|
547
|
+
logger.info(`[dryRun] would write ${dest} (${JSON.stringify(buildInfo)})`);
|
|
548
|
+
return buildInfo;
|
|
549
|
+
}
|
|
550
|
+
await mkdir5(dirname(dest), { recursive: true });
|
|
551
|
+
await writeFile4(dest, `${JSON.stringify(buildInfo, null, 2)}
|
|
552
|
+
`, { mode: 420 });
|
|
553
|
+
const gitSuffix = gitCommit ? ` git=${gitCommit}` : "";
|
|
554
|
+
logger.info(`build info: v${version} release=${stamp}${gitSuffix}`);
|
|
555
|
+
return buildInfo;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// src/deploy/init-structure.js
|
|
559
|
+
import { access as access4, appendFile as appendFile2, mkdir as mkdir6, writeFile as writeFile5 } from "fs/promises";
|
|
560
|
+
import { dirname as dirname2, join as join8 } from "path";
|
|
561
|
+
async function pathExists4(path) {
|
|
562
|
+
try {
|
|
563
|
+
await access4(path);
|
|
564
|
+
return true;
|
|
565
|
+
} catch {
|
|
566
|
+
return false;
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
async function requireDeployRoot(parentDir, serviceRoot) {
|
|
570
|
+
if (await pathExists4(parentDir)) return;
|
|
571
|
+
throw new Error(
|
|
572
|
+
`Cannot create ${serviceRoot}: parent directory ${parentDir} does not exist.
|
|
573
|
+
This is meant to run on the target host (where ${parentDir} exists). For a local dry run use --appsRoot=/tmp/<service>.`
|
|
574
|
+
);
|
|
575
|
+
}
|
|
576
|
+
function buildEcosystemConfig(service, paths) {
|
|
577
|
+
const { pm2 } = service;
|
|
578
|
+
const outLog = join8(paths.logs, `${pm2.appName}.out.log`);
|
|
579
|
+
const errLog = join8(paths.logs, `${pm2.appName}.err.log`);
|
|
580
|
+
return `/**
|
|
581
|
+
* pm2 ecosystem for ${service.name} \u2014 seeded by cli-toolkit deploy (init).
|
|
582
|
+
*
|
|
583
|
+
* cwd points at the \`current\` symlink (created on first deploy).
|
|
584
|
+
* Tweak \`args\` here, then: pm2 reload ${paths.ecosystem} --update-env
|
|
585
|
+
*/
|
|
586
|
+
module.exports = {
|
|
587
|
+
apps: [
|
|
588
|
+
{
|
|
589
|
+
name: "${pm2.appName}",
|
|
590
|
+
script: "${pm2.script}",
|
|
591
|
+
cwd: "${paths.current}",
|
|
592
|
+
args: "${pm2.args}",
|
|
593
|
+
instances: 1,
|
|
594
|
+
exec_mode: "fork",
|
|
595
|
+
autorestart: true,
|
|
596
|
+
min_uptime: "10s",
|
|
597
|
+
max_restarts: 10,
|
|
598
|
+
restart_delay: 2000,
|
|
599
|
+
max_memory_restart: "1500M",
|
|
600
|
+
out_file: "${outLog}",
|
|
601
|
+
error_file: "${errLog}",
|
|
602
|
+
merge_logs: true,
|
|
603
|
+
time: true,
|
|
604
|
+
env: {
|
|
605
|
+
NODE_ENV: "production",
|
|
606
|
+
},
|
|
607
|
+
},
|
|
608
|
+
],
|
|
609
|
+
};
|
|
610
|
+
`;
|
|
611
|
+
}
|
|
612
|
+
async function initServiceStructure(service, options = {}) {
|
|
613
|
+
const { dryRun = false, logger = console } = options;
|
|
614
|
+
const paths = servicePaths(service);
|
|
615
|
+
const dirs = [paths.releases, paths.shared, paths.logs];
|
|
616
|
+
const created = [];
|
|
617
|
+
const skipped = [];
|
|
618
|
+
if (!dryRun) {
|
|
619
|
+
await requireDeployRoot(dirname2(paths.root), paths.root);
|
|
620
|
+
}
|
|
621
|
+
for (const dir of dirs) {
|
|
622
|
+
if (await pathExists4(dir)) {
|
|
623
|
+
skipped.push(dir);
|
|
624
|
+
continue;
|
|
625
|
+
}
|
|
626
|
+
if (!dryRun) await mkdir6(dir, { recursive: true });
|
|
627
|
+
created.push(dir);
|
|
628
|
+
}
|
|
629
|
+
let ecosystemCreated = false;
|
|
630
|
+
if (await pathExists4(paths.ecosystem)) {
|
|
631
|
+
skipped.push(paths.ecosystem);
|
|
632
|
+
} else {
|
|
633
|
+
if (!dryRun) {
|
|
634
|
+
await writeFile5(paths.ecosystem, buildEcosystemConfig(service, paths), { mode: 420 });
|
|
635
|
+
}
|
|
636
|
+
ecosystemCreated = true;
|
|
637
|
+
created.push(paths.ecosystem);
|
|
638
|
+
}
|
|
639
|
+
const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] init-structure service=${service.name} dryRun=${dryRun} created=${created.length} skipped=${skipped.length}
|
|
640
|
+
`;
|
|
641
|
+
if (!dryRun) {
|
|
642
|
+
await mkdir6(paths.logs, { recursive: true });
|
|
643
|
+
await appendFile2(paths.deployLog, line);
|
|
644
|
+
}
|
|
645
|
+
logger.info(`service=${service.name} appsRoot=${paths.root}`);
|
|
646
|
+
logger.info(`created: ${created.length ? created.join(", ") : "(none)"}`);
|
|
647
|
+
logger.info(`already present: ${skipped.length ? skipped.join(", ") : "(none)"}`);
|
|
648
|
+
if (ecosystemCreated) logger.info(`seeded ${paths.ecosystem}`);
|
|
649
|
+
return { paths, created, skipped, ecosystemCreated };
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// src/deploy/bootstrap-host.js
|
|
653
|
+
import { execSync } from "child_process";
|
|
654
|
+
import { access as access5, chmod, copyFile, mkdir as mkdir7, readFile as readFile4, writeFile as writeFile6 } from "fs/promises";
|
|
655
|
+
import { homedir } from "os";
|
|
656
|
+
import { basename, join as join9 } from "path";
|
|
657
|
+
async function pathExists5(path) {
|
|
658
|
+
try {
|
|
659
|
+
await access5(path);
|
|
660
|
+
return true;
|
|
661
|
+
} catch {
|
|
662
|
+
return false;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
function expandHome(path) {
|
|
666
|
+
return path.startsWith("~/") ? join9(homedir(), path.slice(2)) : path;
|
|
667
|
+
}
|
|
668
|
+
async function ensurePm2Startup(options = {}) {
|
|
669
|
+
const { user = "ubuntu", dryRun = false, logger = console } = options;
|
|
670
|
+
if (dryRun) {
|
|
671
|
+
logger.info("[dryRun] would configure pm2 startup systemd");
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
try {
|
|
675
|
+
execSync("pm2 ping", { stdio: "ignore" });
|
|
676
|
+
} catch {
|
|
677
|
+
}
|
|
678
|
+
try {
|
|
679
|
+
const out = execSync(`pm2 startup systemd -u ${user} --hp /home/${user}`, { encoding: "utf8" });
|
|
680
|
+
const sudoLine = out.split("\n").find((l) => l.trim().startsWith("sudo"));
|
|
681
|
+
if (sudoLine) {
|
|
682
|
+
execSync(sudoLine.trim(), { stdio: "inherit" });
|
|
683
|
+
logger.info("pm2 startup systemd configured");
|
|
684
|
+
}
|
|
685
|
+
} catch (err) {
|
|
686
|
+
logger.warn(`pm2 startup skipped or already configured: ${err.message}`);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
async function installDeployKey(deployKeyPath, options = {}) {
|
|
690
|
+
const { dryRun = false, logger = console } = options;
|
|
691
|
+
const keyPath = expandHome(deployKeyPath);
|
|
692
|
+
if (!await pathExists5(keyPath)) {
|
|
693
|
+
logger.warn(`deploy key not found at ${keyPath} \u2014 skipping git ssh setup`);
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
const keyBase = basename(keyPath);
|
|
697
|
+
const sshDir = join9(homedir(), ".ssh");
|
|
698
|
+
const destKey = join9(sshDir, keyBase);
|
|
699
|
+
const configPath = join9(sshDir, "config");
|
|
700
|
+
const block = `
|
|
701
|
+
Host github.com
|
|
702
|
+
HostName github.com
|
|
703
|
+
User git
|
|
704
|
+
IdentityFile ${destKey}
|
|
705
|
+
IdentitiesOnly yes
|
|
706
|
+
`;
|
|
707
|
+
if (dryRun) {
|
|
708
|
+
logger.info(`[dryRun] would install deploy key ${keyPath} \u2192 ${destKey}`);
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
await mkdir7(sshDir, { recursive: true, mode: 448 });
|
|
712
|
+
await copyFile(keyPath, destKey);
|
|
713
|
+
await chmod(destKey, 384);
|
|
714
|
+
let config = "";
|
|
715
|
+
if (await pathExists5(configPath)) config = await readFile4(configPath, "utf8");
|
|
716
|
+
if (!config.includes("Host github.com")) {
|
|
717
|
+
await writeFile6(configPath, `${config.trimEnd()}
|
|
718
|
+
${block}
|
|
719
|
+
`, { mode: 384 });
|
|
720
|
+
logger.info("updated ~/.ssh/config for github.com");
|
|
721
|
+
}
|
|
722
|
+
logger.info(`deploy key installed at ${destKey}`);
|
|
723
|
+
}
|
|
724
|
+
async function installLogrotate(service, options = {}) {
|
|
725
|
+
const { dryRun = false, logger = console } = options;
|
|
726
|
+
const conf = `/etc/logrotate.d/${service.name}`;
|
|
727
|
+
const body = `${service.appsRoot}/logs/*.log {
|
|
728
|
+
daily
|
|
729
|
+
rotate 14
|
|
730
|
+
compress
|
|
731
|
+
delaycompress
|
|
732
|
+
missingok
|
|
733
|
+
notifempty
|
|
734
|
+
copytruncate
|
|
735
|
+
}
|
|
736
|
+
`;
|
|
737
|
+
if (dryRun) {
|
|
738
|
+
logger.info(`[dryRun] would write ${conf}`);
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
const tmp = join9("/tmp", `${service.name}-logrotate.conf`);
|
|
742
|
+
await writeFile6(tmp, body);
|
|
743
|
+
await runShell(`sudo cp '${tmp}' '${conf}'`, { logger });
|
|
744
|
+
logger.info(`logrotate config written: ${conf}`);
|
|
745
|
+
}
|
|
746
|
+
async function bootstrapHost(service, options = {}) {
|
|
747
|
+
const { deployKey = service.deployKey, user = "ubuntu", dryRun = false, logger = console } = options;
|
|
748
|
+
await ensurePm2Startup({ user, dryRun, logger });
|
|
749
|
+
if (deployKey) await installDeployKey(deployKey, { dryRun, logger });
|
|
750
|
+
await installLogrotate(service, { dryRun, logger });
|
|
751
|
+
logger.info("bootstrap-host complete");
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// src/deploy/deploy-service.js
|
|
755
|
+
async function deployService(service, options = {}) {
|
|
756
|
+
const {
|
|
757
|
+
dryRun = false,
|
|
758
|
+
skipPull = false,
|
|
759
|
+
skipTests = false,
|
|
760
|
+
skipNginx = false,
|
|
761
|
+
logger = console
|
|
762
|
+
} = options;
|
|
763
|
+
const paths = servicePaths(service);
|
|
764
|
+
await initServiceStructure(service, { dryRun, logger });
|
|
765
|
+
if (!skipPull) await pullRepo(service, { dryRun, logger });
|
|
766
|
+
await syncEnv(service, { dryRun, logger });
|
|
767
|
+
const { stamp, path: releasePath } = await createRelease(service, { dryRun, logger });
|
|
768
|
+
await writeReleaseBuildInfo(service, releasePath, { stamp, dryRun, logger });
|
|
769
|
+
await installDeps(service, releasePath, paths, { dryRun, logger });
|
|
770
|
+
if (!skipTests) await runReleaseTests(service, releasePath, paths, { dryRun, logger });
|
|
771
|
+
await activateRelease(releasePath, paths, { dryRun, logger });
|
|
772
|
+
await pruneReleases(service, paths, { dryRun, logger });
|
|
773
|
+
await reloadPm2(paths, { dryRun, logger });
|
|
774
|
+
if (!skipNginx) await enableNginxUpstream(service, { dryRun, logger });
|
|
775
|
+
const summary = `deploy complete stamp=${stamp} dryRun=${dryRun}`;
|
|
776
|
+
logger.info(summary);
|
|
777
|
+
if (!dryRun) await appendDeployLog(paths.deployLog, summary);
|
|
778
|
+
return { stamp, releasePath };
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
// src/deploy/provision-service.js
|
|
782
|
+
import { access as access6 } from "fs/promises";
|
|
783
|
+
async function pathExists6(path) {
|
|
784
|
+
try {
|
|
785
|
+
await access6(path);
|
|
786
|
+
return true;
|
|
787
|
+
} catch {
|
|
788
|
+
return false;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
async function provisionService(service, options = {}) {
|
|
792
|
+
const {
|
|
793
|
+
dryRun = false,
|
|
794
|
+
deploy = true,
|
|
795
|
+
skipBootstrap = true,
|
|
796
|
+
deployKey,
|
|
797
|
+
logger = console
|
|
798
|
+
} = options;
|
|
799
|
+
if (!skipBootstrap) {
|
|
800
|
+
await bootstrapHost(service, { deployKey, dryRun, logger });
|
|
801
|
+
}
|
|
802
|
+
await initServiceStructure(service, { dryRun, logger });
|
|
803
|
+
const paths = servicePaths(service);
|
|
804
|
+
if (await pathExists6(paths.repo)) {
|
|
805
|
+
logger.info(`repo exists at ${paths.repo} \u2014 pulling`);
|
|
806
|
+
await pullRepo(service, { dryRun, logger });
|
|
807
|
+
} else {
|
|
808
|
+
await cloneRepo(service, { dryRun, logger });
|
|
809
|
+
}
|
|
810
|
+
await syncEnv(service, { dryRun, logger });
|
|
811
|
+
if (deploy) {
|
|
812
|
+
await deployService(service, { dryRun, logger, skipPull: true });
|
|
813
|
+
} else {
|
|
814
|
+
logger.info("provision complete (deploy skipped)");
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// src/deploy/rollback-service.js
|
|
819
|
+
import { readlink as readlink3 } from "fs/promises";
|
|
820
|
+
async function rollbackService(service, options = {}) {
|
|
821
|
+
const { release: targetName, dryRun = false, logger = console } = options;
|
|
822
|
+
const paths = servicePaths(service);
|
|
823
|
+
const releases = await listReleases(paths);
|
|
824
|
+
if (releases.length === 0) throw new Error("No releases to roll back to");
|
|
825
|
+
let activeName = null;
|
|
826
|
+
try {
|
|
827
|
+
const target = await readlink3(paths.current);
|
|
828
|
+
activeName = target.split("/").pop();
|
|
829
|
+
} catch {
|
|
830
|
+
throw new Error("No active release (current symlink missing)");
|
|
831
|
+
}
|
|
832
|
+
let rollbackTarget;
|
|
833
|
+
if (targetName) {
|
|
834
|
+
rollbackTarget = releases.find((r) => r.name === targetName);
|
|
835
|
+
if (!rollbackTarget) throw new Error(`Release not found: ${targetName}`);
|
|
836
|
+
} else {
|
|
837
|
+
rollbackTarget = releases.find((r) => r.name !== activeName);
|
|
838
|
+
if (!rollbackTarget) throw new Error("No previous release to roll back to");
|
|
839
|
+
}
|
|
840
|
+
if (rollbackTarget.name === activeName) throw new Error(`Already on release ${activeName}`);
|
|
841
|
+
logger.info(`rollback ${activeName} \u2192 ${rollbackTarget.name}`);
|
|
842
|
+
const buildInfo = await readReleaseBuildInfo(service, rollbackTarget.path);
|
|
843
|
+
if (buildInfo?.version) {
|
|
844
|
+
logger.info(`rollback target: v${buildInfo.version} release=${buildInfo.release ?? rollbackTarget.name}`);
|
|
845
|
+
}
|
|
846
|
+
await activateRelease(rollbackTarget.path, paths, { dryRun, logger });
|
|
847
|
+
await reloadPm2(paths, { dryRun, logger });
|
|
848
|
+
const summary = `rollback ${activeName} \u2192 ${rollbackTarget.name} dryRun=${dryRun}`;
|
|
849
|
+
if (!dryRun) await appendDeployLog(paths.deployLog, summary);
|
|
850
|
+
return { from: activeName, to: rollbackTarget.name, path: rollbackTarget.path };
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// src/deploy/ssh-remote.js
|
|
854
|
+
import { access as access7, readFile as readFile5, writeFile as writeFile7 } from "fs/promises";
|
|
855
|
+
import { homedir as homedir2, tmpdir as tmpdir2 } from "os";
|
|
856
|
+
import { basename as basename2, dirname as dirname3, join as join10 } from "path";
|
|
857
|
+
import { spawn as spawn2 } from "child_process";
|
|
858
|
+
var REMOTE_CLI_REL = "node_modules/@nmakarov/cli-toolkit/scripts/deploy/cli.js";
|
|
859
|
+
async function pathExists7(path) {
|
|
860
|
+
try {
|
|
861
|
+
await access7(path);
|
|
862
|
+
return true;
|
|
863
|
+
} catch {
|
|
864
|
+
return false;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
function expandHome2(path) {
|
|
868
|
+
return path.startsWith("~/") ? join10(homedir2(), path.slice(2)) : path;
|
|
869
|
+
}
|
|
870
|
+
function resolveLocalEnvPath(envFile) {
|
|
871
|
+
if (envFile) {
|
|
872
|
+
const expanded = expandHome2(envFile);
|
|
873
|
+
return expanded.startsWith("/") ? expanded : join10(process.cwd(), expanded);
|
|
874
|
+
}
|
|
875
|
+
return join10(process.cwd(), ".env");
|
|
876
|
+
}
|
|
877
|
+
function parseGitHost(repoUrl) {
|
|
878
|
+
const u = String(repoUrl ?? "");
|
|
879
|
+
let m = u.match(/^[^@]+@([^:]+):/);
|
|
880
|
+
if (m) return m[1];
|
|
881
|
+
m = u.match(/^ssh:\/\/[^@]+@([^/:]+)/);
|
|
882
|
+
if (m) return m[1];
|
|
883
|
+
return null;
|
|
884
|
+
}
|
|
885
|
+
function shellQuote(value) {
|
|
886
|
+
return `'${String(value).replace(/'/g, `'\\''`)}'`;
|
|
887
|
+
}
|
|
888
|
+
function sshRun(host, remoteCommand, options = {}) {
|
|
889
|
+
const { logger } = options;
|
|
890
|
+
return new Promise((resolve2, reject) => {
|
|
891
|
+
logger?.info?.(`ssh ${host} ${remoteCommand.slice(0, 120)}${remoteCommand.length > 120 ? "\u2026" : ""}`);
|
|
892
|
+
const child = spawn2("ssh", [host, remoteCommand], { stdio: "inherit" });
|
|
893
|
+
child.on("error", reject);
|
|
894
|
+
child.on("close", (code) => code === 0 ? resolve2() : reject(new Error(`ssh ${host} exited with code ${code}`)));
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
function scp(localPath, remoteSpec) {
|
|
898
|
+
return new Promise((resolve2, reject) => {
|
|
899
|
+
const child = spawn2("scp", [localPath, remoteSpec], { stdio: "inherit" });
|
|
900
|
+
child.on("error", reject);
|
|
901
|
+
child.on("close", (code) => code === 0 ? resolve2() : reject(new Error(`scp exited with code ${code}`)));
|
|
902
|
+
});
|
|
903
|
+
}
|
|
904
|
+
async function ensureDeployKeyOnRemote(host, deployKeyPath, options = {}) {
|
|
905
|
+
const { logger = console } = options;
|
|
906
|
+
if (!deployKeyPath) return false;
|
|
907
|
+
const localPath = expandHome2(deployKeyPath);
|
|
908
|
+
if (!await pathExists7(localPath)) return false;
|
|
909
|
+
const keyBase = basename2(localPath);
|
|
910
|
+
logger.info(`copying deploy key ${localPath} \u2192 ${host}:~/.ssh/${keyBase}`);
|
|
911
|
+
await sshRun(host, "mkdir -p ~/.ssh && chmod 700 ~/.ssh", { logger });
|
|
912
|
+
await scp(localPath, `${host}:.ssh/${keyBase}`, { logger });
|
|
913
|
+
await sshRun(host, `chmod 600 ~/.ssh/${keyBase}`, { logger });
|
|
914
|
+
return true;
|
|
915
|
+
}
|
|
916
|
+
async function prepareGitHost(host, options = {}) {
|
|
917
|
+
const { logger = console, gitHost, keyBasename } = options;
|
|
918
|
+
if (!gitHost) return;
|
|
919
|
+
const configBlock = keyBasename ? `if ! grep -q 'Host ${gitHost}' ~/.ssh/config 2>/dev/null; then
|
|
920
|
+
printf '%s\\n' '' 'Host ${gitHost}' ' HostName ${gitHost}' ' User git' ' IdentityFile ~/.ssh/${keyBasename}' ' IdentitiesOnly yes' >> ~/.ssh/config
|
|
921
|
+
chmod 600 ~/.ssh/config
|
|
922
|
+
echo "configured ~/.ssh/config for ${gitHost}"
|
|
923
|
+
fi` : `:`;
|
|
924
|
+
const script = `
|
|
925
|
+
set -euo pipefail
|
|
926
|
+
mkdir -p ~/.ssh
|
|
927
|
+
chmod 700 ~/.ssh
|
|
928
|
+
if ! grep -q '^${gitHost}' ~/.ssh/known_hosts 2>/dev/null; then
|
|
929
|
+
ssh-keyscan -t ed25519,rsa ${gitHost} >> ~/.ssh/known_hosts 2>/dev/null
|
|
930
|
+
echo "added ${gitHost} to known_hosts"
|
|
931
|
+
fi
|
|
932
|
+
${configBlock}
|
|
933
|
+
`.trim();
|
|
934
|
+
await sshRun(host, script, { logger });
|
|
935
|
+
}
|
|
936
|
+
async function ensureRepoDependencies(host, service, options = {}) {
|
|
937
|
+
const { logger = console } = options;
|
|
938
|
+
const paths = servicePaths(service);
|
|
939
|
+
const run2 = shellQuote(paths.repoRun);
|
|
940
|
+
await sshRun(
|
|
941
|
+
host,
|
|
942
|
+
`cd ${run2} && if [ ! -d node_modules/@nmakarov/cli-toolkit ] || [ package-lock.json -nt node_modules/.package-lock.json ]; then npm ci; fi`,
|
|
943
|
+
{ logger }
|
|
944
|
+
);
|
|
945
|
+
}
|
|
946
|
+
async function ensureEnvOnRemote(host, service, options = {}) {
|
|
947
|
+
const { logger = console, envFile } = options;
|
|
948
|
+
const paths = servicePaths(service);
|
|
949
|
+
const localPath = resolveLocalEnvPath(envFile);
|
|
950
|
+
if (!await pathExists7(localPath)) return false;
|
|
951
|
+
logger.info(`copying .env ${localPath} \u2192 ${host}:${paths.repoEnv}`);
|
|
952
|
+
await sshRun(host, `mkdir -p ${shellQuote(dirname3(paths.repoEnv))}`, { logger });
|
|
953
|
+
const scrubbed = scrubEnvContent(await readFile5(localPath, "utf8"), service.envScrubPatterns ?? []);
|
|
954
|
+
const tmp = join10(tmpdir2(), `deploy-env-${Date.now()}`);
|
|
955
|
+
await writeFile7(tmp, scrubbed, { mode: 384 });
|
|
956
|
+
await scp(tmp, `${host}:${paths.repoEnv}`, { logger });
|
|
957
|
+
await sshRun(host, `chmod 600 ${shellQuote(paths.repoEnv)}`, { logger });
|
|
958
|
+
return true;
|
|
959
|
+
}
|
|
960
|
+
async function ensureRemoteRepo(host, service, options = {}) {
|
|
961
|
+
const { logger = console, deployKey = service.deployKey, envFile } = options;
|
|
962
|
+
const paths = servicePaths(service);
|
|
963
|
+
const repo = shellQuote(paths.repo);
|
|
964
|
+
const repoUrl = shellQuote(service.repoUrl);
|
|
965
|
+
const root = shellQuote(paths.root);
|
|
966
|
+
const localKeyBase = deployKey ? basename2(expandHome2(deployKey)) : null;
|
|
967
|
+
await ensureDeployKeyOnRemote(host, deployKey, { logger });
|
|
968
|
+
await prepareGitHost(host, { logger, gitHost: parseGitHost(service.repoUrl), keyBasename: localKeyBase });
|
|
969
|
+
await sshRun(
|
|
970
|
+
host,
|
|
971
|
+
`mkdir -p ${root} && if [ -d ${repo}/.git ]; then git -C ${repo} pull --ff-only; else git clone ${repoUrl} ${repo}; fi`,
|
|
972
|
+
{ logger }
|
|
973
|
+
);
|
|
974
|
+
await ensureRepoDependencies(host, service, { logger });
|
|
975
|
+
await ensureEnvOnRemote(host, service, { logger, envFile });
|
|
976
|
+
}
|
|
977
|
+
async function runRemoteCli(host, service, command, args = [], options = {}) {
|
|
978
|
+
const { logger = console, manifests, skipPull = false, deployKey = service.deployKey, envFile } = options;
|
|
979
|
+
const paths = servicePaths(service);
|
|
980
|
+
const run2 = shellQuote(paths.repoRun);
|
|
981
|
+
const cli = shellQuote(REMOTE_CLI_REL);
|
|
982
|
+
if (!skipPull) {
|
|
983
|
+
await ensureRemoteRepo(host, service, { logger, deployKey, envFile });
|
|
984
|
+
} else {
|
|
985
|
+
await ensureRepoDependencies(host, service, { logger });
|
|
986
|
+
await ensureEnvOnRemote(host, service, { logger, envFile });
|
|
987
|
+
}
|
|
988
|
+
const passthrough = [
|
|
989
|
+
`--service=${service.name}`,
|
|
990
|
+
...manifests ? [`--manifests=${manifests}`] : [],
|
|
991
|
+
...args
|
|
992
|
+
].map(shellQuote).join(" ");
|
|
993
|
+
await sshRun(host, `cd ${run2} && node ${cli} ${shellQuote(command)} ${passthrough}`.trim(), { logger });
|
|
994
|
+
}
|
|
995
|
+
async function runRemoteStatus(host, service, options = {}) {
|
|
996
|
+
const { logger = console } = options;
|
|
997
|
+
const paths = servicePaths(service);
|
|
998
|
+
const port = service.pm2.port;
|
|
999
|
+
const app = service.pm2.appName;
|
|
1000
|
+
const script = `
|
|
1001
|
+
echo "=== apps root ==="
|
|
1002
|
+
ls -la ${shellQuote(paths.root)} 2>/dev/null || echo "(missing)"
|
|
1003
|
+
echo ""
|
|
1004
|
+
echo "=== current ==="
|
|
1005
|
+
readlink ${shellQuote(paths.current)} 2>/dev/null || echo "(not set)"
|
|
1006
|
+
echo ""
|
|
1007
|
+
echo "=== releases ==="
|
|
1008
|
+
ls -1 ${shellQuote(paths.releases)} 2>/dev/null || echo "(none)"
|
|
1009
|
+
echo ""
|
|
1010
|
+
echo "=== pm2 ==="
|
|
1011
|
+
pm2 describe ${app} 2>/dev/null | head -20 || pm2 status ${app} 2>/dev/null || echo "(not running)"
|
|
1012
|
+
${port ? `echo ""
|
|
1013
|
+
echo "=== app health (localhost) ==="
|
|
1014
|
+
curl -sf http://127.0.0.1:${port}/healthz 2>/dev/null || echo "(no /healthz on :${port})"` : ""}
|
|
1015
|
+
`.trim();
|
|
1016
|
+
await sshRun(host, script, { logger });
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// src/deploy/manifests.js
|
|
1020
|
+
import { isAbsolute, resolve } from "path";
|
|
1021
|
+
import { pathToFileURL } from "url";
|
|
1022
|
+
async function loadServices({ manifests = "deploy/services.js", cwd = process.cwd() } = {}) {
|
|
1023
|
+
const abs = isAbsolute(manifests) ? manifests : resolve(cwd, manifests);
|
|
1024
|
+
let mod;
|
|
1025
|
+
try {
|
|
1026
|
+
mod = await import(pathToFileURL(abs).href);
|
|
1027
|
+
} catch (err) {
|
|
1028
|
+
throw new Error(`Could not load deploy manifests from ${abs}: ${err.message}`);
|
|
1029
|
+
}
|
|
1030
|
+
const raw = mod.services ?? mod.default;
|
|
1031
|
+
if (!raw) {
|
|
1032
|
+
throw new Error(`Manifests module ${abs} must export \`services\` (or default): a map or array of service manifests`);
|
|
1033
|
+
}
|
|
1034
|
+
const list = Array.isArray(raw) ? raw : Object.values(raw);
|
|
1035
|
+
const out = {};
|
|
1036
|
+
for (const entry of list) {
|
|
1037
|
+
const svc = defineService(entry);
|
|
1038
|
+
out[svc.name] = svc;
|
|
1039
|
+
}
|
|
1040
|
+
return out;
|
|
1041
|
+
}
|
|
1042
|
+
function resolveServiceFrom(serviceMap, name, { appsRoot } = {}) {
|
|
1043
|
+
const svc = serviceMap[name];
|
|
1044
|
+
if (!svc) {
|
|
1045
|
+
throw new Error(`Unknown service "${name}". Known: ${Object.keys(serviceMap).join(", ") || "(none)"}`);
|
|
1046
|
+
}
|
|
1047
|
+
return appsRoot ? { ...svc, appsRoot } : svc;
|
|
1048
|
+
}
|
|
1049
|
+
export {
|
|
1050
|
+
REMOTE_CLI_REL,
|
|
1051
|
+
activateRelease,
|
|
1052
|
+
appendDeployLog,
|
|
1053
|
+
bootstrapHost,
|
|
1054
|
+
bumpPatchVersion,
|
|
1055
|
+
cloneRepo,
|
|
1056
|
+
createRelease,
|
|
1057
|
+
defineService,
|
|
1058
|
+
deployService,
|
|
1059
|
+
deriveRepoDirName,
|
|
1060
|
+
enableNginxUpstream,
|
|
1061
|
+
ensureDeployKeyOnRemote,
|
|
1062
|
+
ensureEnvOnRemote,
|
|
1063
|
+
ensureRemoteRepo,
|
|
1064
|
+
ensureRepoDependencies,
|
|
1065
|
+
initServiceStructure,
|
|
1066
|
+
installDeps,
|
|
1067
|
+
listReleases,
|
|
1068
|
+
loadServices,
|
|
1069
|
+
npmEnv,
|
|
1070
|
+
npmInstallEnv,
|
|
1071
|
+
parseGitHost,
|
|
1072
|
+
prepareGitHost,
|
|
1073
|
+
provisionService,
|
|
1074
|
+
pruneReleases,
|
|
1075
|
+
pullRepo,
|
|
1076
|
+
readCurrentRelease,
|
|
1077
|
+
readReleaseBuildInfo,
|
|
1078
|
+
releaseDir,
|
|
1079
|
+
releaseStamp,
|
|
1080
|
+
reloadPm2,
|
|
1081
|
+
resolveNextVersion,
|
|
1082
|
+
resolveServiceFrom,
|
|
1083
|
+
rollbackService,
|
|
1084
|
+
run,
|
|
1085
|
+
runReleaseTests,
|
|
1086
|
+
runRemoteCli,
|
|
1087
|
+
runRemoteStatus,
|
|
1088
|
+
runShell,
|
|
1089
|
+
scrubEnvContent,
|
|
1090
|
+
servicePaths,
|
|
1091
|
+
shellQuote,
|
|
1092
|
+
sshRun,
|
|
1093
|
+
syncEnv,
|
|
1094
|
+
writeReleaseBuildInfo
|
|
1095
|
+
};
|
|
1096
|
+
//# sourceMappingURL=deploy.js.map
|