easy-devops 1.2.1 → 1.3.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 +97 -6
- package/dist/ui/assets/index-B6zdwEnG.css +1 -0
- package/dist/ui/assets/index-Cy0oNmul.js +442 -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 +221 -65
- 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 +39 -52
- 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 +171 -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 +9 -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,600 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* core/cleanup.js
|
|
3
|
+
*
|
|
4
|
+
* Finding reclaimable files, and removing only the ones the caller names.
|
|
5
|
+
*
|
|
6
|
+
* ── Dry run first, always ──────────────────────────────────────────────────
|
|
7
|
+
*
|
|
8
|
+
* `scan()` deletes nothing and `apply()` acts only on ids it is handed. That
|
|
9
|
+
* split is the whole safety model: there is no "clean everything" entry point
|
|
10
|
+
* to call by accident, and the CLI prints the inventory with sizes before any
|
|
11
|
+
* confirmation. A disk-reclaiming command that acts first and reports after is
|
|
12
|
+
* one nobody can run twice with confidence.
|
|
13
|
+
*
|
|
14
|
+
* ── What is never listed ───────────────────────────────────────────────────
|
|
15
|
+
*
|
|
16
|
+
* Not "never deleted" — never LISTED, so it cannot be selected either:
|
|
17
|
+
*
|
|
18
|
+
* - the database and its -wal / -shm siblings, and the settings in it
|
|
19
|
+
* - anything under the configured sslDir: certificates, keys, accounts
|
|
20
|
+
* - active nginx .conf files (only `.bak` copies beside them are offered)
|
|
21
|
+
* - the PINNED runtime, and the Node version it points at
|
|
22
|
+
* - the version manager's default alias
|
|
23
|
+
* - any Node version a PM2 app is running
|
|
24
|
+
* - `daemon.stop` — a stop request is not litter. It is what keeps a stopped
|
|
25
|
+
* service stopped until the next logon, so removing it would silently
|
|
26
|
+
* restart something the user stopped on purpose.
|
|
27
|
+
* - a live `daemon.lock` — only one whose owner is provably gone
|
|
28
|
+
*
|
|
29
|
+
* ── Why Node versions are listed but not selected ──────────────────────────
|
|
30
|
+
*
|
|
31
|
+
* Disk-wise they are the biggest item by far, and "unused" is a guess: a
|
|
32
|
+
* version can be in a shell alias, a CI script, another project's .nvmrc, or a
|
|
33
|
+
* PM2 app's recorded exec path. The ones we can prove are in use are excluded
|
|
34
|
+
* outright; the rest are offered with the evidence, and the user chooses. The
|
|
35
|
+
* default selection is empty.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
import fs from 'fs';
|
|
39
|
+
import path from 'path';
|
|
40
|
+
|
|
41
|
+
import { run } from './shell.js';
|
|
42
|
+
import { getDataDir, isWindows, programDataDir, quoteExe } from './platform.js';
|
|
43
|
+
import { loadConfig } from './config.js';
|
|
44
|
+
import { inspect as inspectLock, lockPath } from './daemon/lock.js';
|
|
45
|
+
import { claimDir, CLAIM_TTL_MS } from './notifications/claim.js';
|
|
46
|
+
import { runtimeDir, runtimeNodePath, inspectLink } from './service/runtime.js';
|
|
47
|
+
import { recordedState } from './service/index.js';
|
|
48
|
+
import * as runner from './runner.js';
|
|
49
|
+
|
|
50
|
+
/** Default age before an Easy DevOps log counts as reclaimable. */
|
|
51
|
+
export const DEFAULT_LOG_DAYS = 14;
|
|
52
|
+
|
|
53
|
+
/** The groups, in the order a report should present them. */
|
|
54
|
+
export const GROUPS = Object.freeze([
|
|
55
|
+
'runtime-backups',
|
|
56
|
+
'logs',
|
|
57
|
+
'temp',
|
|
58
|
+
'nginx-bak',
|
|
59
|
+
'pm2-logs',
|
|
60
|
+
'node-versions',
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
// ─── Small filesystem helpers ────────────────────────────────────────────────
|
|
64
|
+
|
|
65
|
+
function sizeOf(target) {
|
|
66
|
+
let total = 0;
|
|
67
|
+
let stat;
|
|
68
|
+
try {
|
|
69
|
+
stat = fs.statSync(target);
|
|
70
|
+
} catch {
|
|
71
|
+
return 0;
|
|
72
|
+
}
|
|
73
|
+
if (!stat.isDirectory()) return stat.size;
|
|
74
|
+
|
|
75
|
+
let entries = [];
|
|
76
|
+
try {
|
|
77
|
+
entries = fs.readdirSync(target);
|
|
78
|
+
} catch {
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
for (const entry of entries) total += sizeOf(path.join(target, entry));
|
|
82
|
+
return total;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function ageDays(target, now) {
|
|
86
|
+
try {
|
|
87
|
+
return (now - fs.statSync(target).mtimeMs) / 86_400_000;
|
|
88
|
+
} catch {
|
|
89
|
+
return 0;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function listDir(dir) {
|
|
94
|
+
try {
|
|
95
|
+
return fs.readdirSync(dir, { withFileTypes: true });
|
|
96
|
+
} catch {
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Human-readable bytes. ASCII only: these lines reach a Windows console. */
|
|
102
|
+
export function humanBytes(bytes) {
|
|
103
|
+
const units = ['B', 'KB', 'MB', 'GB'];
|
|
104
|
+
let value = Number(bytes) || 0;
|
|
105
|
+
let unit = 0;
|
|
106
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
107
|
+
value /= 1024;
|
|
108
|
+
unit += 1;
|
|
109
|
+
}
|
|
110
|
+
return `${value < 10 && unit > 0 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ─── Scanners ────────────────────────────────────────────────────────────────
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Old runtime backups.
|
|
117
|
+
*
|
|
118
|
+
* `node.exe.prev` is what `ezz runtime update` keeps so it can roll back, and
|
|
119
|
+
* `<dataDir>.backup-*` is what the Server-mode data migration keeps. The NEWEST
|
|
120
|
+
* of each kind is held back: it is the one an undo would need.
|
|
121
|
+
*/
|
|
122
|
+
function scanRuntimeBackups({ dataDir, now }) {
|
|
123
|
+
const items = [];
|
|
124
|
+
const dir = runtimeDir(dataDir);
|
|
125
|
+
|
|
126
|
+
const prev = `${runtimeNodePath(dataDir)}.prev`;
|
|
127
|
+
if (fs.existsSync(prev)) {
|
|
128
|
+
items.push({
|
|
129
|
+
group: 'runtime-backups',
|
|
130
|
+
path: prev,
|
|
131
|
+
bytes: sizeOf(prev),
|
|
132
|
+
why: 'the runtime the service used before the last `ezz runtime update`',
|
|
133
|
+
removable: true,
|
|
134
|
+
keep: false,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Smoke-test directories, if a crashed run left one behind.
|
|
139
|
+
const smoke = path.join(dir, 'smoke');
|
|
140
|
+
if (fs.existsSync(smoke)) {
|
|
141
|
+
items.push({
|
|
142
|
+
group: 'runtime-backups',
|
|
143
|
+
path: smoke,
|
|
144
|
+
bytes: sizeOf(smoke),
|
|
145
|
+
why: 'a leftover runtime smoke-test directory',
|
|
146
|
+
removable: true,
|
|
147
|
+
keep: false,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Data-directory backups, newest kept.
|
|
152
|
+
const parent = path.dirname(dataDir);
|
|
153
|
+
const base = `${path.basename(dataDir)}.backup-`;
|
|
154
|
+
const backups = listDir(parent)
|
|
155
|
+
.filter((e) => e.name.startsWith(base))
|
|
156
|
+
.map((e) => {
|
|
157
|
+
const full = path.join(parent, e.name);
|
|
158
|
+
return { full, mtime: (() => { try { return fs.statSync(full).mtimeMs; } catch { return 0; } })() };
|
|
159
|
+
})
|
|
160
|
+
.sort((a, b) => b.mtime - a.mtime);
|
|
161
|
+
|
|
162
|
+
backups.forEach((backup, index) => {
|
|
163
|
+
items.push({
|
|
164
|
+
group: 'runtime-backups',
|
|
165
|
+
path: backup.full,
|
|
166
|
+
bytes: sizeOf(backup.full),
|
|
167
|
+
why: index === 0
|
|
168
|
+
? 'the most recent data-directory backup - kept, so the last move can still be undone'
|
|
169
|
+
: `a data-directory backup from ${new Date(backup.mtime).toISOString().slice(0, 10)}`,
|
|
170
|
+
removable: index !== 0,
|
|
171
|
+
keep: index === 0,
|
|
172
|
+
ageDays: Math.round(ageDays(backup.full, now)),
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
return items;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Easy DevOps' own logs, older than `days`. */
|
|
180
|
+
function scanLogs({ dataDir, days, now }) {
|
|
181
|
+
const items = [];
|
|
182
|
+
|
|
183
|
+
const dirs = [path.join(dataDir, 'logs')];
|
|
184
|
+
// Windows Server mode writes the service's logs under ProgramData.
|
|
185
|
+
if (isWindows) dirs.push(path.join(programDataDir(), 'logs'));
|
|
186
|
+
|
|
187
|
+
for (const dir of dirs) {
|
|
188
|
+
for (const entry of listDir(dir)) {
|
|
189
|
+
if (entry.isDirectory()) continue;
|
|
190
|
+
const full = path.join(dir, entry.name);
|
|
191
|
+
const age = ageDays(full, now);
|
|
192
|
+
if (age < days) continue;
|
|
193
|
+
items.push({
|
|
194
|
+
group: 'logs',
|
|
195
|
+
path: full,
|
|
196
|
+
bytes: sizeOf(full),
|
|
197
|
+
why: `${Math.round(age)} days old`,
|
|
198
|
+
removable: true,
|
|
199
|
+
ageDays: Math.round(age),
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// The Personal-mode supervisor's log lives in the data directory root and
|
|
205
|
+
// grows for as long as the machine runs.
|
|
206
|
+
const supervisor = path.join(dataDir, 'daemon-supervisor.log');
|
|
207
|
+
if (fs.existsSync(supervisor)) {
|
|
208
|
+
const age = ageDays(supervisor, now);
|
|
209
|
+
if (age >= days) {
|
|
210
|
+
items.push({
|
|
211
|
+
group: 'logs',
|
|
212
|
+
path: supervisor,
|
|
213
|
+
bytes: sizeOf(supervisor),
|
|
214
|
+
why: `the logon supervisor's log, ${Math.round(age)} days old`,
|
|
215
|
+
removable: true,
|
|
216
|
+
ageDays: Math.round(age),
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return items;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Temporary files, stale claims and a dead lock.
|
|
226
|
+
*
|
|
227
|
+
* The lock is the careful one: a lock file whose owner is still alive, or
|
|
228
|
+
* whose heartbeat is fresh, is NOT litter — removing it would let a second
|
|
229
|
+
* daemon start alongside the first. Only one that `inspect()` already
|
|
230
|
+
* considers dead is offered.
|
|
231
|
+
*/
|
|
232
|
+
function scanTemp({ dataDir, now }) {
|
|
233
|
+
const items = [];
|
|
234
|
+
|
|
235
|
+
for (const entry of listDir(dataDir)) {
|
|
236
|
+
if (entry.isDirectory()) continue;
|
|
237
|
+
const name = entry.name;
|
|
238
|
+
const full = path.join(dataDir, name);
|
|
239
|
+
|
|
240
|
+
// Never: a stop request is a deliberate state, not a leftover.
|
|
241
|
+
if (name === 'daemon.stop') continue;
|
|
242
|
+
|
|
243
|
+
if (/\.tmp$/i.test(name) || /^\.ez-write-probe-/.test(name) || /^ez-runtime-probe-/.test(name)) {
|
|
244
|
+
items.push({
|
|
245
|
+
group: 'temp',
|
|
246
|
+
path: full,
|
|
247
|
+
bytes: sizeOf(full),
|
|
248
|
+
why: 'a temporary file left behind by an interrupted write',
|
|
249
|
+
removable: true,
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Stale notification claims: past the TTL means the owner crashed between
|
|
255
|
+
// claiming and committing, and dispatch already treats them as reclaimable.
|
|
256
|
+
for (const entry of listDir(claimDir(dataDir))) {
|
|
257
|
+
if (!entry.name.endsWith('.claim')) continue;
|
|
258
|
+
const full = path.join(claimDir(dataDir), entry.name);
|
|
259
|
+
const ageMs = now - (() => { try { return fs.statSync(full).mtimeMs; } catch { return now; } })();
|
|
260
|
+
if (ageMs < CLAIM_TTL_MS) continue;
|
|
261
|
+
items.push({
|
|
262
|
+
group: 'temp',
|
|
263
|
+
path: full,
|
|
264
|
+
bytes: sizeOf(full),
|
|
265
|
+
why: `a notification claim ${Math.round(ageMs / 1000)}s old, past the ${Math.round(CLAIM_TTL_MS / 1000)}s timeout`,
|
|
266
|
+
removable: true,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const lock = inspectLock({ dataDir, now });
|
|
271
|
+
if (lock.lock && !lock.running) {
|
|
272
|
+
items.push({
|
|
273
|
+
group: 'temp',
|
|
274
|
+
path: lockPath(dataDir),
|
|
275
|
+
bytes: sizeOf(lockPath(dataDir)),
|
|
276
|
+
why: `a dead daemon lock (${lock.reason})`,
|
|
277
|
+
removable: true,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
return items;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** `.bak` copies nginx-apply leaves beside a config it rewrote. */
|
|
285
|
+
function scanNginxBak({ config, now }) {
|
|
286
|
+
const items = [];
|
|
287
|
+
const dir = config.nginxDir;
|
|
288
|
+
if (!dir) return items;
|
|
289
|
+
|
|
290
|
+
// Only where configs actually live, and only `.bak` - never a `.conf`.
|
|
291
|
+
const candidates = [dir, path.join(dir, 'conf.d'), path.join(dir, 'sites-available'), path.join(dir, 'sites-enabled')];
|
|
292
|
+
|
|
293
|
+
for (const base of candidates) {
|
|
294
|
+
for (const entry of listDir(base)) {
|
|
295
|
+
if (entry.isDirectory()) continue;
|
|
296
|
+
if (!entry.name.endsWith('.bak')) continue;
|
|
297
|
+
const full = path.join(base, entry.name);
|
|
298
|
+
items.push({
|
|
299
|
+
group: 'nginx-bak',
|
|
300
|
+
path: full,
|
|
301
|
+
bytes: sizeOf(full),
|
|
302
|
+
why: `a backup of ${entry.name.replace(/\.bak$/, '')}, ${Math.round(ageDays(full, now))} days old`,
|
|
303
|
+
removable: true,
|
|
304
|
+
ageDays: Math.round(ageDays(full, now)),
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
return items;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* PM2's own logs, which only PM2 can safely truncate.
|
|
314
|
+
*
|
|
315
|
+
* The action is `pm2 flush`, not a delete: PM2 holds the files open, and on
|
|
316
|
+
* Windows removing an open log leaves it writing to a handle with no name.
|
|
317
|
+
* Listed only when PM2 is actually present AND its daemon is running, because
|
|
318
|
+
* every pm2 command starts that daemon and a cleanup scan must not be what
|
|
319
|
+
* brings one to life on a machine that does not use PM2.
|
|
320
|
+
*/
|
|
321
|
+
async function scanPm2Logs({ deps = {} }) {
|
|
322
|
+
const items = [];
|
|
323
|
+
const detect = deps.runnerDetect ?? runner.detect;
|
|
324
|
+
const daemonUp = (deps.isDaemonRunning ?? runner.isDaemonRunning)();
|
|
325
|
+
|
|
326
|
+
const pm2 = await detect({ probeVersion: false });
|
|
327
|
+
if (!pm2.installed) return items;
|
|
328
|
+
|
|
329
|
+
const home = (deps.pm2HomeDir ?? runner.pm2HomeDir)();
|
|
330
|
+
const logs = home ? path.join(home, 'logs') : null;
|
|
331
|
+
const bytes = logs ? sizeOf(logs) : 0;
|
|
332
|
+
|
|
333
|
+
items.push({
|
|
334
|
+
group: 'pm2-logs',
|
|
335
|
+
path: logs ?? '(pm2 log directory)',
|
|
336
|
+
bytes,
|
|
337
|
+
why: daemonUp
|
|
338
|
+
? 'PM2 log files, truncated with `pm2 flush`'
|
|
339
|
+
: 'PM2 log files - its daemon is not running, so flushing would start it',
|
|
340
|
+
removable: daemonUp,
|
|
341
|
+
action: 'pm2-flush',
|
|
342
|
+
pm2Path: pm2.path ?? 'pm2',
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
return items;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Installed Node versions, with the evidence for whether each is in use.
|
|
350
|
+
*
|
|
351
|
+
* Listed only. `removable` here means "nothing proved it is in use", which is
|
|
352
|
+
* weaker than the other groups and is why the CLI defaults the selection to
|
|
353
|
+
* nothing and prints the reason beside each one.
|
|
354
|
+
*/
|
|
355
|
+
async function scanNodeVersions({ dataDir, deps = {} }) {
|
|
356
|
+
const exec = deps.run ?? run;
|
|
357
|
+
const items = [];
|
|
358
|
+
|
|
359
|
+
const installed = await (deps.listInstalledNode ?? listInstalledNode)({ deps });
|
|
360
|
+
if (installed.versions.length === 0) return items;
|
|
361
|
+
|
|
362
|
+
// Everything we can prove is in use.
|
|
363
|
+
const pinnedPath = isWindows ? runtimeNodePath(dataDir) : inspectLink(dataDir).target;
|
|
364
|
+
const recorded = (deps.recordedState ?? recordedState)().nodeExe ?? null;
|
|
365
|
+
|
|
366
|
+
const pinnedVersions = new Set();
|
|
367
|
+
for (const candidate of [pinnedPath, recorded]) {
|
|
368
|
+
const version = candidate ? versionFromPath(candidate) : null;
|
|
369
|
+
if (version) pinnedVersions.add(version);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// A pinned path that carries no version in it (a copy under ProgramData) is
|
|
373
|
+
// asked directly, so a copied runtime still protects its source version.
|
|
374
|
+
if (pinnedPath && fs.existsSync(pinnedPath) && pinnedVersions.size === 0) {
|
|
375
|
+
const probe = await exec(`${quoteExe(pinnedPath)} --version`, { timeout: 15_000 });
|
|
376
|
+
if (probe.success) pinnedVersions.add(probe.stdout.trim().replace(/^v/, ''));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const pm2Versions = await (deps.pm2NodeVersions ?? pm2NodeVersions)({ deps });
|
|
380
|
+
|
|
381
|
+
for (const entry of installed.versions) {
|
|
382
|
+
const reasons = [];
|
|
383
|
+
if (pinnedVersions.has(entry.version)) reasons.push('the service is pinned to it');
|
|
384
|
+
if (entry.isDefault) reasons.push(`it is ${installed.manager}'s default`);
|
|
385
|
+
if (entry.isCurrent) reasons.push('it is the version your shell uses now');
|
|
386
|
+
if (pm2Versions.has(entry.version)) reasons.push('a PM2 app runs it');
|
|
387
|
+
|
|
388
|
+
items.push({
|
|
389
|
+
group: 'node-versions',
|
|
390
|
+
path: entry.path ?? `v${entry.version}`,
|
|
391
|
+
version: entry.version,
|
|
392
|
+
bytes: entry.path ? sizeOf(entry.path) : 0,
|
|
393
|
+
why: reasons.length ? `in use: ${reasons.join('; ')}` : 'nothing on this machine refers to it',
|
|
394
|
+
removable: reasons.length === 0,
|
|
395
|
+
keep: reasons.length > 0,
|
|
396
|
+
action: 'node-uninstall',
|
|
397
|
+
manager: installed.manager,
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
return items;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** `.../v20.11.1/bin/node` -> `20.11.1` */
|
|
405
|
+
function versionFromPath(target) {
|
|
406
|
+
return String(target).match(/v?(\d+\.\d+\.\d+)/)?.[1] ?? null;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* The Node versions a version manager has installed.
|
|
411
|
+
*
|
|
412
|
+
* @returns {Promise<{ manager: string|null, versions: Array<Object> }>}
|
|
413
|
+
*/
|
|
414
|
+
export async function listInstalledNode({ deps = {} } = {}) {
|
|
415
|
+
const exec = deps.run ?? run;
|
|
416
|
+
|
|
417
|
+
if (isWindows) {
|
|
418
|
+
const listed = await exec('nvm list', { timeout: 30_000 });
|
|
419
|
+
if (!listed.success || !/\d+\.\d+\.\d+/.test(listed.stdout)) {
|
|
420
|
+
return { manager: null, versions: [] };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const root = await exec('nvm root', { timeout: 15_000 });
|
|
424
|
+
const base = root.success ? (root.stdout.match(/:\s*(.+)$/m)?.[1] ?? '').trim() : '';
|
|
425
|
+
|
|
426
|
+
const versions = [];
|
|
427
|
+
for (const line of listed.stdout.split('\n')) {
|
|
428
|
+
const m = line.match(/(\*?)\s*(\d+\.\d+\.\d+)/);
|
|
429
|
+
if (!m) continue;
|
|
430
|
+
const version = m[2];
|
|
431
|
+
versions.push({
|
|
432
|
+
version,
|
|
433
|
+
isCurrent: m[1] === '*',
|
|
434
|
+
// nvm-windows has no alias system, so "default" does not apply.
|
|
435
|
+
isDefault: false,
|
|
436
|
+
path: base ? path.join(base, `v${version}`) : null,
|
|
437
|
+
});
|
|
438
|
+
}
|
|
439
|
+
return { manager: 'nvm-windows', versions };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const script = 'export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; ';
|
|
443
|
+
const listed = await exec(`${script}nvm ls --no-colors`, { timeout: 30_000 });
|
|
444
|
+
if (!listed.success || !/\d+\.\d+\.\d+/.test(listed.stdout)) {
|
|
445
|
+
return { manager: null, versions: [] };
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// `nvm alias default` prints what default resolves to, which is the only
|
|
449
|
+
// reliable way to know it: the `ls` output marks it inconsistently.
|
|
450
|
+
const aliased = await exec(`${script}nvm alias default`, { timeout: 15_000 });
|
|
451
|
+
const defaultVersion = aliased.success ? versionFromPath(aliased.stdout) : null;
|
|
452
|
+
|
|
453
|
+
const versions = [];
|
|
454
|
+
for (const line of listed.stdout.split('\n')) {
|
|
455
|
+
const m = line.match(/(->)?\s*v(\d+\.\d+\.\d+)/);
|
|
456
|
+
if (!m) continue;
|
|
457
|
+
const version = m[2];
|
|
458
|
+
if (versions.some((v) => v.version === version)) continue;
|
|
459
|
+
versions.push({
|
|
460
|
+
version,
|
|
461
|
+
isCurrent: Boolean(m[1]),
|
|
462
|
+
isDefault: defaultVersion === version,
|
|
463
|
+
path: path.join(process.env.HOME ?? '', '.nvm', 'versions', 'node', `v${version}`),
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
return { manager: 'nvm', versions };
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Node versions that PM2 apps are running, read from their exec paths. */
|
|
470
|
+
export async function pm2NodeVersions({ deps = {} } = {}) {
|
|
471
|
+
const found = new Set();
|
|
472
|
+
|
|
473
|
+
// Never start the daemon to answer this.
|
|
474
|
+
if (!(deps.isDaemonRunning ?? runner.isDaemonRunning)()) return found;
|
|
475
|
+
|
|
476
|
+
const pm2 = await (deps.runnerDetect ?? runner.detect)({ probeVersion: false });
|
|
477
|
+
if (!pm2.installed) return found;
|
|
478
|
+
|
|
479
|
+
const listed = await (deps.runnerList ?? runner.list)({ pm2Path: pm2.path ?? 'pm2' });
|
|
480
|
+
if (!listed.ok) return found;
|
|
481
|
+
|
|
482
|
+
for (const app of listed.apps ?? []) {
|
|
483
|
+
const version = app.execPath ? versionFromPath(app.execPath) : null;
|
|
484
|
+
if (version) found.add(version);
|
|
485
|
+
}
|
|
486
|
+
return found;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// ─── The scan ────────────────────────────────────────────────────────────────
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Everything reclaimable, grouped, with sizes. Deletes nothing.
|
|
493
|
+
*
|
|
494
|
+
* @param {Object} [opts]
|
|
495
|
+
* @param {number} [opts.days] Log age threshold
|
|
496
|
+
* @returns {Promise<{ items: Array<Object>, groups: Object, totalBytes: number, days: number }>}
|
|
497
|
+
*/
|
|
498
|
+
export async function scan({
|
|
499
|
+
dataDir = getDataDir(),
|
|
500
|
+
days = DEFAULT_LOG_DAYS,
|
|
501
|
+
now = Date.now(),
|
|
502
|
+
config = loadConfig(),
|
|
503
|
+
deps = {},
|
|
504
|
+
} = {}) {
|
|
505
|
+
const items = [
|
|
506
|
+
...scanRuntimeBackups({ dataDir, now }),
|
|
507
|
+
...scanLogs({ dataDir, days, now }),
|
|
508
|
+
...scanTemp({ dataDir, now }),
|
|
509
|
+
...scanNginxBak({ config, now }),
|
|
510
|
+
...(await scanPm2Logs({ deps })),
|
|
511
|
+
...(await scanNodeVersions({ dataDir, deps })),
|
|
512
|
+
];
|
|
513
|
+
|
|
514
|
+
// Stable ids, so a caller can select by id without the paths travelling
|
|
515
|
+
// through a prompt and coming back altered.
|
|
516
|
+
items.forEach((item, index) => { item.id = `${item.group}:${index}`; });
|
|
517
|
+
|
|
518
|
+
const groups = {};
|
|
519
|
+
for (const group of GROUPS) {
|
|
520
|
+
const inGroup = items.filter((i) => i.group === group);
|
|
521
|
+
groups[group] = {
|
|
522
|
+
items: inGroup,
|
|
523
|
+
bytes: inGroup.filter((i) => i.removable).reduce((sum, i) => sum + i.bytes, 0),
|
|
524
|
+
count: inGroup.length,
|
|
525
|
+
removable: inGroup.filter((i) => i.removable).length,
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
return {
|
|
530
|
+
items,
|
|
531
|
+
groups,
|
|
532
|
+
days,
|
|
533
|
+
dataDir,
|
|
534
|
+
// Only what could actually be freed: a kept item's size is not a saving.
|
|
535
|
+
totalBytes: items.filter((i) => i.removable).reduce((sum, i) => sum + i.bytes, 0),
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// ─── Applying ────────────────────────────────────────────────────────────────
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Removes the given items, and nothing else.
|
|
543
|
+
*
|
|
544
|
+
* Each item carries its own action, so a caller never has to know that PM2
|
|
545
|
+
* logs are flushed rather than deleted, or that a Node version is uninstalled
|
|
546
|
+
* by its manager.
|
|
547
|
+
*
|
|
548
|
+
* @param {Object} opts
|
|
549
|
+
* @param {Array<Object>} opts.items From scan()
|
|
550
|
+
* @returns {Promise<{ removed: Array<Object>, failed: Array<Object>, freedBytes: number }>}
|
|
551
|
+
*/
|
|
552
|
+
export async function apply({ items = [], log = () => {}, deps = {} } = {}) {
|
|
553
|
+
const exec = deps.run ?? run;
|
|
554
|
+
const removed = [];
|
|
555
|
+
const failed = [];
|
|
556
|
+
|
|
557
|
+
for (const item of items) {
|
|
558
|
+
// Defence in depth: an item the scan marked as keep must not be removable
|
|
559
|
+
// even if a caller passes it in.
|
|
560
|
+
if (item.keep || !item.removable) {
|
|
561
|
+
failed.push({ ...item, reason: 'this item is kept on purpose and was not removed' });
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
if (item.action === 'pm2-flush') {
|
|
566
|
+
const flushed = await exec(`${item.pm2Path ?? 'pm2'} flush`, { timeout: 60_000 });
|
|
567
|
+
flushed.success
|
|
568
|
+
? removed.push(item)
|
|
569
|
+
: failed.push({ ...item, reason: (flushed.stderr || flushed.stdout || 'pm2 flush failed').trim().slice(0, 200) });
|
|
570
|
+
log(`pm2 flush: ${flushed.success ? 'done' : 'failed'}`);
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
if (item.action === 'node-uninstall') {
|
|
575
|
+
const command = item.manager === 'nvm-windows'
|
|
576
|
+
? `nvm uninstall ${item.version}`
|
|
577
|
+
: `export NVM_DIR="$HOME/.nvm"; [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"; nvm uninstall ${item.version}`;
|
|
578
|
+
const gone = await exec(command, { timeout: 300_000 });
|
|
579
|
+
gone.success
|
|
580
|
+
? removed.push(item)
|
|
581
|
+
: failed.push({ ...item, reason: (gone.stderr || gone.stdout || 'uninstall failed').trim().slice(0, 200) });
|
|
582
|
+
log(`Node v${item.version}: ${gone.success ? 'uninstalled' : 'could not be uninstalled'}`);
|
|
583
|
+
continue;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
try {
|
|
587
|
+
fs.rmSync(item.path, { recursive: true, force: true });
|
|
588
|
+
removed.push(item);
|
|
589
|
+
log(`Removed ${item.path}`);
|
|
590
|
+
} catch (err) {
|
|
591
|
+
failed.push({ ...item, reason: err.message });
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
return {
|
|
596
|
+
removed,
|
|
597
|
+
failed,
|
|
598
|
+
freedBytes: removed.reduce((sum, i) => sum + (i.bytes ?? 0), 0),
|
|
599
|
+
};
|
|
600
|
+
}
|