easy-devops 1.2.1 → 1.3.1
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 +97 -6
- package/dist/ui/assets/index-CMRzkIKj.css +1 -0
- package/dist/ui/assets/index-DEouL3IK.js +452 -0
- package/dist/ui/assets/socket-DwLPrgsr.js +1 -0
- package/dist/ui/assets/socket-K5ttLD2q.js +65 -0
- package/dist/ui/brand/apple-touch-icon.png +0 -0
- package/dist/ui/brand/favicon-16.png +0 -0
- package/dist/ui/brand/favicon-32.png +0 -0
- package/dist/ui/brand/favicon-light-16.png +0 -0
- package/dist/ui/brand/favicon-light-32.png +0 -0
- package/dist/ui/brand/favicon.ico +0 -0
- package/dist/ui/brand/icon-192.png +0 -0
- package/dist/ui/brand/icon-48.png +0 -0
- package/dist/ui/brand/icon-512.png +0 -0
- package/dist/ui/brand/icon-64-light.png +0 -0
- package/dist/ui/brand/icon-64.png +0 -0
- package/dist/ui/brand/logo-dark.png +0 -0
- package/dist/ui/brand/logo-light.png +0 -0
- package/dist/ui/brand/mark-dark.png +0 -0
- package/dist/ui/brand/mark-light.png +0 -0
- package/dist/ui/index.html +71 -0
- package/install.ps1 +188 -1
- package/install.sh +254 -29
- package/package.json +15 -4
- package/src/cli/dash.js +110 -0
- package/src/cli/index.js +237 -106
- package/src/cli/managers/domain-manager.js +60 -40
- package/src/cli/managers/ssl-manager.js +47 -330
- package/src/cli/menu.js +156 -0
- package/src/cli/menus/cleanup.js +205 -0
- package/src/cli/menus/dashboard.js +92 -1
- package/src/cli/menus/runtime.js +236 -0
- package/src/cli/menus/service.js +764 -0
- package/src/cli/menus/settings.js +176 -8
- package/src/cli/menus/uninstall.js +167 -0
- package/src/cli/menus/update.js +222 -47
- package/src/core/acme-challenge.js +273 -0
- package/src/core/cert-operations.js +189 -0
- package/src/{dashboard/lib → core}/cert-reader.js +2 -2
- package/src/core/cert-renewal.js +494 -0
- package/src/core/cleanup.js +600 -0
- package/src/core/config.js +169 -2
- package/src/core/daemon/ipc.js +292 -0
- package/src/core/daemon/lock.js +294 -0
- package/src/core/daemon/run.js +241 -0
- package/src/core/daemon/stopRequest.js +162 -0
- package/src/core/db.js +37 -8
- package/src/core/deploy/apps.js +491 -0
- package/src/core/deploy/domainLink.js +200 -0
- package/src/core/deploy/engine.js +973 -0
- package/src/core/deploy/ezfile.js +361 -0
- package/src/core/deploy/github.js +239 -0
- package/src/core/deploy/githubApi.js +261 -0
- package/src/core/deploy/hookServer.js +325 -0
- package/src/core/deploy/hubCommands.js +267 -0
- package/src/core/deploy/launcher.js +57 -0
- package/src/core/deploy/status.js +91 -0
- package/src/core/deploy/store.js +398 -0
- package/src/core/domainNotifier.js +94 -28
- package/src/core/domains-db.js +234 -0
- package/src/core/events.js +94 -2
- package/src/core/hub/agent.js +842 -0
- package/src/core/hubLink.js +306 -0
- package/src/core/hubPermissions.js +430 -0
- package/src/core/installSource.js +162 -0
- package/src/core/jobs/bus.js +120 -0
- package/src/core/jobs/index.js +371 -0
- package/src/core/jobs/monitors.js +368 -0
- package/src/core/jobs/owner.js +217 -0
- package/src/core/jobs/revisionWatcher.js +106 -0
- package/src/core/nginx-apply.js +213 -0
- package/src/core/nginx-conf-generator.js +253 -17
- package/src/{dashboard/lib → core}/nginx-service.js +18 -9
- package/src/core/notifications/claim.js +214 -0
- package/src/core/notifications/dispatch.js +154 -0
- package/src/core/notifier.js +31 -1
- package/src/core/passwords.js +172 -0
- package/src/core/permissions.js +8 -4
- package/src/core/platform.js +709 -2
- package/src/core/probeCache.js +258 -0
- package/src/core/purge.js +372 -0
- package/src/core/runner.js +488 -0
- package/src/core/service/acl.js +226 -0
- package/src/core/service/dataDir.js +345 -0
- package/src/core/service/index.js +1128 -0
- package/src/core/service/legacy.js +218 -0
- package/src/core/service/runtime.js +446 -0
- package/src/core/service/runtimeUpdate.js +800 -0
- package/src/core/service/systemd.js +458 -0
- package/src/core/service/windowsPersonal.js +530 -0
- package/src/core/service/windowsService.js +576 -0
- package/src/core/service/winsw.js +260 -0
- package/src/core/setupCode.js +331 -0
- package/src/core/shell.js +70 -7
- package/src/core/ssl-issuer.js +627 -0
- package/src/core/updater.js +295 -0
- package/src/core/validators.js +99 -0
- package/src/dashboard/controllers/authController.js +302 -15
- package/src/dashboard/controllers/deploymentsController.js +479 -0
- package/src/dashboard/controllers/domainsController.js +80 -61
- package/src/dashboard/controllers/hubController.js +135 -0
- package/src/dashboard/controllers/nginxController.js +21 -3
- package/src/dashboard/controllers/processesController.js +368 -0
- package/src/dashboard/controllers/settingsController.js +180 -12
- package/src/dashboard/controllers/sslController.js +288 -10
- package/src/dashboard/lib/daemonBridge.js +163 -0
- package/src/dashboard/lib/localRequest.js +235 -0
- package/src/dashboard/lib/loginRateLimit.js +119 -0
- package/src/dashboard/lib/requireAuth.js +80 -0
- package/src/dashboard/public/js/app.js +489 -19
- package/src/dashboard/routes/auth.js +10 -10
- package/src/dashboard/routes/deployments.js +46 -0
- package/src/dashboard/routes/domains.js +9 -0
- package/src/dashboard/routes/hub.js +22 -0
- package/src/dashboard/routes/nginx.js +9 -0
- package/src/dashboard/routes/processes.js +29 -0
- package/src/dashboard/routes/settings.js +9 -0
- package/src/dashboard/routes/ssl.js +10 -0
- package/src/dashboard/server.js +288 -21
- package/src/dashboard/socketManager.js +171 -207
- package/src/dashboard/views/index.ejs +1 -0
- package/src/dashboard/views/partials/login.ejs +68 -7
- package/src/dashboard/views/partials/processes-panel.ejs +261 -0
- package/src/dashboard/views/partials/settings-panel.ejs +287 -0
- package/src/dashboard/views/partials/sidebar.ejs +2 -0
- package/src/dashboard/lib/domains-db.js +0 -51
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* core/deploy/store.js
|
|
3
|
+
*
|
|
4
|
+
* Where a deployed app lives on disk, and the small files that describe it.
|
|
5
|
+
*
|
|
6
|
+
* <dataDir>/deploy/<appId>/
|
|
7
|
+
* releases/<releaseId>/ one checkout per deployment, built in place
|
|
8
|
+
* runs/<runId>.json the record of one deployment attempt
|
|
9
|
+
* logs/<runId>.log its output
|
|
10
|
+
* state.json which release is live, and the one before it
|
|
11
|
+
* deploy.lock held while a deployment is running
|
|
12
|
+
* id_deploy the app's private deploy key, when it has one
|
|
13
|
+
*
|
|
14
|
+
* ── Why files, not the database ──────────────────────────────────────────────
|
|
15
|
+
*
|
|
16
|
+
* A deployment can be started by the dashboard (a button) or by the background
|
|
17
|
+
* service (the deploy hook, the Hub), which are different processes. good.db
|
|
18
|
+
* offers no compare-and-swap, so two processes updating one array of runs
|
|
19
|
+
* would lose writes. Each run is therefore its own file, written atomically
|
|
20
|
+
* (temp file + rename), and the lock is a file created with the exclusive
|
|
21
|
+
* flag. The APP REGISTRY stays in the database (core/deploy/apps.js): it is
|
|
22
|
+
* only ever edited by a person, one request at a time.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import fs from 'fs';
|
|
26
|
+
import path from 'path';
|
|
27
|
+
import crypto from 'crypto';
|
|
28
|
+
|
|
29
|
+
import { getDataDir } from '../platform.js';
|
|
30
|
+
import { dbGet } from '../db.js';
|
|
31
|
+
import { loadConfig } from '../config.js';
|
|
32
|
+
|
|
33
|
+
/** Name of the folder new apps are created in, under the data directory by default. */
|
|
34
|
+
export const DEPLOY_FOLDER = 'ez_deploys';
|
|
35
|
+
/** Where apps lived before the folder was configurable. Apps without a recorded `dir` are still there. */
|
|
36
|
+
const LEGACY_FOLDER = 'deploy';
|
|
37
|
+
|
|
38
|
+
/** How many run records are kept per app. Older ones are deleted with their logs. */
|
|
39
|
+
export const MAX_RUNS_KEPT = 30;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A lock older than this is treated as abandoned even if its pid is alive —
|
|
43
|
+
* the pid may have been reused by an unrelated process after a crash.
|
|
44
|
+
*/
|
|
45
|
+
export const LOCK_STALE_MS = 2 * 60 * 60 * 1000;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A folder path that is safe to put in a shell command between double quotes.
|
|
49
|
+
*
|
|
50
|
+
* The deployments folder is typed by a person and ends up in `git -C "<dir>"`
|
|
51
|
+
* and `pm2 start "<file>"`. Rather than escape it per shell, the characters
|
|
52
|
+
* that could end the quoting or expand inside it are refused outright; nothing
|
|
53
|
+
* a real folder path needs is lost. Spaces are fine.
|
|
54
|
+
*
|
|
55
|
+
* @returns {string|null} An error message, or null when the path is acceptable
|
|
56
|
+
*/
|
|
57
|
+
export function validateDeployDir(dir) {
|
|
58
|
+
if (typeof dir !== 'string' || dir.trim() === '') return 'A folder path is required.';
|
|
59
|
+
const value = dir.trim();
|
|
60
|
+
if (value.length > 400) return 'The path is too long.';
|
|
61
|
+
if (!path.isAbsolute(value)) return 'Use an absolute path, such as /srv/ez_deploys or D:\\ez_deploys.';
|
|
62
|
+
if (/["'`$\r\n\0;&|<>*?%!]/.test(value)) return 'The path contains characters that are not allowed.';
|
|
63
|
+
if (path.parse(path.resolve(value)).root === path.resolve(value)) return 'Choose a folder, not the root of a drive.';
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The default deployments folder: `<data dir>/ez_deploys`. */
|
|
68
|
+
export function defaultDeployRoot(dataDir = getDataDir()) {
|
|
69
|
+
return path.join(dataDir, DEPLOY_FOLDER);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Where NEW apps are created: the `deployDir` setting, or the default.
|
|
74
|
+
*
|
|
75
|
+
* Changing the setting never moves anything. Every app records the folder it
|
|
76
|
+
* was created in (`dir` on its record) and keeps using it; only apps created
|
|
77
|
+
* afterwards land in the new place. Moving an existing app is an explicit
|
|
78
|
+
* action — moveApp() in core/deploy/engine.js.
|
|
79
|
+
*/
|
|
80
|
+
export function deployRoot(dataDir = getDataDir()) {
|
|
81
|
+
let configured = null;
|
|
82
|
+
try { configured = loadConfig()?.deployDir ?? null; } catch { /* unreadable config: use the default */ }
|
|
83
|
+
if (typeof configured === 'string' && validateDeployDir(configured) === null) return path.resolve(configured.trim());
|
|
84
|
+
return defaultDeployRoot(dataDir);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The folder one app lives in.
|
|
89
|
+
*
|
|
90
|
+
* 1. the `dir` on its record — set at creation, changed only by a move;
|
|
91
|
+
* 2. the pre-setting location `<data dir>/deploy/<id>`, when that exists —
|
|
92
|
+
* apps created before the folder was configurable are still there;
|
|
93
|
+
* 3. otherwise where a new app with this id would be created.
|
|
94
|
+
*/
|
|
95
|
+
export function appRoot(appId, dataDir = getDataDir()) {
|
|
96
|
+
let record = null;
|
|
97
|
+
try {
|
|
98
|
+
const apps = dbGet('deployApps');
|
|
99
|
+
record = Array.isArray(apps) ? apps.find((a) => a?.id === appId) ?? null : null;
|
|
100
|
+
} catch { /* fall through to the computed locations */ }
|
|
101
|
+
|
|
102
|
+
if (typeof record?.dir === 'string' && record.dir) return record.dir;
|
|
103
|
+
|
|
104
|
+
const legacy = path.join(dataDir, LEGACY_FOLDER, appId);
|
|
105
|
+
if (fs.existsSync(legacy)) return legacy;
|
|
106
|
+
return path.join(deployRoot(dataDir), appId);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Paths for one app.
|
|
111
|
+
*
|
|
112
|
+
* `appId` is validated by core/deploy/apps.js before it gets anywhere near
|
|
113
|
+
* here; the check below is a second line, because this value becomes a
|
|
114
|
+
* directory name and a traversal would be a write outside the data directory.
|
|
115
|
+
*/
|
|
116
|
+
export function appPaths(appId, dataDir = getDataDir()) {
|
|
117
|
+
if (typeof appId !== 'string' || !/^[a-z0-9][a-z0-9-]{0,39}$/.test(appId)) {
|
|
118
|
+
throw new Error(`Invalid app id: ${JSON.stringify(appId)}`);
|
|
119
|
+
}
|
|
120
|
+
return pathsIn(appRoot(appId, dataDir));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** The same layout, for an explicit folder — used while an app is being moved. */
|
|
124
|
+
export function pathsIn(root) {
|
|
125
|
+
return {
|
|
126
|
+
root,
|
|
127
|
+
releases: path.join(root, 'releases'),
|
|
128
|
+
runs: path.join(root, 'runs'),
|
|
129
|
+
logs: path.join(root, 'logs'),
|
|
130
|
+
state: path.join(root, 'state.json'),
|
|
131
|
+
lock: path.join(root, 'deploy.lock'),
|
|
132
|
+
deployKey: path.join(root, 'id_deploy'),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function ensureAppDirs(appId, dataDir) {
|
|
137
|
+
const p = appPaths(appId, dataDir);
|
|
138
|
+
for (const dir of [p.root, p.releases, p.runs, p.logs]) fs.mkdirSync(dir, { recursive: true });
|
|
139
|
+
return p;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ─── Small atomic JSON files ──────────────────────────────────────────────────
|
|
143
|
+
|
|
144
|
+
function writeJsonAtomic(file, value) {
|
|
145
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
146
|
+
fs.writeFileSync(tmp, JSON.stringify(value, null, 2));
|
|
147
|
+
fs.renameSync(tmp, file);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function readJson(file) {
|
|
151
|
+
try {
|
|
152
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
153
|
+
} catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ─── Ids ──────────────────────────────────────────────────────────────────────
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* A release id: sortable by time, unique, and safe as a directory name on
|
|
162
|
+
* both platforms. e.g. `20261115-214502-3fa9c1`.
|
|
163
|
+
*/
|
|
164
|
+
export function newReleaseId(now = new Date()) {
|
|
165
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
166
|
+
const stamp =
|
|
167
|
+
`${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}-` +
|
|
168
|
+
`${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`;
|
|
169
|
+
return `${stamp}-${crypto.randomBytes(3).toString('hex')}`;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** True for a string shaped like an id this module generates. */
|
|
173
|
+
export function isId(value) {
|
|
174
|
+
return typeof value === 'string' && /^[0-9]{8}-[0-9]{6}-[0-9a-f]{6}$/.test(value);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ─── State ────────────────────────────────────────────────────────────────────
|
|
178
|
+
|
|
179
|
+
/** @returns {{ current: string|null, previous: string|null, updatedAt: number|null }} */
|
|
180
|
+
export function readState(appId, dataDir) {
|
|
181
|
+
const s = readJson(appPaths(appId, dataDir).state);
|
|
182
|
+
return {
|
|
183
|
+
current: isId(s?.current) ? s.current : null,
|
|
184
|
+
previous: isId(s?.previous) ? s.previous : null,
|
|
185
|
+
updatedAt: typeof s?.updatedAt === 'number' ? s.updatedAt : null,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function writeState(appId, state, dataDir) {
|
|
190
|
+
ensureAppDirs(appId, dataDir);
|
|
191
|
+
writeJsonAtomic(appPaths(appId, dataDir).state, { ...state, updatedAt: Date.now() });
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// ─── Runs ─────────────────────────────────────────────────────────────────────
|
|
195
|
+
|
|
196
|
+
export function runFile(appId, runId, dataDir) {
|
|
197
|
+
if (!isId(runId)) throw new Error(`Invalid run id: ${JSON.stringify(runId)}`);
|
|
198
|
+
return path.join(appPaths(appId, dataDir).runs, `${runId}.json`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function logFile(appId, runId, dataDir) {
|
|
202
|
+
if (!isId(runId)) throw new Error(`Invalid run id: ${JSON.stringify(runId)}`);
|
|
203
|
+
return path.join(appPaths(appId, dataDir).logs, `${runId}.log`);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function writeRun(run, dataDir) {
|
|
207
|
+
ensureAppDirs(run.appId, dataDir);
|
|
208
|
+
writeJsonAtomic(runFile(run.appId, run.id, dataDir), run);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** @returns {Object|null} */
|
|
212
|
+
export function readRun(appId, runId, dataDir) {
|
|
213
|
+
if (!isId(runId)) return null;
|
|
214
|
+
let file;
|
|
215
|
+
try { file = runFile(appId, runId, dataDir); } catch { return null; }
|
|
216
|
+
const run = readJson(file);
|
|
217
|
+
return run && run.id === runId ? run : null;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Newest first.
|
|
222
|
+
* @returns {Array<Object>}
|
|
223
|
+
*/
|
|
224
|
+
export function listRuns(appId, { limit = MAX_RUNS_KEPT, dataDir } = {}) {
|
|
225
|
+
let names;
|
|
226
|
+
try {
|
|
227
|
+
names = fs.readdirSync(appPaths(appId, dataDir).runs);
|
|
228
|
+
} catch {
|
|
229
|
+
return [];
|
|
230
|
+
}
|
|
231
|
+
return names
|
|
232
|
+
.filter((n) => n.endsWith('.json') && isId(n.slice(0, -5)))
|
|
233
|
+
.sort()
|
|
234
|
+
.reverse()
|
|
235
|
+
.slice(0, limit)
|
|
236
|
+
.map((n) => readRun(appId, n.slice(0, -5), dataDir))
|
|
237
|
+
.filter(Boolean);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Deletes run records (and their logs) beyond the newest MAX_RUNS_KEPT. */
|
|
241
|
+
export function pruneRuns(appId, dataDir) {
|
|
242
|
+
const p = appPaths(appId, dataDir);
|
|
243
|
+
let names;
|
|
244
|
+
try { names = fs.readdirSync(p.runs); } catch { return 0; }
|
|
245
|
+
|
|
246
|
+
const ids = names.filter((n) => n.endsWith('.json')).map((n) => n.slice(0, -5)).filter(isId).sort().reverse();
|
|
247
|
+
let removed = 0;
|
|
248
|
+
for (const id of ids.slice(MAX_RUNS_KEPT)) {
|
|
249
|
+
try { fs.rmSync(path.join(p.runs, `${id}.json`), { force: true }); removed += 1; } catch { /* next time */ }
|
|
250
|
+
try { fs.rmSync(path.join(p.logs, `${id}.log`), { force: true }); } catch { /* next time */ }
|
|
251
|
+
}
|
|
252
|
+
return removed;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The tail of a run's log.
|
|
257
|
+
* @returns {{ text: string, truncated: boolean }}
|
|
258
|
+
*/
|
|
259
|
+
export function readLogTail(appId, runId, { maxBytes = 64 * 1024, dataDir } = {}) {
|
|
260
|
+
let file;
|
|
261
|
+
try { file = logFile(appId, runId, dataDir); } catch { return { text: '', truncated: false }; }
|
|
262
|
+
|
|
263
|
+
let fd;
|
|
264
|
+
try {
|
|
265
|
+
fd = fs.openSync(file, 'r');
|
|
266
|
+
const size = fs.fstatSync(fd).size;
|
|
267
|
+
const start = Math.max(0, size - maxBytes);
|
|
268
|
+
const buf = Buffer.alloc(size - start);
|
|
269
|
+
fs.readSync(fd, buf, 0, buf.length, start);
|
|
270
|
+
let text = buf.toString('utf8');
|
|
271
|
+
// Starting mid-file usually lands inside a line; drop the partial one.
|
|
272
|
+
if (start > 0) text = text.slice(text.indexOf('\n') + 1);
|
|
273
|
+
return { text, truncated: start > 0 };
|
|
274
|
+
} catch {
|
|
275
|
+
return { text: '', truncated: false };
|
|
276
|
+
} finally {
|
|
277
|
+
if (fd !== undefined) { try { fs.closeSync(fd); } catch { /* ignore */ } }
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// ─── Releases ─────────────────────────────────────────────────────────────────
|
|
282
|
+
|
|
283
|
+
export function releaseDir(appId, releaseId, dataDir) {
|
|
284
|
+
if (!isId(releaseId)) throw new Error(`Invalid release id: ${JSON.stringify(releaseId)}`);
|
|
285
|
+
return path.join(appPaths(appId, dataDir).releases, releaseId);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Release ids on disk, newest first. */
|
|
289
|
+
export function listReleases(appId, dataDir) {
|
|
290
|
+
try {
|
|
291
|
+
return fs.readdirSync(appPaths(appId, dataDir).releases, { withFileTypes: true })
|
|
292
|
+
.filter((e) => e.isDirectory() && isId(e.name))
|
|
293
|
+
.map((e) => e.name)
|
|
294
|
+
.sort()
|
|
295
|
+
.reverse();
|
|
296
|
+
} catch {
|
|
297
|
+
return [];
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Removes old releases, keeping the newest `keep` plus anything in `protect`.
|
|
303
|
+
* The live release and the one a rollback would return to are always
|
|
304
|
+
* protected by the caller — deleting either would turn a rollback into an
|
|
305
|
+
* outage.
|
|
306
|
+
*
|
|
307
|
+
* @returns {string[]} The release ids that were removed
|
|
308
|
+
*/
|
|
309
|
+
export function pruneReleases(appId, { keep = 5, protect = [], dataDir } = {}) {
|
|
310
|
+
const all = listReleases(appId, dataDir);
|
|
311
|
+
const guarded = new Set(protect.filter(Boolean));
|
|
312
|
+
const removed = [];
|
|
313
|
+
for (const id of all.slice(Math.max(1, keep))) {
|
|
314
|
+
if (guarded.has(id)) continue;
|
|
315
|
+
try {
|
|
316
|
+
fs.rmSync(releaseDir(appId, id, dataDir), { recursive: true, force: true });
|
|
317
|
+
removed.push(id);
|
|
318
|
+
} catch { /* a file in use (Windows): try again on the next deployment */ }
|
|
319
|
+
}
|
|
320
|
+
return removed;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// ─── The per-app lock ─────────────────────────────────────────────────────────
|
|
324
|
+
|
|
325
|
+
function pidAlive(pid) {
|
|
326
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
327
|
+
try {
|
|
328
|
+
process.kill(pid, 0);
|
|
329
|
+
return true;
|
|
330
|
+
} catch (err) {
|
|
331
|
+
// EPERM means it exists but belongs to someone else — still alive.
|
|
332
|
+
return err.code === 'EPERM';
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Takes the deployment lock for an app.
|
|
338
|
+
*
|
|
339
|
+
* Two deployments of one app at once would build into each other's process
|
|
340
|
+
* list: both would stop and start the same PM2 name. The exclusive-create
|
|
341
|
+
* flag makes taking the lock atomic across processes.
|
|
342
|
+
*
|
|
343
|
+
* @returns {{ ok: true, release: () => void } | { ok: false, reason: string, runId: string|null }}
|
|
344
|
+
*/
|
|
345
|
+
export function acquireLock(appId, { runId = null, dataDir, now = Date.now() } = {}) {
|
|
346
|
+
const p = ensureAppDirs(appId, dataDir);
|
|
347
|
+
const body = JSON.stringify({ pid: process.pid, runId, at: now });
|
|
348
|
+
|
|
349
|
+
const take = () => {
|
|
350
|
+
fs.writeFileSync(p.lock, body, { flag: 'wx' });
|
|
351
|
+
let released = false;
|
|
352
|
+
return {
|
|
353
|
+
ok: true,
|
|
354
|
+
release() {
|
|
355
|
+
if (released) return;
|
|
356
|
+
released = true;
|
|
357
|
+
// Only remove a lock that is still ours: after a stale takeover it is
|
|
358
|
+
// somebody else's, and removing it would let a third deployment in.
|
|
359
|
+
const held = readJson(p.lock);
|
|
360
|
+
if (held?.pid === process.pid && held?.runId === runId) {
|
|
361
|
+
try { fs.rmSync(p.lock, { force: true }); } catch { /* ignore */ }
|
|
362
|
+
}
|
|
363
|
+
},
|
|
364
|
+
};
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
try {
|
|
368
|
+
return take();
|
|
369
|
+
} catch (err) {
|
|
370
|
+
if (err.code !== 'EEXIST') throw err;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const held = readJson(p.lock);
|
|
374
|
+
const stale = !held || !pidAlive(held.pid) || now - (held.at ?? 0) > LOCK_STALE_MS;
|
|
375
|
+
if (!stale) {
|
|
376
|
+
return { ok: false, reason: 'A deployment of this app is already running.', runId: held.runId ?? null };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
try { fs.rmSync(p.lock, { force: true }); } catch { /* raced with another taker */ }
|
|
380
|
+
try {
|
|
381
|
+
return take();
|
|
382
|
+
} catch (err) {
|
|
383
|
+
if (err.code !== 'EEXIST') throw err;
|
|
384
|
+
return { ok: false, reason: 'A deployment of this app is already running.', runId: null };
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** The run currently holding the lock, or null. */
|
|
389
|
+
export function lockHolder(appId, dataDir) {
|
|
390
|
+
const held = readJson(appPaths(appId, dataDir).lock);
|
|
391
|
+
if (!held || !pidAlive(held.pid) || Date.now() - (held.at ?? 0) > LOCK_STALE_MS) return null;
|
|
392
|
+
return { pid: held.pid, runId: held.runId ?? null, at: held.at ?? null };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Removes everything on disk for an app. */
|
|
396
|
+
export function removeAppFiles(appId, dataDir) {
|
|
397
|
+
fs.rmSync(appPaths(appId, dataDir).root, { recursive: true, force: true });
|
|
398
|
+
}
|
|
@@ -220,60 +220,126 @@ export function setNotificationState(domain, eventType, state) {
|
|
|
220
220
|
* @property {string|null} reason - Why (e.g., 'state_changed', 'recovery', 'no_change')
|
|
221
221
|
* @property {string} currentStatus - The new status ('up' or 'down')
|
|
222
222
|
* @property {string|null} previousNotifiedFor - What we previously notified about
|
|
223
|
+
* @property {Object|null} nextState - The state to record once the send succeeds
|
|
223
224
|
*/
|
|
224
225
|
|
|
225
226
|
/**
|
|
226
|
-
*
|
|
227
|
-
*
|
|
228
|
-
*
|
|
227
|
+
* Decides whether a transition is worth notifying about.
|
|
228
|
+
*
|
|
229
|
+
* PURE: this records nothing. It used to write "notified" to the database
|
|
230
|
+
* before the notification was sent, which made a failed send invisible — the
|
|
231
|
+
* state already claimed it had gone out, so it was never retried.
|
|
232
|
+
*
|
|
233
|
+
* The caller now does: evaluate -> claim -> send -> commit, and releases the
|
|
234
|
+
* claim if the send fails. See core/notifications/claim.js and
|
|
235
|
+
* core/notifications/dispatch.js.
|
|
236
|
+
*
|
|
237
|
+
* nextState is what commitNotification() should persist. It is returned even
|
|
238
|
+
* when shouldNotify is false, because the first sighting of a domain still has
|
|
239
|
+
* to be recorded — it just must not produce a notification.
|
|
229
240
|
*
|
|
230
241
|
* @param {string|null} domain - null for global events
|
|
231
242
|
* @param {string} eventType
|
|
232
243
|
* @param {string} currentStatus - 'up' or 'down'
|
|
233
244
|
* @returns {NotificationDecision}
|
|
234
245
|
*/
|
|
235
|
-
export function
|
|
246
|
+
export function evaluateTransition(domain, eventType, currentStatus) {
|
|
236
247
|
const previousState = getNotificationState(domain, eventType);
|
|
237
248
|
const previousNotifiedFor = previousState.notifiedFor;
|
|
238
249
|
|
|
239
|
-
// Normalize status to 'up' or 'down'
|
|
240
250
|
const status = currentStatus === 'up' || currentStatus === 'down' ? currentStatus : 'unknown';
|
|
241
251
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
// First time seeing this domain/event - don't notify, just record state
|
|
252
|
+
// First time seeing this domain/event: record it, never notify. Otherwise
|
|
253
|
+
// every restart would announce everything as newly down.
|
|
245
254
|
if (previousNotifiedFor === null || previousState.status === 'unknown') {
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
255
|
+
return {
|
|
256
|
+
shouldNotify: false,
|
|
257
|
+
reason: 'first_check',
|
|
258
|
+
currentStatus: status,
|
|
259
|
+
previousNotifiedFor: null,
|
|
260
|
+
nextState: { status, lastNotifiedAt: null, notifiedFor: status },
|
|
261
|
+
};
|
|
249
262
|
}
|
|
250
263
|
|
|
251
|
-
// Status unchanged from what we already notified about
|
|
252
264
|
if (previousNotifiedFor === status) {
|
|
253
|
-
|
|
254
|
-
|
|
265
|
+
return {
|
|
266
|
+
shouldNotify: false,
|
|
267
|
+
reason: 'no_change',
|
|
268
|
+
currentStatus: status,
|
|
269
|
+
previousNotifiedFor,
|
|
270
|
+
nextState: null,
|
|
271
|
+
};
|
|
255
272
|
}
|
|
256
273
|
|
|
257
|
-
// Status changed!
|
|
258
274
|
if (status === 'down' && previousNotifiedFor !== 'down') {
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
275
|
+
return {
|
|
276
|
+
shouldNotify: true,
|
|
277
|
+
reason: 'state_changed',
|
|
278
|
+
currentStatus: 'down',
|
|
279
|
+
previousNotifiedFor,
|
|
280
|
+
nextState: { status: 'down', lastNotifiedAt: null, notifiedFor: 'down' },
|
|
281
|
+
};
|
|
263
282
|
}
|
|
264
283
|
|
|
265
284
|
if (status === 'up' && previousNotifiedFor === 'down') {
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
285
|
+
return {
|
|
286
|
+
shouldNotify: true,
|
|
287
|
+
reason: 'recovery',
|
|
288
|
+
currentStatus: 'up',
|
|
289
|
+
previousNotifiedFor: 'down',
|
|
290
|
+
nextState: { status: 'up', lastNotifiedAt: null, notifiedFor: 'up' },
|
|
291
|
+
};
|
|
270
292
|
}
|
|
271
293
|
|
|
272
|
-
//
|
|
273
|
-
//
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
294
|
+
// status is 'unknown', or an up->up with a stale notifiedFor. Record the
|
|
295
|
+
// status so the next real transition is judged against the truth, but say
|
|
296
|
+
// nothing: there is no event here a user would want to hear about.
|
|
297
|
+
return {
|
|
298
|
+
shouldNotify: false,
|
|
299
|
+
reason: 'edge_case',
|
|
300
|
+
currentStatus: status,
|
|
301
|
+
previousNotifiedFor,
|
|
302
|
+
nextState: { status, lastNotifiedAt: null, notifiedFor: status },
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Records a decision as sent.
|
|
308
|
+
*
|
|
309
|
+
* Call this ONLY after the notification actually went out. The timestamp is
|
|
310
|
+
* stamped here rather than in evaluateTransition(), so lastNotifiedAt always
|
|
311
|
+
* means "when it was really delivered".
|
|
312
|
+
*
|
|
313
|
+
* @param {string|null} domain
|
|
314
|
+
* @param {string} eventType
|
|
315
|
+
* @param {NotificationDecision} decision
|
|
316
|
+
* @param {number} [sentAt]
|
|
317
|
+
*/
|
|
318
|
+
export function commitNotification(domain, eventType, decision, sentAt = Date.now()) {
|
|
319
|
+
if (!decision?.nextState) return;
|
|
320
|
+
|
|
321
|
+
setNotificationState(domain, eventType, {
|
|
322
|
+
...decision.nextState,
|
|
323
|
+
lastNotifiedAt: decision.shouldNotify ? sentAt : decision.nextState.lastNotifiedAt,
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Evaluate and record in one step, with no send in between.
|
|
329
|
+
*
|
|
330
|
+
* Retained for callers that only track state and never notify. It is NOT the
|
|
331
|
+
* path the monitors use: anything that sends must evaluate, claim, send and
|
|
332
|
+
* then commit, so a failed send is retried.
|
|
333
|
+
*
|
|
334
|
+
* @param {string|null} domain
|
|
335
|
+
* @param {string} eventType
|
|
336
|
+
* @param {string} currentStatus
|
|
337
|
+
* @returns {NotificationDecision}
|
|
338
|
+
*/
|
|
339
|
+
export function shouldSendNotification(domain, eventType, currentStatus) {
|
|
340
|
+
const decision = evaluateTransition(domain, eventType, currentStatus);
|
|
341
|
+
commitNotification(domain, eventType, decision);
|
|
342
|
+
return decision;
|
|
277
343
|
}
|
|
278
344
|
|
|
279
345
|
/**
|