@xeplr/monitor 0.1.2 → 1.0.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 +148 -99
- package/api/README.md +71 -0
- package/api/app.js +46 -0
- package/api/bin/auth.js +37 -0
- package/api/bin/www +72 -0
- package/api/db/setup.js +10 -0
- package/api/env.required.js +37 -0
- package/api/lib/host.js +188 -0
- package/api/lib/jobs.js +83 -0
- package/api/lib/services.js +67 -0
- package/api/lib/stats.js +362 -0
- package/{lib → api/lib}/systemd.js +75 -14
- package/api/migrations/0001_monitor.sql +43 -0
- package/api/migrations/0002_backup_connections.sql +26 -0
- package/api/migrations/0003_settings_audit.sql +18 -0
- package/api/migrations/0004_monitor_stats.sql +73 -0
- package/api/migrations/README.md +9 -0
- package/api/migrations-auth/0006_monitor.sql +56 -0
- package/api/migrations-auth/0007_monitor_home.sql +42 -0
- package/api/migrations-auth/0008_backups.sql +44 -0
- package/api/migrations-auth/0009_app_settings.sql +44 -0
- package/api/migrations-auth/0010_monitor_history.sql +22 -0
- package/api/models/index.js +18 -0
- package/api/package-lock.json +2839 -0
- package/api/package.json +39 -0
- package/api/production.env.example +61 -0
- package/api/routes/appSettings.js +73 -0
- package/api/routes/index.js +47 -0
- package/api/routes/monitor.js +196 -0
- package/api/setup.schema.js +166 -0
- package/deploy/control.sh +27 -0
- package/deploy/deploy.js +183 -0
- package/deploy/install.sh +240 -0
- package/deploy/settings.cjs +93 -0
- package/package.json +28 -46
- package/ui/.env +8 -0
- package/ui/README.md +29 -0
- package/ui/index.html +13 -0
- package/ui/package-lock.json +2094 -0
- package/ui/package.json +31 -0
- package/ui/pages.json +33 -0
- package/ui/public/logo-wide.svg +17 -0
- package/ui/public/logo.svg +10 -0
- package/ui/src/App.jsx +130 -0
- package/ui/src/api/monitor.js +6 -0
- package/ui/src/index.css +414 -0
- package/ui/src/main.jsx +27 -0
- package/ui/src/pages/Connections.jsx +9 -0
- package/ui/src/pages/Home.jsx +8 -0
- package/ui/src/pages/Monitor.jsx +9 -0
- package/ui/vite.config.js +56 -0
- package/bin/server.js +0 -19
- package/bin/users.js +0 -86
- package/deploy/monitor.env.example +0 -16
- package/deploy/nginx.conf.example +0 -17
- package/deploy/sudoers.example +0 -13
- package/deploy/xeplr-monitor.service +0 -26
- package/index.js +0 -89
- package/lib/router.js +0 -179
- package/lib/services.js +0 -76
- package/lib/session.js +0 -78
- package/lib/store.js +0 -73
- package/lib/users.js +0 -119
- package/public/assets/index-BsBYpvNI.js +0 -18
- package/public/assets/index-DNZBwVTn.css +0 -1
- package/public/index.html +0 -15
package/api/lib/stats.js
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
// THE HISTORY BEHIND THE CHARTS (migrations/0004_monitor_stats.sql).
|
|
2
|
+
//
|
|
3
|
+
// Every minute the "monitor-sample" job (a system job of @xeplr/jobs, kept by
|
|
4
|
+
// lib/jobs.js — no timer of our own) runs record():
|
|
5
|
+
// - a reading of every watched service (memory, its peak, CPU over the
|
|
6
|
+
// minute, threads, restarts) and of the server (memory, CPU, swap, load);
|
|
7
|
+
// - what each service's log said since the last read (journald, from its
|
|
8
|
+
// cursor): lines, warnings and errors per minute, and the requests it
|
|
9
|
+
// logged — "← GET /reports/:id/rows 200 73ms" (@xeplr/logs' request line,
|
|
10
|
+
// which every xeplr app writes), counted per minute per address.
|
|
11
|
+
// Daily, "monitor-prune" removes what is older than KEEP_DAYS.
|
|
12
|
+
//
|
|
13
|
+
// A SPIKE BETWEEN READINGS: systemd's MemoryPeak is the most a service has
|
|
14
|
+
// held since it started. When it rose since the last reading, the service
|
|
15
|
+
// went that high inside this minute even if the reading itself is lower —
|
|
16
|
+
// kept as spikeBytes, the dot on the chart.
|
|
17
|
+
//
|
|
18
|
+
// Reading back (the routes): points grouped into steps that fit the range —
|
|
19
|
+
// a minute for an hour, 5 minutes for a day, 30 for a week, 2 hours for a
|
|
20
|
+
// month — each step's highest memory and CPU (a spike is never averaged
|
|
21
|
+
// away) and its average. Every query is stoppable: the person leaving the
|
|
22
|
+
// page cancels it in Postgres (@xeplr/base-apis stoppable).
|
|
23
|
+
var os = require('os');
|
|
24
|
+
var systemd = require('./systemd');
|
|
25
|
+
var host = require('./host');
|
|
26
|
+
var { MonitoredService } = require('../models');
|
|
27
|
+
|
|
28
|
+
var KEEP_DAYS = 30;
|
|
29
|
+
var MAX_ADDRESSES = 1000; // distinct addresses per service per read; the rest count as "(other)"
|
|
30
|
+
var MAX_BACK_MS = 60 * 60 * 1000; // after a gap (the monitor was down), read at most the last hour
|
|
31
|
+
var READ_TIMEOUT_MS = 30000;
|
|
32
|
+
var QUERY_TIMEOUT_MS = 30000;
|
|
33
|
+
var MAX_RANGE_MS = KEEP_DAYS * 24 * 3600 * 1000;
|
|
34
|
+
|
|
35
|
+
function knex() { return MonitoredService.knex(); }
|
|
36
|
+
function refuse(message, status) { var e = new Error(message); e.status = status || 400; return e; }
|
|
37
|
+
|
|
38
|
+
// ── what a log line says ─────────────────────────────────────────────────
|
|
39
|
+
|
|
40
|
+
var METHODS = 'GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS';
|
|
41
|
+
// "← GET /x 200 73ms" (@xeplr/logs), and the same words without the arrow.
|
|
42
|
+
var HIT = new RegExp('(?:^|\\s)(?:←\\s*)?(' + METHODS + ')\\s+(\\S+)\\s+([1-5]\\d\\d)\\s+(\\d+(?:\\.\\d+)?)\\s?ms\\b');
|
|
43
|
+
|
|
44
|
+
/** One address with its ids taken out: /reports/8fe1a7…/rows?x=1 → /reports/:id/rows. */
|
|
45
|
+
function pathOf(url) {
|
|
46
|
+
var p = String(url || '').split(/[?#]/)[0] || '/';
|
|
47
|
+
p = p.split('/').map(function(seg) {
|
|
48
|
+
if (!seg) return seg;
|
|
49
|
+
if (/^\d+$/.test(seg)) return ':n';
|
|
50
|
+
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(seg)) return ':id';
|
|
51
|
+
if (/^[0-9a-f]{16,}$/i.test(seg)) return ':id';
|
|
52
|
+
if (seg.length >= 20 && /\d/.test(seg) && /^[A-Za-z0-9_-]+$/.test(seg)) return ':id';
|
|
53
|
+
return seg;
|
|
54
|
+
}).join('/');
|
|
55
|
+
return p.length > 300 ? p.slice(0, 299) + '…' : p;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A request the line reports → { method, path, status, ms }, or null. */
|
|
59
|
+
function hitOf(message) {
|
|
60
|
+
var m = HIT.exec(String(message || ''));
|
|
61
|
+
if (!m) return null;
|
|
62
|
+
return { method: m[1], path: pathOf(m[2]), status: Number(m[3]), ms: Math.round(Number(m[4])) };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function minuteOf(ms) { return new Date(Math.floor(ms / 60000) * 60000); }
|
|
66
|
+
|
|
67
|
+
/** One read's lines, counted: { counts: Map(minute → {lines,warnings,errors}), hits: Map(key → row) }. */
|
|
68
|
+
function tally() {
|
|
69
|
+
var counts = new Map();
|
|
70
|
+
var hits = new Map();
|
|
71
|
+
var addresses = new Set();
|
|
72
|
+
return {
|
|
73
|
+
counts: counts,
|
|
74
|
+
hits: hits,
|
|
75
|
+
add: function(entry) {
|
|
76
|
+
var at = minuteOf(entry.at).toISOString();
|
|
77
|
+
var c = counts.get(at) || { lines: 0, warnings: 0, errors: 0 };
|
|
78
|
+
c.lines++;
|
|
79
|
+
if (entry.priority <= 3) c.errors++;
|
|
80
|
+
else if (entry.priority === 4) c.warnings++;
|
|
81
|
+
counts.set(at, c);
|
|
82
|
+
var h = hitOf(entry.message);
|
|
83
|
+
if (!h) return;
|
|
84
|
+
var key = h.method + ' ' + h.path;
|
|
85
|
+
if (!addresses.has(key)) {
|
|
86
|
+
if (addresses.size >= MAX_ADDRESSES) h.path = '(other)';
|
|
87
|
+
else addresses.add(key);
|
|
88
|
+
}
|
|
89
|
+
var k = at + '\u0000' + h.method + '\u0000' + h.path + '\u0000' + h.status;
|
|
90
|
+
var row = hits.get(k) || { at: at, method: h.method, path: h.path, status: h.status, hits: 0, totalMs: 0, maxMs: 0 };
|
|
91
|
+
row.hits++;
|
|
92
|
+
row.totalMs += h.ms;
|
|
93
|
+
row.maxMs = Math.max(row.maxMs, h.ms);
|
|
94
|
+
hits.set(k, row);
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ── recording ────────────────────────────────────────────────────────────
|
|
100
|
+
|
|
101
|
+
var lastCpu = new Map(); // unit → { seconds, at }: CPU over the minute, not since the page's last look
|
|
102
|
+
var lastPeak = new Map(); // unit → MemoryPeak at the last reading
|
|
103
|
+
var lastServerCpu = null;
|
|
104
|
+
|
|
105
|
+
/** CPU % between two readings of a counter in seconds (100 = one core), or null. */
|
|
106
|
+
function percentBetween(prev, seconds, at) {
|
|
107
|
+
if (!prev || seconds === null || seconds === undefined || seconds < prev.seconds || at <= prev.at) return null;
|
|
108
|
+
return Math.round(((seconds - prev.seconds) / ((at - prev.at) / 1000)) * 1000) / 10;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The peak, when it rose since the last reading (a spike inside this minute), else null. */
|
|
112
|
+
function spikeOf(prev, peak) {
|
|
113
|
+
if (peak === null || peak === undefined || prev === undefined || prev === null) return null;
|
|
114
|
+
return peak > prev ? peak : null;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* One service's reading as a row, from what systemd said (systemd.status):
|
|
119
|
+
* CPU over the minute since this job's own last reading (not the page's
|
|
120
|
+
* 5-second look), and the peak when it rose — a spike inside the minute.
|
|
121
|
+
*/
|
|
122
|
+
function serviceRow(unit, st, at) {
|
|
123
|
+
var cpu = st.cpuSeconds === null || st.cpuSeconds === undefined ? null : st.cpuSeconds;
|
|
124
|
+
var row = {
|
|
125
|
+
unit: unit,
|
|
126
|
+
at: new Date(at),
|
|
127
|
+
state: st.state,
|
|
128
|
+
memoryBytes: st.memoryBytes,
|
|
129
|
+
memoryPeakBytes: st.memoryPeakBytes,
|
|
130
|
+
spikeBytes: spikeOf(lastPeak.get(unit), st.memoryPeakBytes),
|
|
131
|
+
memoryMaxBytes: st.memoryMaxBytes,
|
|
132
|
+
swapBytes: st.swapBytes,
|
|
133
|
+
cpuSeconds: cpu,
|
|
134
|
+
cpuPercent: st.state === 'active' ? percentBetween(lastCpu.get(unit), cpu, at) : null,
|
|
135
|
+
tasks: st.tasks,
|
|
136
|
+
restarts: st.restarts
|
|
137
|
+
};
|
|
138
|
+
if (cpu !== null) lastCpu.set(unit, { seconds: cpu, at: at });
|
|
139
|
+
if (st.memoryPeakBytes !== null && st.memoryPeakBytes !== undefined) lastPeak.set(unit, st.memoryPeakBytes);
|
|
140
|
+
return row;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The server's reading as a row, from /proc/meminfo's and /proc/stat's text; null without them. */
|
|
144
|
+
function serverRow(memText, statText, at, load1) {
|
|
145
|
+
if (memText === null || memText === undefined) return null;
|
|
146
|
+
var mem = host.memoryOf(host.meminfo(memText));
|
|
147
|
+
if (!mem) return null;
|
|
148
|
+
var ticks = host.cpuTicks(statText);
|
|
149
|
+
var cpu = null;
|
|
150
|
+
if (ticks && lastServerCpu && ticks.total > lastServerCpu.total) {
|
|
151
|
+
cpu = Math.round((1 - (ticks.idle - lastServerCpu.idle) / (ticks.total - lastServerCpu.total)) * 1000) / 10;
|
|
152
|
+
}
|
|
153
|
+
if (ticks) lastServerCpu = ticks;
|
|
154
|
+
return {
|
|
155
|
+
at: new Date(at),
|
|
156
|
+
memoryTotalBytes: mem.totalBytes,
|
|
157
|
+
memoryUsedBytes: mem.usedBytes,
|
|
158
|
+
availableBytes: mem.availableBytes,
|
|
159
|
+
cacheBytes: mem.cacheBytes + mem.buffersBytes,
|
|
160
|
+
swapUsedBytes: mem.swapUsedBytes,
|
|
161
|
+
cpuPercent: cpu,
|
|
162
|
+
load1: load1 === undefined || load1 === null ? null : Math.round(load1 * 100) / 100
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function saveSample(row) { await knex()('monitor_samples').insert(row).onConflict(['unit', 'at']).ignore(); }
|
|
167
|
+
async function saveServer(row) { if (row) await knex()('monitor_server_samples').insert(row).onConflict('at').ignore(); }
|
|
168
|
+
|
|
169
|
+
/** Where to read the unit's log from: its cursor when the last read was recent, else a time. */
|
|
170
|
+
async function readFrom(unit, now) {
|
|
171
|
+
var last = await knex()('monitor_log_reads').where({ unit: unit }).first();
|
|
172
|
+
if (last && last.cursor && last.readAt && now - new Date(last.readAt).getTime() < MAX_BACK_MS) return { cursor: last.cursor, limitMs: READ_TIMEOUT_MS };
|
|
173
|
+
return { since: new Date(now - (last ? MAX_BACK_MS : 60000)), limitMs: READ_TIMEOUT_MS };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* A read's counts written, with where it stopped — in one transaction, so a
|
|
178
|
+
* minute is never counted without its cursor moving. A minute read in two
|
|
179
|
+
* runs adds up, never replaces.
|
|
180
|
+
*/
|
|
181
|
+
async function saveRead(unit, t, cursor, now) {
|
|
182
|
+
var counts = [];
|
|
183
|
+
t.counts.forEach(function(c, at) { counts.push({ unit: unit, at: new Date(at), lines: c.lines, warnings: c.warnings, errors: c.errors }); });
|
|
184
|
+
var hits = [];
|
|
185
|
+
t.hits.forEach(function(h) { hits.push({ unit: unit, at: new Date(h.at), method: h.method, path: h.path, status: h.status, hits: h.hits, totalMs: h.totalMs, maxMs: h.maxMs }); });
|
|
186
|
+
await knex().transaction(async function(trx) {
|
|
187
|
+
for (var i = 0; i < counts.length; i += 500) {
|
|
188
|
+
await trx('monitor_log_counts').insert(counts.slice(i, i + 500)).onConflict(['unit', 'at']).merge({
|
|
189
|
+
lines: trx.raw('"monitor_log_counts"."lines" + excluded."lines"'),
|
|
190
|
+
warnings: trx.raw('"monitor_log_counts"."warnings" + excluded."warnings"'),
|
|
191
|
+
errors: trx.raw('"monitor_log_counts"."errors" + excluded."errors"')
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
for (var j = 0; j < hits.length; j += 500) {
|
|
195
|
+
await trx('monitor_hits').insert(hits.slice(j, j + 500)).onConflict(['unit', 'at', 'method', 'path', 'status']).merge({
|
|
196
|
+
hits: trx.raw('"monitor_hits"."hits" + excluded."hits"'),
|
|
197
|
+
totalMs: trx.raw('"monitor_hits"."totalMs" + excluded."totalMs"'),
|
|
198
|
+
maxMs: trx.raw('greatest("monitor_hits"."maxMs", excluded."maxMs")')
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
await trx('monitor_log_reads').insert({ unit: unit, cursor: cursor, readAt: new Date(now) }).onConflict('unit').merge();
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* One minute's recording: every watched service read and its log counted,
|
|
207
|
+
* then the server. One service failing does not stop the others; the run
|
|
208
|
+
* says which did. → what was recorded, for the job's run history.
|
|
209
|
+
*/
|
|
210
|
+
async function record(o) {
|
|
211
|
+
o = o || {};
|
|
212
|
+
var now = o.now || Date.now();
|
|
213
|
+
var list = await MonitoredService.query().select('unit');
|
|
214
|
+
var out = { services: 0, lines: 0, failed: [] };
|
|
215
|
+
for (var i = 0; i < list.length; i++) {
|
|
216
|
+
if (o.signal && o.signal.aborted) break;
|
|
217
|
+
var unit = list[i].unit;
|
|
218
|
+
try {
|
|
219
|
+
await saveSample(serviceRow(unit, await systemd.status(unit), now));
|
|
220
|
+
var t = tally();
|
|
221
|
+
var read = await systemd.readNew(unit, await readFrom(unit, now), t.add);
|
|
222
|
+
await saveRead(unit, t, read.cursor, now);
|
|
223
|
+
out.lines += read.lines;
|
|
224
|
+
out.services++;
|
|
225
|
+
} catch (err) {
|
|
226
|
+
out.failed.push({ unit: unit, error: err.message });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
var server = serverRow(host.readText('/proc/meminfo'), host.readText('/proc/stat'), now, os.loadavg()[0]);
|
|
230
|
+
await saveServer(server);
|
|
231
|
+
out.server = Boolean(server);
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Everything older than KEEP_DAYS, gone. → rows removed per table. */
|
|
236
|
+
async function prune(o) {
|
|
237
|
+
var before = new Date(((o && o.now) || Date.now()) - KEEP_DAYS * 24 * 3600 * 1000);
|
|
238
|
+
var k = knex();
|
|
239
|
+
var out = {};
|
|
240
|
+
var tables = ['monitor_samples', 'monitor_server_samples', 'monitor_log_counts', 'monitor_hits'];
|
|
241
|
+
for (var i = 0; i < tables.length; i++) out[tables[i]] = await k(tables[i]).where('at', '<', before).del();
|
|
242
|
+
return out;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// ── reading back ─────────────────────────────────────────────────────────
|
|
246
|
+
|
|
247
|
+
/** A range from the request: { from, to } as Dates (default the last hour), at most KEEP_DAYS. */
|
|
248
|
+
function rangeOf(q) {
|
|
249
|
+
q = q || {};
|
|
250
|
+
var to = q.to ? new Date(q.to) : new Date();
|
|
251
|
+
var from = q.from ? new Date(q.from) : new Date(to.getTime() - 3600 * 1000);
|
|
252
|
+
if (isNaN(from) || isNaN(to)) throw refuse('from and to are times, e.g. 2026-12-03T10:00:00Z');
|
|
253
|
+
if (from >= to) throw refuse('from must be before to');
|
|
254
|
+
if (to - from > MAX_RANGE_MS) throw refuse('At most ' + KEEP_DAYS + ' days at a time: that is how long the history is kept');
|
|
255
|
+
return { from: from, to: to };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** The step points are grouped by, in seconds, so a chart holds at most a few hundred. */
|
|
259
|
+
function stepOf(range) {
|
|
260
|
+
var span = range.to - range.from;
|
|
261
|
+
if (span <= 2 * 3600 * 1000) return 60;
|
|
262
|
+
if (span <= 26 * 3600 * 1000) return 300;
|
|
263
|
+
if (span <= 8 * 24 * 3600 * 1000) return 1800;
|
|
264
|
+
return 7200;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Raw SQL on the request's one held connection (stoppable): the person
|
|
269
|
+
* leaving cancels it in Postgres, and Postgres ends it at the time limit.
|
|
270
|
+
*/
|
|
271
|
+
function onConnection(stopper, sql, args, order) {
|
|
272
|
+
var bind;
|
|
273
|
+
stopper.onBuild({ onBuildKnex: function(fn) { bind = fn; }, timeout: function() {} });
|
|
274
|
+
// Only a query builder can be held to one connection (knex's raw cannot),
|
|
275
|
+
// so the SQL is read as a subquery of one.
|
|
276
|
+
var k = knex();
|
|
277
|
+
return bind(k.select('*').from(k.raw('(' + sql + ') AS "q"', args)).orderBy(order)).timeout(QUERY_TIMEOUT_MS, { cancel: true });
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function bucket(step) { return 'to_timestamp(floor(extract(epoch from "at") / ' + Number(step) + ') * ' + Number(step) + ')'; }
|
|
281
|
+
|
|
282
|
+
function num(v) { return v === null || v === undefined ? null : Number(v); }
|
|
283
|
+
|
|
284
|
+
/** One service's history: memory, CPU, threads, restarts, spikes, log counts and requests per step. */
|
|
285
|
+
async function serviceHistory(stopper, unit, q) {
|
|
286
|
+
var range = rangeOf(q);
|
|
287
|
+
var step = stepOf(range);
|
|
288
|
+
var k = knex();
|
|
289
|
+
var b = bucket(step);
|
|
290
|
+
var args = { unit: unit, from: range.from, to: range.to };
|
|
291
|
+
var samples = (await onConnection(stopper,
|
|
292
|
+
'SELECT ' + b + ' AS "at", max("memoryBytes") AS "memoryMax", avg("memoryBytes") AS "memoryAvg", max("spikeBytes") AS "spike",' +
|
|
293
|
+
' max("memoryMaxBytes") AS "limit", max("swapBytes") AS "swap", max("cpuPercent") AS "cpuMax", avg("cpuPercent") AS "cpuAvg",' +
|
|
294
|
+
' max("tasks") AS "tasks", max("restarts") AS "restarts", count(*) FILTER (WHERE "state" <> \'active\') AS "down"' +
|
|
295
|
+
' FROM "monitor_samples" WHERE "unit" = :unit AND "at" >= :from AND "at" < :to GROUP BY 1', args, [{ column: 'at' }]));
|
|
296
|
+
var logs = (await onConnection(stopper,
|
|
297
|
+
'SELECT ' + b + ' AS "at", sum("lines") AS "lines", sum("warnings") AS "warnings", sum("errors") AS "errors"' +
|
|
298
|
+
' FROM "monitor_log_counts" WHERE "unit" = :unit AND "at" >= :from AND "at" < :to GROUP BY 1', args, [{ column: 'at' }]));
|
|
299
|
+
var hits = (await onConnection(stopper,
|
|
300
|
+
'SELECT ' + b + ' AS "at", sum("hits") AS "hits", sum("hits") FILTER (WHERE "status" >= 500) AS "failed",' +
|
|
301
|
+
' sum("hits") FILTER (WHERE "status" >= 400 AND "status" < 500) AS "refused", sum("totalMs") AS "totalMs", max("maxMs") AS "maxMs"' +
|
|
302
|
+
' FROM "monitor_hits" WHERE "unit" = :unit AND "at" >= :from AND "at" < :to GROUP BY 1', args, [{ column: 'at' }]));
|
|
303
|
+
return {
|
|
304
|
+
unit: unit, from: range.from.toISOString(), to: range.to.toISOString(), stepSeconds: step,
|
|
305
|
+
samples: samples.map(function(r) {
|
|
306
|
+
return { at: new Date(r.at).toISOString(), memoryMax: num(r.memoryMax), memoryAvg: r.memoryAvg === null ? null : Math.round(Number(r.memoryAvg)), spike: num(r.spike),
|
|
307
|
+
limit: num(r.limit), swap: num(r.swap), cpuMax: num(r.cpuMax), cpuAvg: r.cpuAvg === null ? null : Math.round(Number(r.cpuAvg) * 10) / 10,
|
|
308
|
+
tasks: num(r.tasks), restarts: num(r.restarts), down: Number(r.down) };
|
|
309
|
+
}),
|
|
310
|
+
logs: logs.map(function(r) { return { at: new Date(r.at).toISOString(), lines: Number(r.lines), warnings: Number(r.warnings), errors: Number(r.errors) }; }),
|
|
311
|
+
hits: hits.map(function(r) {
|
|
312
|
+
var n = Number(r.hits);
|
|
313
|
+
return { at: new Date(r.at).toISOString(), hits: n, failed: Number(r.failed || 0), refused: Number(r.refused || 0), avgMs: n ? Math.round(Number(r.totalMs) / n) : null, maxMs: num(r.maxMs) };
|
|
314
|
+
})
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The server's history: memory used, available, cache, swap, CPU and load per step. */
|
|
319
|
+
async function serverHistory(stopper, q) {
|
|
320
|
+
var range = rangeOf(q);
|
|
321
|
+
var step = stepOf(range);
|
|
322
|
+
var rows = (await onConnection(stopper,
|
|
323
|
+
'SELECT ' + bucket(step) + ' AS "at", max("memoryTotalBytes") AS "total", max("memoryUsedBytes") AS "usedMax", avg("memoryUsedBytes") AS "usedAvg",' +
|
|
324
|
+
' min("availableBytes") AS "availableMin", avg("cacheBytes") AS "cache", max("swapUsedBytes") AS "swap", max("cpuPercent") AS "cpuMax",' +
|
|
325
|
+
' avg("cpuPercent") AS "cpuAvg", max("load1") AS "load"' +
|
|
326
|
+
' FROM "monitor_server_samples" WHERE "at" >= :from AND "at" < :to GROUP BY 1', { from: range.from, to: range.to }, [{ column: 'at' }]));
|
|
327
|
+
return {
|
|
328
|
+
from: range.from.toISOString(), to: range.to.toISOString(), stepSeconds: step,
|
|
329
|
+
samples: rows.map(function(r) {
|
|
330
|
+
return { at: new Date(r.at).toISOString(), total: num(r.total), usedMax: num(r.usedMax), usedAvg: r.usedAvg === null ? null : Math.round(Number(r.usedAvg)),
|
|
331
|
+
availableMin: num(r.availableMin), cache: r.cache === null ? null : Math.round(Number(r.cache)), swap: num(r.swap), cpuMax: num(r.cpuMax),
|
|
332
|
+
cpuAvg: r.cpuAvg === null ? null : Math.round(Number(r.cpuAvg) * 10) / 10, load: num(r.load) };
|
|
333
|
+
})
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Requests by address over a range: the busiest first, for one service or all. */
|
|
338
|
+
async function traffic(stopper, q) {
|
|
339
|
+
var range = rangeOf(q);
|
|
340
|
+
var args = { from: range.from, to: range.to };
|
|
341
|
+
var where = '"at" >= :from AND "at" < :to';
|
|
342
|
+
if (q && q.unit) { where += ' AND "unit" = :unit'; args.unit = systemd.unitName(q.unit); }
|
|
343
|
+
var limit = Math.min(Math.max(parseInt(q && q.limit, 10) || 200, 1), 1000);
|
|
344
|
+
var rows = (await onConnection(stopper,
|
|
345
|
+
'SELECT "unit", "method", "path", sum("hits") AS "hits", sum("hits") FILTER (WHERE "status" >= 500) AS "failed",' +
|
|
346
|
+
' sum("hits") FILTER (WHERE "status" >= 400 AND "status" < 500) AS "refused", sum("totalMs") AS "totalMs", max("maxMs") AS "maxMs"' +
|
|
347
|
+
' FROM "monitor_hits" WHERE ' + where + ' GROUP BY 1, 2, 3 ORDER BY 4 DESC, 3 LIMIT ' + limit, args, [{ column: 'hits', order: 'desc' }, { column: 'path' }]));
|
|
348
|
+
return {
|
|
349
|
+
from: range.from.toISOString(), to: range.to.toISOString(),
|
|
350
|
+
addresses: rows.map(function(r) {
|
|
351
|
+
var n = Number(r.hits);
|
|
352
|
+
return { unit: r.unit, method: r.method, path: r.path, hits: n, failed: Number(r.failed || 0), refused: Number(r.refused || 0),
|
|
353
|
+
avgMs: n ? Math.round(Number(r.totalMs) / n) : null, maxMs: num(r.maxMs) };
|
|
354
|
+
})
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
module.exports = {
|
|
359
|
+
record: record, prune: prune, serviceHistory: serviceHistory, serverHistory: serverHistory, traffic: traffic,
|
|
360
|
+
hitOf: hitOf, pathOf: pathOf, tally: tally, serviceRow: serviceRow, serverRow: serverRow, saveSample: saveSample, saveServer: saveServer, readFrom: readFrom, saveRead: saveRead, percentBetween: percentBetween, spikeOf: spikeOf, rangeOf: rangeOf, stepOf: stepOf,
|
|
361
|
+
KEEP_DAYS: KEEP_DAYS
|
|
362
|
+
};
|
|
@@ -7,8 +7,9 @@
|
|
|
7
7
|
// list, and a unit name is checked against UNIT before it reaches one. Only
|
|
8
8
|
// start, stop, restart and kill change anything.
|
|
9
9
|
//
|
|
10
|
-
// sudo: 'actions' (the default) runs those four through `sudo -n
|
|
11
|
-
//
|
|
10
|
+
// sudo: 'actions' (the default) runs those four through `sudo -n` — through
|
|
11
|
+
// the control command when one is configured (deploy/control.sh, the only
|
|
12
|
+
// command sudoers allows); 'all' reads
|
|
12
13
|
// the journal through sudo too; 'none' runs everything as the monitor's own
|
|
13
14
|
// user (root, or a user in the systemd-journal group that has polkit rights).
|
|
14
15
|
var { execFile, spawn } = require('child_process');
|
|
@@ -47,14 +48,6 @@ function unitName(name) {
|
|
|
47
48
|
return /\.(service|socket|timer|target|path|mount)$/.test(n) ? n : n + '.service';
|
|
48
49
|
}
|
|
49
50
|
|
|
50
|
-
/** Whether a unit matches one of the allowed patterns ("xeplr-*"; * matches anything). */
|
|
51
|
-
function allowed(unit, patterns) {
|
|
52
|
-
return (patterns || []).some(function(p) {
|
|
53
|
-
var re = new RegExp('^' + p.trim().replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
|
|
54
|
-
return re.test(unit) || re.test(unit.replace(/\.service$/, ''));
|
|
55
|
-
});
|
|
56
|
-
}
|
|
57
|
-
|
|
58
51
|
function run(bin, args, useSudo, limitMs) {
|
|
59
52
|
return new Promise(function(resolve, reject) {
|
|
60
53
|
var file = useSudo ? 'sudo' : bin;
|
|
@@ -63,7 +56,7 @@ function run(bin, args, useSudo, limitMs) {
|
|
|
63
56
|
if (err) {
|
|
64
57
|
var said = String(stderr || '').trim() || err.message;
|
|
65
58
|
if (err.killed) said = 'No answer within ' + Math.round(limitMs / 1000) + ' seconds';
|
|
66
|
-
else if (/a password is required|
|
|
59
|
+
else if (/a password is required|a terminal is required|interactive authentication is required/.test(said)) said = 'sudo refused: the monitor\'s user may not run "' + bin + ' ' + args.join(' ') + '" without a password. The deploy allows it (/etc/sudoers.d/xeplr-monitor): deploy again';
|
|
67
60
|
else if (err.code === 'ENOENT') said = file + ' is not installed here: the monitor controls systemd services, on Linux';
|
|
68
61
|
return reject(Object.assign(new Error(said), { status: 502, stdout: stdout }));
|
|
69
62
|
}
|
|
@@ -158,9 +151,13 @@ async function status(unit) {
|
|
|
158
151
|
/** start | stop | restart | kill (SIGKILL to every process of it). */
|
|
159
152
|
async function act(unit, action) {
|
|
160
153
|
if (ACTIONS.indexOf(action) < 0) throw refuse('Unknown action "' + action + '": start, stop, restart or kill');
|
|
161
|
-
var args = action === 'kill' ? ['kill', '--signal=SIGKILL', unit] : [action, unit];
|
|
162
154
|
try {
|
|
163
|
-
|
|
155
|
+
// With a control command (MONITOR_CONTROL_COMMAND, installed by the
|
|
156
|
+
// deploy: deploy/control.sh) sudo runs that, which checks the action, the
|
|
157
|
+
// and the name itself — sudoers then needs no wildcard.
|
|
158
|
+
// Without one (development), systemctl itself.
|
|
159
|
+
if (cfg.control && cfg.sudo !== 'none') await run(cfg.control, [action, unit], true, ACTION_LIMIT_MS);
|
|
160
|
+
else await run(cfg.systemctl, action === 'kill' ? ['kill', '--signal=SIGKILL', unit] : [action, unit], cfg.sudo !== 'none', ACTION_LIMIT_MS);
|
|
164
161
|
} catch (err) {
|
|
165
162
|
// systemd 255 (Ubuntu 24.04) kills the service, then says it could not
|
|
166
163
|
// signal its "auxiliary processes" even when it has none. Done is done:
|
|
@@ -314,6 +311,70 @@ function follow(unit, onLine, onEnd) {
|
|
|
314
311
|
return function stop() { try { child.kill('SIGTERM'); } catch (e) { /* already gone */ } };
|
|
315
312
|
}
|
|
316
313
|
|
|
314
|
+
/**
|
|
315
|
+
* Read a unit's log from where the last read stopped — after `cursor`, or
|
|
316
|
+
* since `since` when there is none — streamed, `onEntry({ at, priority,
|
|
317
|
+
* message })` for each line, so a busy minute is never held in memory whole.
|
|
318
|
+
* → { cursor, lines }: the cursor to start from next time. Ended at
|
|
319
|
+
* `limitMs`; what was read until then still counts.
|
|
320
|
+
*/
|
|
321
|
+
function readNew(unit, o, onEntry) {
|
|
322
|
+
o = o || {};
|
|
323
|
+
var argv = readArgs(unit, o);
|
|
324
|
+
var child = cfg.sudo === 'all' ? spawn('sudo', ['-n', cfg.journalctl].concat(argv)) : spawn(cfg.journalctl, argv);
|
|
325
|
+
var rest = '';
|
|
326
|
+
var cursor = o.cursor || null;
|
|
327
|
+
var lines = 0;
|
|
328
|
+
function take(l) {
|
|
329
|
+
var e = entryOf(l);
|
|
330
|
+
if (!e) return;
|
|
331
|
+
cursor = e.cursor || cursor;
|
|
332
|
+
lines++;
|
|
333
|
+
onEntry(e);
|
|
334
|
+
}
|
|
335
|
+
return new Promise(function(resolve, reject) {
|
|
336
|
+
var timer = setTimeout(function() { try { child.kill('SIGTERM'); } catch (e) { /* gone */ } }, o.limitMs || READ_LIMIT_MS);
|
|
337
|
+
if (timer.unref) timer.unref();
|
|
338
|
+
child.stdout.on('data', function(chunk) {
|
|
339
|
+
var parts = (rest + chunk.toString('utf8')).split('\n');
|
|
340
|
+
rest = parts.pop();
|
|
341
|
+
parts.forEach(take);
|
|
342
|
+
});
|
|
343
|
+
var errText = '';
|
|
344
|
+
child.stderr.on('data', function(c) { errText += c.toString('utf8'); });
|
|
345
|
+
child.on('error', function(e) { clearTimeout(timer); reject(e); });
|
|
346
|
+
child.on('close', function(code, signal) {
|
|
347
|
+
clearTimeout(timer);
|
|
348
|
+
take(rest);
|
|
349
|
+
if (code && !signal) return reject(new Error(errText.trim() || 'journalctl ended (' + code + ')'));
|
|
350
|
+
resolve({ cursor: cursor, lines: lines });
|
|
351
|
+
});
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** journalctl's arguments for readNew: after the cursor, or since a time (default a minute ago). */
|
|
356
|
+
function readArgs(unit, o) {
|
|
357
|
+
var argv = ['-u', unitName(unit), '-o', 'json', '--no-pager', '--output-fields=MESSAGE,PRIORITY'];
|
|
358
|
+
if (o && o.cursor) argv.push('--after-cursor', String(o.cursor));
|
|
359
|
+
else argv.push('--since', stamp((o && o.since) || new Date(Date.now() - 60000), 'since'));
|
|
360
|
+
return argv;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** One line of `journalctl -o json` → { at (ms), priority, message, cursor }, or null. */
|
|
364
|
+
function entryOf(text) {
|
|
365
|
+
if (!text) return null;
|
|
366
|
+
var e;
|
|
367
|
+
try { e = JSON.parse(text); } catch (err) { return null; }
|
|
368
|
+
var msg = e.MESSAGE;
|
|
369
|
+
if (Array.isArray(msg)) msg = Buffer.from(msg).toString('utf8'); // not valid UTF-8 as sent: journalctl gives the bytes
|
|
370
|
+
return {
|
|
371
|
+
at: Math.floor(Number(e.__REALTIME_TIMESTAMP) / 1000),
|
|
372
|
+
priority: e.PRIORITY === undefined ? 6 : Number(e.PRIORITY),
|
|
373
|
+
message: msg === undefined || msg === null ? '' : String(msg),
|
|
374
|
+
cursor: e.__CURSOR || null
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
|
|
317
378
|
/** The unit this process itself runs in (from its cgroup), or null — so the monitor never stops itself. */
|
|
318
379
|
function selfUnit() {
|
|
319
380
|
try {
|
|
@@ -323,4 +384,4 @@ function selfUnit() {
|
|
|
323
384
|
} catch (e) { return null; }
|
|
324
385
|
}
|
|
325
386
|
|
|
326
|
-
module.exports = { configure: configure, unitName: unitName,
|
|
387
|
+
module.exports = { configure: configure, unitName: unitName, status: status, act: act, processes: processes, forgetGone: forgetGone, commandsOf: commandsOf, logs: logs, follow: follow, readNew: readNew, readArgs: readArgs, entryOf: entryOf, selfUnit: selfUnit, lineOf: lineOf, ACTIONS: ACTIONS, MAX_LINES: MAX_LINES };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
-- 0001_monitor.sql — the monitor's own tables.
|
|
2
|
+
--
|
|
3
|
+
-- monitor_services: the systemd services someone chose to watch. A service is
|
|
4
|
+
-- controlled only once it is here AND its unit matches MONITOR_ALLOW; sudoers
|
|
5
|
+
-- repeats that pattern.
|
|
6
|
+
CREATE TABLE IF NOT EXISTS "monitor_services" (
|
|
7
|
+
"id" varchar(25) PRIMARY KEY,
|
|
8
|
+
"unit" varchar(200) NOT NULL, -- xeplr-bi-api.service
|
|
9
|
+
"label" varchar(80) NOT NULL, -- what people read; changed any time
|
|
10
|
+
"addedBy" varchar(200),
|
|
11
|
+
"isActive" boolean DEFAULT true,
|
|
12
|
+
"mtId1" varchar(25),
|
|
13
|
+
"mtId2" varchar(25),
|
|
14
|
+
"mtId3" varchar(25),
|
|
15
|
+
"mtId4" varchar(25),
|
|
16
|
+
"recordCreatedDate" timestamp DEFAULT now(),
|
|
17
|
+
"recordModifiedDate" timestamp DEFAULT now(),
|
|
18
|
+
"recordCreatedBy" varchar(25),
|
|
19
|
+
"recordModifiedBy" varchar(25)
|
|
20
|
+
);
|
|
21
|
+
CREATE UNIQUE INDEX IF NOT EXISTS "monitor_services_unit" ON "monitor_services" ("unit") WHERE "isActive";
|
|
22
|
+
|
|
23
|
+
-- monitor_audit: every change made through the monitor, refused ones too —
|
|
24
|
+
-- who, from where, what, on which service, and whether it worked.
|
|
25
|
+
CREATE TABLE IF NOT EXISTS "monitor_audit" (
|
|
26
|
+
"id" varchar(25) PRIMARY KEY,
|
|
27
|
+
"email" varchar(200),
|
|
28
|
+
"ip" varchar(64),
|
|
29
|
+
"action" varchar(40) NOT NULL, -- add | edit | remove | start | stop | restart | kill
|
|
30
|
+
"unit" varchar(200),
|
|
31
|
+
"ok" boolean NOT NULL,
|
|
32
|
+
"error" text,
|
|
33
|
+
"isActive" boolean DEFAULT true,
|
|
34
|
+
"mtId1" varchar(25),
|
|
35
|
+
"mtId2" varchar(25),
|
|
36
|
+
"mtId3" varchar(25),
|
|
37
|
+
"mtId4" varchar(25),
|
|
38
|
+
"recordCreatedDate" timestamp DEFAULT now(),
|
|
39
|
+
"recordModifiedDate" timestamp DEFAULT now(),
|
|
40
|
+
"recordCreatedBy" varchar(25),
|
|
41
|
+
"recordModifiedBy" varchar(25)
|
|
42
|
+
);
|
|
43
|
+
CREATE INDEX IF NOT EXISTS "monitor_audit_when" ON "monitor_audit" ("recordCreatedDate" DESC);
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
-- 0002_backup_connections.sql — the logins the backup jobs use.
|
|
2
|
+
--
|
|
3
|
+
-- A database connection is a SERVER login (host, port, user): the job picks
|
|
4
|
+
-- which database on it to back up. An S3 one is a bucket, its region and the
|
|
5
|
+
-- folder backups go in. What is not secret is in "details" (shown on the
|
|
6
|
+
-- page); the password or secret key is in "secret", encrypted with
|
|
7
|
+
-- ENCRYPTION_KEY (@xeplr/utils), never sent back to a browser and never in a
|
|
8
|
+
-- job: a job holds this row's id, and the login is filled in only for the run.
|
|
9
|
+
CREATE TABLE IF NOT EXISTS "backup_connections" (
|
|
10
|
+
"id" varchar(25) PRIMARY KEY,
|
|
11
|
+
"name" varchar(80) NOT NULL,
|
|
12
|
+
"kind" varchar(20) NOT NULL, -- postgres | mysql | s3
|
|
13
|
+
"details" jsonb NOT NULL, -- { host, port, user } | { bucket, region, prefix, accessKeyHint }
|
|
14
|
+
"secret" text NOT NULL, -- encrypted JSON: { password } | { accessKeyId, secretAccessKey }
|
|
15
|
+
"addedBy" varchar(200),
|
|
16
|
+
"isActive" boolean DEFAULT true,
|
|
17
|
+
"mtId1" varchar(25),
|
|
18
|
+
"mtId2" varchar(25),
|
|
19
|
+
"mtId3" varchar(25),
|
|
20
|
+
"mtId4" varchar(25),
|
|
21
|
+
"recordCreatedDate" timestamp DEFAULT now(),
|
|
22
|
+
"recordModifiedDate" timestamp DEFAULT now(),
|
|
23
|
+
"recordCreatedBy" varchar(25),
|
|
24
|
+
"recordModifiedBy" varchar(25)
|
|
25
|
+
);
|
|
26
|
+
CREATE UNIQUE INDEX IF NOT EXISTS "backup_connections_name" ON "backup_connections" (lower("name")) WHERE "isActive";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
-- 0003_settings_audit.sql
|
|
2
|
+
-- WHO CHANGED WHICH APP SETTING, AND WHEN (settings menu → App settings,
|
|
3
|
+
-- routes/appSettings.js over @xeplr/setup settingsRouter).
|
|
4
|
+
--
|
|
5
|
+
-- A change that cannot be recorded here is not saved — the library puts the
|
|
6
|
+
-- env file back. Setting NAMES only, never a value: a row here must be safe
|
|
7
|
+
-- to show anyone who may read the table.
|
|
8
|
+
--
|
|
9
|
+
-- Install-wide (no tenant columns): a setting belongs to the install, not to
|
|
10
|
+
-- a company. Never pruned by anything.
|
|
11
|
+
CREATE TABLE IF NOT EXISTS "settings_audit" (
|
|
12
|
+
"id" varchar(25) PRIMARY KEY,
|
|
13
|
+
"userId" varchar(25),
|
|
14
|
+
"userEmail" varchar(320),
|
|
15
|
+
"names" jsonb NOT NULL,
|
|
16
|
+
"changedAt" timestamptz NOT NULL DEFAULT now()
|
|
17
|
+
);
|
|
18
|
+
CREATE INDEX IF NOT EXISTS "settings_audit_when" ON "settings_audit" ("changedAt" DESC);
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
-- 0004_monitor_stats.sql — the history behind the charts: a reading of every
|
|
2
|
+
-- watched service and of the server each minute, and per minute what each
|
|
3
|
+
-- service's log said (lines, warnings, errors, and the requests it logged).
|
|
4
|
+
-- Written by the sampling job (lib/stats.js, the "monitor-sample" action, a
|
|
5
|
+
-- system job of @xeplr/jobs every minute); rows older than 30 days are
|
|
6
|
+
-- removed by "monitor-prune" (daily). Measurements, not records: no ids,
|
|
7
|
+
-- tenants or audit columns — this app runs one install, and the key is
|
|
8
|
+
-- (what, when).
|
|
9
|
+
|
|
10
|
+
-- One reading of one service.
|
|
11
|
+
CREATE TABLE IF NOT EXISTS "monitor_samples" (
|
|
12
|
+
"unit" varchar(200) NOT NULL,
|
|
13
|
+
"at" timestamptz NOT NULL,
|
|
14
|
+
"state" varchar(20), -- active | inactive | failed | …
|
|
15
|
+
"memoryBytes" bigint,
|
|
16
|
+
"memoryPeakBytes" bigint, -- systemd's MemoryPeak: the most since the service started
|
|
17
|
+
"spikeBytes" bigint, -- the peak, when it rose since the last reading: a spike inside this minute
|
|
18
|
+
"memoryMaxBytes" bigint, -- its limit (null: none)
|
|
19
|
+
"swapBytes" bigint,
|
|
20
|
+
"cpuSeconds" double precision, -- CPU used in all, since it started
|
|
21
|
+
"cpuPercent" real, -- over the minute since the last reading (100 = one core)
|
|
22
|
+
"tasks" integer,
|
|
23
|
+
"restarts" integer,
|
|
24
|
+
PRIMARY KEY ("unit", "at")
|
|
25
|
+
);
|
|
26
|
+
CREATE INDEX IF NOT EXISTS "monitor_samples_at" ON "monitor_samples" ("at");
|
|
27
|
+
|
|
28
|
+
-- One reading of the server.
|
|
29
|
+
CREATE TABLE IF NOT EXISTS "monitor_server_samples" (
|
|
30
|
+
"at" timestamptz PRIMARY KEY,
|
|
31
|
+
"memoryTotalBytes" bigint,
|
|
32
|
+
"memoryUsedBytes" bigint,
|
|
33
|
+
"availableBytes" bigint,
|
|
34
|
+
"cacheBytes" bigint,
|
|
35
|
+
"swapUsedBytes" bigint,
|
|
36
|
+
"cpuPercent" real, -- all cores together, over the minute
|
|
37
|
+
"load1" real
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
-- Per service per minute: how many log lines, warnings and errors.
|
|
41
|
+
CREATE TABLE IF NOT EXISTS "monitor_log_counts" (
|
|
42
|
+
"unit" varchar(200) NOT NULL,
|
|
43
|
+
"at" timestamptz NOT NULL, -- the minute
|
|
44
|
+
"lines" integer NOT NULL DEFAULT 0,
|
|
45
|
+
"warnings" integer NOT NULL DEFAULT 0,
|
|
46
|
+
"errors" integer NOT NULL DEFAULT 0,
|
|
47
|
+
PRIMARY KEY ("unit", "at")
|
|
48
|
+
);
|
|
49
|
+
CREATE INDEX IF NOT EXISTS "monitor_log_counts_at" ON "monitor_log_counts" ("at");
|
|
50
|
+
|
|
51
|
+
-- Per service per minute per address: the requests its log reported
|
|
52
|
+
-- ("← GET /reports/:id/rows 200 73ms"). Ids in the address are replaced by
|
|
53
|
+
-- :id, so one address is one row however many records it was asked for.
|
|
54
|
+
CREATE TABLE IF NOT EXISTS "monitor_hits" (
|
|
55
|
+
"unit" varchar(200) NOT NULL,
|
|
56
|
+
"at" timestamptz NOT NULL, -- the minute
|
|
57
|
+
"method" varchar(10) NOT NULL,
|
|
58
|
+
"path" varchar(300) NOT NULL,
|
|
59
|
+
"status" smallint NOT NULL,
|
|
60
|
+
"hits" integer NOT NULL DEFAULT 0,
|
|
61
|
+
"totalMs" bigint NOT NULL DEFAULT 0,
|
|
62
|
+
"maxMs" integer NOT NULL DEFAULT 0,
|
|
63
|
+
PRIMARY KEY ("unit", "at", "method", "path", "status")
|
|
64
|
+
);
|
|
65
|
+
CREATE INDEX IF NOT EXISTS "monitor_hits_at" ON "monitor_hits" ("at");
|
|
66
|
+
|
|
67
|
+
-- Where the last read of each service's log stopped (journald's cursor), so
|
|
68
|
+
-- each minute reads only what is new.
|
|
69
|
+
CREATE TABLE IF NOT EXISTS "monitor_log_reads" (
|
|
70
|
+
"unit" varchar(200) PRIMARY KEY,
|
|
71
|
+
"cursor" text,
|
|
72
|
+
"readAt" timestamptz
|
|
73
|
+
);
|