pulse-hub 3.5.0 → 3.6.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/CHANGELOG.md +6 -0
- package/backend/.env.example +52 -52
- package/backend/agent.js +372 -372
- package/backend/cli.js +23 -1
- package/backend/emails/env-backup.html +52 -52
- package/backend/emails/invite.html +53 -53
- package/backend/lib/agent-rpc.js +72 -72
- package/backend/lib/async-route.js +17 -17
- package/backend/lib/authz/bootstrap.js +35 -35
- package/backend/lib/authz/catalog.js +291 -291
- package/backend/lib/authz/delegation.js +104 -104
- package/backend/lib/authz/effective.js +104 -104
- package/backend/lib/authz/engine.js +251 -251
- package/backend/lib/authz/index.js +134 -134
- package/backend/lib/authz/migrate.js +871 -871
- package/backend/lib/authz/mutate.js +87 -87
- package/backend/lib/authz/preview.js +327 -327
- package/backend/lib/authz/scope.js +282 -282
- package/backend/lib/env-mask.js +131 -131
- package/backend/lib/invite-helpers.js +83 -83
- package/backend/lib/invites.js +160 -160
- package/backend/lib/logs.js +244 -244
- package/backend/lib/metrics.js +249 -249
- package/backend/lib/relay-state.js +564 -564
- package/backend/lib/session.js +48 -48
- package/backend/middleware/authz.js +65 -65
- package/backend/public/assets/favicon.svg +6 -6
- package/backend/public/assets/index.js +1 -1
- package/backend/public/index.html +23 -24
- package/backend/routes/access.js +123 -123
- package/backend/routes/audit.js +41 -41
- package/backend/routes/auth.js +207 -207
- package/backend/routes/invites-public.js +91 -91
- package/backend/routes/invites.js +121 -121
- package/backend/routes/logs.js +68 -68
- package/backend/routes/metrics.js +76 -76
- package/backend/routes/policies.js +240 -240
- package/backend/routes/teams.js +221 -221
- package/backend/routes/users.js +100 -100
- package/backend/seed-admins.js +68 -68
- package/backend/server.js +106 -106
- package/backend/ws/agent-relay.js +159 -159
- package/package.json +1 -1
package/backend/lib/metrics.js
CHANGED
|
@@ -1,249 +1,249 @@
|
|
|
1
|
-
const fs = require('fs');
|
|
2
|
-
const os = require('os');
|
|
3
|
-
const childProcess = require('child_process');
|
|
4
|
-
|
|
5
|
-
// Every external command gets a hard timeout: these all run synchronously on the agent's
|
|
6
|
-
// only thread, so a hung `docker`/`pm2`/`df` (wedged daemon, stuck mount) would otherwise
|
|
7
|
-
// freeze the whole agent — no heartbeat, no metrics — until the box is rebooted.
|
|
8
|
-
const CMD_TIMEOUT_MS = 10 * 1000;
|
|
9
|
-
const execSync = (cmd, opts = {}) => childProcess.execSync(cmd, { timeout: CMD_TIMEOUT_MS, ...opts });
|
|
10
|
-
const spawnSync = (cmd, args, opts = {}) =>
|
|
11
|
-
childProcess.spawnSync(cmd, args, { timeout: CMD_TIMEOUT_MS, ...opts });
|
|
12
|
-
|
|
13
|
-
function getPm2Processes() {
|
|
14
|
-
try {
|
|
15
|
-
const raw = execSync('pm2 jlist').toString();
|
|
16
|
-
const list = JSON.parse(raw);
|
|
17
|
-
return list.map((p) => ({
|
|
18
|
-
name: p.name,
|
|
19
|
-
kind: 'pm2',
|
|
20
|
-
pid: p.pid,
|
|
21
|
-
status: p.pm2_env.status,
|
|
22
|
-
cpu: p.monit.cpu,
|
|
23
|
-
memory_mb: Math.round(p.monit.memory / 1024 / 1024),
|
|
24
|
-
restarts: p.pm2_env.restart_time,
|
|
25
|
-
out_log: p.pm2_env.pm_out_log_path,
|
|
26
|
-
err_log: p.pm2_env.pm_err_log_path,
|
|
27
|
-
}));
|
|
28
|
-
} catch (e) {
|
|
29
|
-
return [];
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function getDockerContainers() {
|
|
34
|
-
try {
|
|
35
|
-
const raw = execSync('docker ps -a --format "{{json .}}"').toString();
|
|
36
|
-
return raw
|
|
37
|
-
.trim()
|
|
38
|
-
.split('\n')
|
|
39
|
-
.filter(Boolean)
|
|
40
|
-
.map((line) => {
|
|
41
|
-
const c = JSON.parse(line);
|
|
42
|
-
return {
|
|
43
|
-
name: c.Names,
|
|
44
|
-
kind: 'docker',
|
|
45
|
-
status: c.State === 'running' ? 'online' : c.State,
|
|
46
|
-
containerId: c.ID,
|
|
47
|
-
};
|
|
48
|
-
});
|
|
49
|
-
} catch (e) {
|
|
50
|
-
return [];
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// One-shot diagnostic for agent startup logs — the polling path above stays silent
|
|
55
|
-
// (same as getPm2Processes on a PM2-less box), but a Docker permission/availability
|
|
56
|
-
// problem is otherwise invisible until someone notices containers never show up.
|
|
57
|
-
function checkDockerAvailable() {
|
|
58
|
-
try {
|
|
59
|
-
execSync('docker ps', { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
60
|
-
return { ok: true };
|
|
61
|
-
} catch (e) {
|
|
62
|
-
return { ok: false, error: (e.stderr ? e.stderr.toString() : e.message).trim().split('\n')[0] };
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
// Units that are always running on a stock Linux box but never interesting to read logs
|
|
67
|
-
// for — keeps the Process dropdown to services an operator actually deployed. The
|
|
68
|
-
// `@`-templated ones (getty@tty1, user@1000) are matched by prefix.
|
|
69
|
-
const SYSTEMD_NOISE =
|
|
70
|
-
/^(getty@|serial-getty@|user@|user-runtime-dir@|systemd-|dbus|polkit|udisks2|multipathd|snapd|ModemManager|irqbalance|chrony|ntp|cron|rsyslog|acpid|unattended-upgrades|networkd-dispatcher|lvm2|accounts-daemon|packagekit|fwupd|gdm|colord|upower)/;
|
|
71
|
-
|
|
72
|
-
// 'absent' = no systemd/journalctl at all (non-Linux, Alpine, container); 'unreadable' =
|
|
73
|
-
// journalctl exists but this OS user can't read the system journal (root, or membership
|
|
74
|
-
// in systemd-journal/adm, is required); 'ok' otherwise. Cheap enough to run on every
|
|
75
|
-
// metrics push, and it's what lets the UI explain *why* no units are listed.
|
|
76
|
-
function checkSystemdAvailable() {
|
|
77
|
-
// spawnSync (not execSync): journalctl prints its "not seeing messages from other
|
|
78
|
-
// users" hint on stderr while still exiting 0, and execSync drops stderr on success.
|
|
79
|
-
const r = spawnSync('journalctl', ['-n', '1', '--no-pager'], { encoding: 'utf-8' });
|
|
80
|
-
if (r.error) return { ok: false, state: 'absent' };
|
|
81
|
-
let user = null;
|
|
82
|
-
try {
|
|
83
|
-
user = os.userInfo().username;
|
|
84
|
-
} catch (e) {}
|
|
85
|
-
if (r.status !== 0 || /not seeing messages from other users/i.test(`${r.stdout}${r.stderr}`))
|
|
86
|
-
return { ok: false, state: 'unreadable', user };
|
|
87
|
-
return { ok: true, state: 'ok', user };
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
function getSystemdUnits() {
|
|
91
|
-
try {
|
|
92
|
-
const raw = execSync(
|
|
93
|
-
'systemctl list-units --type=service --state=running --no-legend --plain --no-pager',
|
|
94
|
-
{ stdio: ['ignore', 'pipe', 'ignore'] },
|
|
95
|
-
).toString();
|
|
96
|
-
return raw
|
|
97
|
-
.trim()
|
|
98
|
-
.split('\n')
|
|
99
|
-
.filter(Boolean)
|
|
100
|
-
.map((line) =>
|
|
101
|
-
line
|
|
102
|
-
.trim()
|
|
103
|
-
.split(/\s+/)[0]
|
|
104
|
-
.replace(/\.service$/, ''),
|
|
105
|
-
)
|
|
106
|
-
.filter((name) => name && !SYSTEMD_NOISE.test(name))
|
|
107
|
-
.map((name) => ({ name, kind: 'systemd', status: 'online', cpu: 0, memory_mb: 0 }));
|
|
108
|
-
} catch (e) {
|
|
109
|
-
return [];
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
// "12.5MiB / 1.9GiB" -> 12.5 rounded to whole MB, regardless of Ki/Mi/Gi unit.
|
|
114
|
-
function parseMemUsageMb(memUsage) {
|
|
115
|
-
const left = memUsage.split('/')[0].trim();
|
|
116
|
-
const m = left.match(/^([\d.]+)\s*([A-Za-z]+)/);
|
|
117
|
-
if (!m) return 0;
|
|
118
|
-
const val = parseFloat(m[1]),
|
|
119
|
-
unit = m[2].toLowerCase();
|
|
120
|
-
if (unit.startsWith('g')) return Math.round(val * 1024);
|
|
121
|
-
if (unit.startsWith('k')) return Math.round(val / 1024);
|
|
122
|
-
return Math.round(val);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
function getDockerStats() {
|
|
126
|
-
try {
|
|
127
|
-
const raw = execSync('docker stats --no-stream --format "{{json .}}"').toString();
|
|
128
|
-
const stats = {};
|
|
129
|
-
raw
|
|
130
|
-
.trim()
|
|
131
|
-
.split('\n')
|
|
132
|
-
.filter(Boolean)
|
|
133
|
-
.forEach((line) => {
|
|
134
|
-
const s = JSON.parse(line);
|
|
135
|
-
stats[s.Name] = { cpu: parseFloat(s.CPUPerc) || 0, memory_mb: parseMemUsageMb(s.MemUsage) };
|
|
136
|
-
});
|
|
137
|
-
return stats;
|
|
138
|
-
} catch (e) {
|
|
139
|
-
return {};
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
function getContainerProcesses() {
|
|
144
|
-
const containers = getDockerContainers();
|
|
145
|
-
if (containers.length === 0) return [];
|
|
146
|
-
const stats = getDockerStats();
|
|
147
|
-
return containers.map((c) => {
|
|
148
|
-
const s = stats[c.name] || { cpu: 0, memory_mb: 0 };
|
|
149
|
-
return { name: c.name, kind: 'docker', status: c.status, cpu: s.cpu, memory_mb: s.memory_mb };
|
|
150
|
-
});
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
function getNetworkStats() {
|
|
154
|
-
try {
|
|
155
|
-
const data = fs.readFileSync('/proc/net/dev', 'utf-8');
|
|
156
|
-
const lines = data.trim().split('\n').slice(2);
|
|
157
|
-
let rx = 0,
|
|
158
|
-
tx = 0;
|
|
159
|
-
for (const line of lines) {
|
|
160
|
-
const [ifacePart, rest] = line.split(':');
|
|
161
|
-
if (!rest) continue;
|
|
162
|
-
if (ifacePart.trim() === 'lo') continue;
|
|
163
|
-
const fields = rest.trim().split(/\s+/).map(Number);
|
|
164
|
-
rx += fields[0] || 0;
|
|
165
|
-
tx += fields[8] || 0;
|
|
166
|
-
}
|
|
167
|
-
return { rx_bytes: rx, tx_bytes: tx };
|
|
168
|
-
} catch (e) {
|
|
169
|
-
return { rx_bytes: 0, tx_bytes: 0 };
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
function getTopProcesses(sortFlag, limit) {
|
|
174
|
-
try {
|
|
175
|
-
const out = execSync(`ps -eo pid,comm,%cpu,%mem --sort=${sortFlag} --no-headers`).toString();
|
|
176
|
-
return out
|
|
177
|
-
.trim()
|
|
178
|
-
.split('\n')
|
|
179
|
-
.slice(0, limit)
|
|
180
|
-
.map((line) => {
|
|
181
|
-
const parts = line.trim().split(/\s+/);
|
|
182
|
-
const pid = parts[0],
|
|
183
|
-
mem = parts[parts.length - 1],
|
|
184
|
-
cpu = parts[parts.length - 2];
|
|
185
|
-
const name = parts.slice(1, parts.length - 2).join(' ');
|
|
186
|
-
return { pid, name, cpu: parseFloat(cpu), mem: parseFloat(mem) };
|
|
187
|
-
});
|
|
188
|
-
} catch (e) {
|
|
189
|
-
return [];
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
function getUptimeString() {
|
|
194
|
-
const secs = os.uptime();
|
|
195
|
-
const d = Math.floor(secs / 86400),
|
|
196
|
-
h = Math.floor((secs % 86400) / 3600),
|
|
197
|
-
m = Math.floor((secs % 3600) / 60);
|
|
198
|
-
return `${d}d ${h}h ${m}m`;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
function getSystemMetrics() {
|
|
202
|
-
const systemd = checkSystemdAvailable();
|
|
203
|
-
const totalMem = os.totalmem(),
|
|
204
|
-
freeMem = os.freemem();
|
|
205
|
-
const memUsedPercent = (((totalMem - freeMem) / totalMem) * 100).toFixed(1);
|
|
206
|
-
let diskPercent = 'N/A',
|
|
207
|
-
diskUsed = 'N/A',
|
|
208
|
-
diskTotal = 'N/A';
|
|
209
|
-
try {
|
|
210
|
-
const dfOut = execSync('df -h / | tail -1').toString().trim().split(/\s+/);
|
|
211
|
-
diskTotal = dfOut[1];
|
|
212
|
-
diskUsed = dfOut[2];
|
|
213
|
-
diskPercent = dfOut[4];
|
|
214
|
-
} catch (e) {}
|
|
215
|
-
return {
|
|
216
|
-
load_avg: os.loadavg().map((n) => n.toFixed(2)),
|
|
217
|
-
cpu_count: os.cpus().length,
|
|
218
|
-
mem_used_percent: memUsedPercent,
|
|
219
|
-
mem_used_mb: Math.round((totalMem - freeMem) / 1024 / 1024),
|
|
220
|
-
mem_total_mb: Math.round(totalMem / 1024 / 1024),
|
|
221
|
-
disk_percent: diskPercent,
|
|
222
|
-
disk_used: diskUsed,
|
|
223
|
-
disk_total: diskTotal,
|
|
224
|
-
hostname: os.hostname(),
|
|
225
|
-
uptime_str: getUptimeString(),
|
|
226
|
-
network: getNetworkStats(),
|
|
227
|
-
top_cpu: getTopProcesses('-%cpu', 5),
|
|
228
|
-
top_mem: getTopProcesses('-%mem', 5),
|
|
229
|
-
processes: [
|
|
230
|
-
...getPm2Processes(),
|
|
231
|
-
...getContainerProcesses(),
|
|
232
|
-
...(systemd.ok ? getSystemdUnits() : []),
|
|
233
|
-
],
|
|
234
|
-
diagnostics: { systemd: systemd.state, user: systemd.user || null },
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
module.exports = {
|
|
239
|
-
getSystemMetrics,
|
|
240
|
-
getPm2Processes,
|
|
241
|
-
getDockerContainers,
|
|
242
|
-
getContainerProcesses,
|
|
243
|
-
checkDockerAvailable,
|
|
244
|
-
getSystemdUnits,
|
|
245
|
-
checkSystemdAvailable,
|
|
246
|
-
getNetworkStats,
|
|
247
|
-
getTopProcesses,
|
|
248
|
-
getUptimeString,
|
|
249
|
-
};
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const os = require('os');
|
|
3
|
+
const childProcess = require('child_process');
|
|
4
|
+
|
|
5
|
+
// Every external command gets a hard timeout: these all run synchronously on the agent's
|
|
6
|
+
// only thread, so a hung `docker`/`pm2`/`df` (wedged daemon, stuck mount) would otherwise
|
|
7
|
+
// freeze the whole agent — no heartbeat, no metrics — until the box is rebooted.
|
|
8
|
+
const CMD_TIMEOUT_MS = 10 * 1000;
|
|
9
|
+
const execSync = (cmd, opts = {}) => childProcess.execSync(cmd, { timeout: CMD_TIMEOUT_MS, ...opts });
|
|
10
|
+
const spawnSync = (cmd, args, opts = {}) =>
|
|
11
|
+
childProcess.spawnSync(cmd, args, { timeout: CMD_TIMEOUT_MS, ...opts });
|
|
12
|
+
|
|
13
|
+
function getPm2Processes() {
|
|
14
|
+
try {
|
|
15
|
+
const raw = execSync('pm2 jlist').toString();
|
|
16
|
+
const list = JSON.parse(raw);
|
|
17
|
+
return list.map((p) => ({
|
|
18
|
+
name: p.name,
|
|
19
|
+
kind: 'pm2',
|
|
20
|
+
pid: p.pid,
|
|
21
|
+
status: p.pm2_env.status,
|
|
22
|
+
cpu: p.monit.cpu,
|
|
23
|
+
memory_mb: Math.round(p.monit.memory / 1024 / 1024),
|
|
24
|
+
restarts: p.pm2_env.restart_time,
|
|
25
|
+
out_log: p.pm2_env.pm_out_log_path,
|
|
26
|
+
err_log: p.pm2_env.pm_err_log_path,
|
|
27
|
+
}));
|
|
28
|
+
} catch (e) {
|
|
29
|
+
return [];
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function getDockerContainers() {
|
|
34
|
+
try {
|
|
35
|
+
const raw = execSync('docker ps -a --format "{{json .}}"').toString();
|
|
36
|
+
return raw
|
|
37
|
+
.trim()
|
|
38
|
+
.split('\n')
|
|
39
|
+
.filter(Boolean)
|
|
40
|
+
.map((line) => {
|
|
41
|
+
const c = JSON.parse(line);
|
|
42
|
+
return {
|
|
43
|
+
name: c.Names,
|
|
44
|
+
kind: 'docker',
|
|
45
|
+
status: c.State === 'running' ? 'online' : c.State,
|
|
46
|
+
containerId: c.ID,
|
|
47
|
+
};
|
|
48
|
+
});
|
|
49
|
+
} catch (e) {
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// One-shot diagnostic for agent startup logs — the polling path above stays silent
|
|
55
|
+
// (same as getPm2Processes on a PM2-less box), but a Docker permission/availability
|
|
56
|
+
// problem is otherwise invisible until someone notices containers never show up.
|
|
57
|
+
function checkDockerAvailable() {
|
|
58
|
+
try {
|
|
59
|
+
execSync('docker ps', { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
60
|
+
return { ok: true };
|
|
61
|
+
} catch (e) {
|
|
62
|
+
return { ok: false, error: (e.stderr ? e.stderr.toString() : e.message).trim().split('\n')[0] };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Units that are always running on a stock Linux box but never interesting to read logs
|
|
67
|
+
// for — keeps the Process dropdown to services an operator actually deployed. The
|
|
68
|
+
// `@`-templated ones (getty@tty1, user@1000) are matched by prefix.
|
|
69
|
+
const SYSTEMD_NOISE =
|
|
70
|
+
/^(getty@|serial-getty@|user@|user-runtime-dir@|systemd-|dbus|polkit|udisks2|multipathd|snapd|ModemManager|irqbalance|chrony|ntp|cron|rsyslog|acpid|unattended-upgrades|networkd-dispatcher|lvm2|accounts-daemon|packagekit|fwupd|gdm|colord|upower)/;
|
|
71
|
+
|
|
72
|
+
// 'absent' = no systemd/journalctl at all (non-Linux, Alpine, container); 'unreadable' =
|
|
73
|
+
// journalctl exists but this OS user can't read the system journal (root, or membership
|
|
74
|
+
// in systemd-journal/adm, is required); 'ok' otherwise. Cheap enough to run on every
|
|
75
|
+
// metrics push, and it's what lets the UI explain *why* no units are listed.
|
|
76
|
+
function checkSystemdAvailable() {
|
|
77
|
+
// spawnSync (not execSync): journalctl prints its "not seeing messages from other
|
|
78
|
+
// users" hint on stderr while still exiting 0, and execSync drops stderr on success.
|
|
79
|
+
const r = spawnSync('journalctl', ['-n', '1', '--no-pager'], { encoding: 'utf-8' });
|
|
80
|
+
if (r.error) return { ok: false, state: 'absent' };
|
|
81
|
+
let user = null;
|
|
82
|
+
try {
|
|
83
|
+
user = os.userInfo().username;
|
|
84
|
+
} catch (e) {}
|
|
85
|
+
if (r.status !== 0 || /not seeing messages from other users/i.test(`${r.stdout}${r.stderr}`))
|
|
86
|
+
return { ok: false, state: 'unreadable', user };
|
|
87
|
+
return { ok: true, state: 'ok', user };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function getSystemdUnits() {
|
|
91
|
+
try {
|
|
92
|
+
const raw = execSync(
|
|
93
|
+
'systemctl list-units --type=service --state=running --no-legend --plain --no-pager',
|
|
94
|
+
{ stdio: ['ignore', 'pipe', 'ignore'] },
|
|
95
|
+
).toString();
|
|
96
|
+
return raw
|
|
97
|
+
.trim()
|
|
98
|
+
.split('\n')
|
|
99
|
+
.filter(Boolean)
|
|
100
|
+
.map((line) =>
|
|
101
|
+
line
|
|
102
|
+
.trim()
|
|
103
|
+
.split(/\s+/)[0]
|
|
104
|
+
.replace(/\.service$/, ''),
|
|
105
|
+
)
|
|
106
|
+
.filter((name) => name && !SYSTEMD_NOISE.test(name))
|
|
107
|
+
.map((name) => ({ name, kind: 'systemd', status: 'online', cpu: 0, memory_mb: 0 }));
|
|
108
|
+
} catch (e) {
|
|
109
|
+
return [];
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// "12.5MiB / 1.9GiB" -> 12.5 rounded to whole MB, regardless of Ki/Mi/Gi unit.
|
|
114
|
+
function parseMemUsageMb(memUsage) {
|
|
115
|
+
const left = memUsage.split('/')[0].trim();
|
|
116
|
+
const m = left.match(/^([\d.]+)\s*([A-Za-z]+)/);
|
|
117
|
+
if (!m) return 0;
|
|
118
|
+
const val = parseFloat(m[1]),
|
|
119
|
+
unit = m[2].toLowerCase();
|
|
120
|
+
if (unit.startsWith('g')) return Math.round(val * 1024);
|
|
121
|
+
if (unit.startsWith('k')) return Math.round(val / 1024);
|
|
122
|
+
return Math.round(val);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function getDockerStats() {
|
|
126
|
+
try {
|
|
127
|
+
const raw = execSync('docker stats --no-stream --format "{{json .}}"').toString();
|
|
128
|
+
const stats = {};
|
|
129
|
+
raw
|
|
130
|
+
.trim()
|
|
131
|
+
.split('\n')
|
|
132
|
+
.filter(Boolean)
|
|
133
|
+
.forEach((line) => {
|
|
134
|
+
const s = JSON.parse(line);
|
|
135
|
+
stats[s.Name] = { cpu: parseFloat(s.CPUPerc) || 0, memory_mb: parseMemUsageMb(s.MemUsage) };
|
|
136
|
+
});
|
|
137
|
+
return stats;
|
|
138
|
+
} catch (e) {
|
|
139
|
+
return {};
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function getContainerProcesses() {
|
|
144
|
+
const containers = getDockerContainers();
|
|
145
|
+
if (containers.length === 0) return [];
|
|
146
|
+
const stats = getDockerStats();
|
|
147
|
+
return containers.map((c) => {
|
|
148
|
+
const s = stats[c.name] || { cpu: 0, memory_mb: 0 };
|
|
149
|
+
return { name: c.name, kind: 'docker', status: c.status, cpu: s.cpu, memory_mb: s.memory_mb };
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function getNetworkStats() {
|
|
154
|
+
try {
|
|
155
|
+
const data = fs.readFileSync('/proc/net/dev', 'utf-8');
|
|
156
|
+
const lines = data.trim().split('\n').slice(2);
|
|
157
|
+
let rx = 0,
|
|
158
|
+
tx = 0;
|
|
159
|
+
for (const line of lines) {
|
|
160
|
+
const [ifacePart, rest] = line.split(':');
|
|
161
|
+
if (!rest) continue;
|
|
162
|
+
if (ifacePart.trim() === 'lo') continue;
|
|
163
|
+
const fields = rest.trim().split(/\s+/).map(Number);
|
|
164
|
+
rx += fields[0] || 0;
|
|
165
|
+
tx += fields[8] || 0;
|
|
166
|
+
}
|
|
167
|
+
return { rx_bytes: rx, tx_bytes: tx };
|
|
168
|
+
} catch (e) {
|
|
169
|
+
return { rx_bytes: 0, tx_bytes: 0 };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function getTopProcesses(sortFlag, limit) {
|
|
174
|
+
try {
|
|
175
|
+
const out = execSync(`ps -eo pid,comm,%cpu,%mem --sort=${sortFlag} --no-headers`).toString();
|
|
176
|
+
return out
|
|
177
|
+
.trim()
|
|
178
|
+
.split('\n')
|
|
179
|
+
.slice(0, limit)
|
|
180
|
+
.map((line) => {
|
|
181
|
+
const parts = line.trim().split(/\s+/);
|
|
182
|
+
const pid = parts[0],
|
|
183
|
+
mem = parts[parts.length - 1],
|
|
184
|
+
cpu = parts[parts.length - 2];
|
|
185
|
+
const name = parts.slice(1, parts.length - 2).join(' ');
|
|
186
|
+
return { pid, name, cpu: parseFloat(cpu), mem: parseFloat(mem) };
|
|
187
|
+
});
|
|
188
|
+
} catch (e) {
|
|
189
|
+
return [];
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function getUptimeString() {
|
|
194
|
+
const secs = os.uptime();
|
|
195
|
+
const d = Math.floor(secs / 86400),
|
|
196
|
+
h = Math.floor((secs % 86400) / 3600),
|
|
197
|
+
m = Math.floor((secs % 3600) / 60);
|
|
198
|
+
return `${d}d ${h}h ${m}m`;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function getSystemMetrics() {
|
|
202
|
+
const systemd = checkSystemdAvailable();
|
|
203
|
+
const totalMem = os.totalmem(),
|
|
204
|
+
freeMem = os.freemem();
|
|
205
|
+
const memUsedPercent = (((totalMem - freeMem) / totalMem) * 100).toFixed(1);
|
|
206
|
+
let diskPercent = 'N/A',
|
|
207
|
+
diskUsed = 'N/A',
|
|
208
|
+
diskTotal = 'N/A';
|
|
209
|
+
try {
|
|
210
|
+
const dfOut = execSync('df -h / | tail -1').toString().trim().split(/\s+/);
|
|
211
|
+
diskTotal = dfOut[1];
|
|
212
|
+
diskUsed = dfOut[2];
|
|
213
|
+
diskPercent = dfOut[4];
|
|
214
|
+
} catch (e) {}
|
|
215
|
+
return {
|
|
216
|
+
load_avg: os.loadavg().map((n) => n.toFixed(2)),
|
|
217
|
+
cpu_count: os.cpus().length,
|
|
218
|
+
mem_used_percent: memUsedPercent,
|
|
219
|
+
mem_used_mb: Math.round((totalMem - freeMem) / 1024 / 1024),
|
|
220
|
+
mem_total_mb: Math.round(totalMem / 1024 / 1024),
|
|
221
|
+
disk_percent: diskPercent,
|
|
222
|
+
disk_used: diskUsed,
|
|
223
|
+
disk_total: diskTotal,
|
|
224
|
+
hostname: os.hostname(),
|
|
225
|
+
uptime_str: getUptimeString(),
|
|
226
|
+
network: getNetworkStats(),
|
|
227
|
+
top_cpu: getTopProcesses('-%cpu', 5),
|
|
228
|
+
top_mem: getTopProcesses('-%mem', 5),
|
|
229
|
+
processes: [
|
|
230
|
+
...getPm2Processes(),
|
|
231
|
+
...getContainerProcesses(),
|
|
232
|
+
...(systemd.ok ? getSystemdUnits() : []),
|
|
233
|
+
],
|
|
234
|
+
diagnostics: { systemd: systemd.state, user: systemd.user || null },
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
module.exports = {
|
|
239
|
+
getSystemMetrics,
|
|
240
|
+
getPm2Processes,
|
|
241
|
+
getDockerContainers,
|
|
242
|
+
getContainerProcesses,
|
|
243
|
+
checkDockerAvailable,
|
|
244
|
+
getSystemdUnits,
|
|
245
|
+
checkSystemdAvailable,
|
|
246
|
+
getNetworkStats,
|
|
247
|
+
getTopProcesses,
|
|
248
|
+
getUptimeString,
|
|
249
|
+
};
|