Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/hub/servers/app/metrics.ts
1503 views
1
/*
2
Express middleware for recording metrics about response time to requests.
3
*/
4
5
import { dirname } from "path";
6
import { Router } from "express";
7
import { get, new_histogram } from "@cocalc/server/metrics/metrics-recorder";
8
import { join } from "path";
9
import basePath from "@cocalc/backend/base-path";
10
import getPool from "@cocalc/database/pool";
11
import { getLogger } from "@cocalc/hub/logger";
12
13
const log = getLogger("metrics");
14
15
// initialize metrics
16
const responseTimeHistogram = new_histogram("http_histogram", "http server", {
17
buckets: [0.01, 0.1, 1, 2, 5, 10, 20],
18
labels: ["path", "method", "code"],
19
});
20
21
// response time metrics
22
function metrics(req, res, next) {
23
const resFinished = responseTimeHistogram.startTimer();
24
const originalEnd = res.end;
25
res.end = (...args) => {
26
originalEnd.apply(res, args);
27
if (!req.path) {
28
return;
29
}
30
// for regular paths, we ignore the file
31
const path = dirname(req.path).split("/").slice(0, 2).join("/");
32
resFinished({
33
path,
34
method: req.method,
35
code: res.statusCode,
36
});
37
};
38
next();
39
}
40
41
export function setupInstrumentation(router: Router) {
42
router.use(metrics);
43
}
44
45
async function isEnabled(pool): Promise<boolean> {
46
const { rows } = await pool.query(
47
"SELECT value FROM server_settings WHERE name='prometheus_metrics'",
48
);
49
const enabled = rows.length > 0 && rows[0].value == "yes";
50
log.info("isEnabled", enabled);
51
return enabled;
52
}
53
54
export function initMetricsEndpoint(router: Router) {
55
const endpoint = join(basePath, "metrics");
56
log.info("initMetricsEndpoint at ", endpoint);
57
// long cache so we can easily check before each response and it is still fast.
58
const pool = getPool("long");
59
60
router.get(endpoint, async (_req, res) => {
61
res.header("Content-Type", "text/plain");
62
res.header("Cache-Control", "no-cache, no-store");
63
if (!(await isEnabled(pool))) {
64
res.json({
65
error:
66
"Sharing of metrics at /metrics is disabled. Metrics can be enabled in the site administration page.",
67
});
68
return;
69
}
70
const metricsRecorder = get();
71
if (metricsRecorder != null) {
72
res.send(await metricsRecorder.metrics());
73
} else {
74
res.json({ error: "Metrics recorder not initialized." });
75
}
76
});
77
}
78
79