@redkern/node-red-prometheus 0.0.0-stage → 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/CHANGELOG.md +32 -0
- package/LICENSE +188 -0
- package/README.md +176 -2
- package/SECURITY.md +18 -0
- package/examples/basic-metrics.json +131 -0
- package/examples/section-timer.json +138 -0
- package/lib/cardinality.js +71 -0
- package/lib/default-metrics.js +51 -0
- package/lib/palette.js +154 -0
- package/lib/receiver.js +169 -0
- package/lib/registry.js +241 -0
- package/lib/warn-once.js +20 -0
- package/nodes/icons/redkern-prom-exporter.svg +9 -0
- package/nodes/icons/redkern-prom-metric.svg +9 -0
- package/nodes/locales/en-US/prometheus.html +75 -0
- package/nodes/locales/en-US/prometheus.json +98 -0
- package/nodes/prometheus.html +415 -0
- package/nodes/prometheus.js +337 -0
- package/observability/grafana-dashboard.json +349 -0
- package/observability/prometheus-rule.yaml +42 -0
- package/package.json +74 -4
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"id": "5c2e8d1f3a4b6c10",
|
|
4
|
+
"type": "tab",
|
|
5
|
+
"label": "redkern prom: section timer",
|
|
6
|
+
"disabled": false,
|
|
7
|
+
"info": ""
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"id": "5c2e8d1f3a4b6c11",
|
|
11
|
+
"type": "comment",
|
|
12
|
+
"z": "5c2e8d1f3a4b6c10",
|
|
13
|
+
"name": "Measure a part of the flow without function nodes",
|
|
14
|
+
"info": "Start timer writes msg.redkern.prom.timers; stop timer observes the elapsed seconds into the histogram.\nThe exporter is in the basics example.",
|
|
15
|
+
"x": 240,
|
|
16
|
+
"y": 40,
|
|
17
|
+
"wires": []
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"id": "5c2e8d1f3a4b6c12",
|
|
21
|
+
"type": "inject",
|
|
22
|
+
"z": "5c2e8d1f3a4b6c10",
|
|
23
|
+
"name": "request",
|
|
24
|
+
"props": [
|
|
25
|
+
{
|
|
26
|
+
"p": "payload"
|
|
27
|
+
}
|
|
28
|
+
],
|
|
29
|
+
"repeat": "",
|
|
30
|
+
"crontab": "",
|
|
31
|
+
"once": false,
|
|
32
|
+
"onceDelay": 0.1,
|
|
33
|
+
"topic": "",
|
|
34
|
+
"payload": "",
|
|
35
|
+
"payloadType": "date",
|
|
36
|
+
"x": 130,
|
|
37
|
+
"y": 100,
|
|
38
|
+
"wires": [
|
|
39
|
+
[
|
|
40
|
+
"5c2e8d1f3a4b6c13"
|
|
41
|
+
]
|
|
42
|
+
]
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
"id": "5c2e8d1f3a4b6c13",
|
|
46
|
+
"type": "redkern-prom-metric",
|
|
47
|
+
"z": "5c2e8d1f3a4b6c10",
|
|
48
|
+
"name": "start",
|
|
49
|
+
"metric": "5c2e8d1f3a4b6c20",
|
|
50
|
+
"operation": "startTimer",
|
|
51
|
+
"autoStep": true,
|
|
52
|
+
"step": "",
|
|
53
|
+
"stepType": "str",
|
|
54
|
+
"status": "success",
|
|
55
|
+
"statusType": "str",
|
|
56
|
+
"value": "1",
|
|
57
|
+
"valueType": "num",
|
|
58
|
+
"duration": "",
|
|
59
|
+
"durationType": "msg",
|
|
60
|
+
"durationUnit": "seconds",
|
|
61
|
+
"timer": "",
|
|
62
|
+
"labels": [],
|
|
63
|
+
"x": 290,
|
|
64
|
+
"y": 100,
|
|
65
|
+
"wires": [
|
|
66
|
+
[
|
|
67
|
+
"5c2e8d1f3a4b6c14"
|
|
68
|
+
]
|
|
69
|
+
]
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
"id": "5c2e8d1f3a4b6c14",
|
|
73
|
+
"type": "delay",
|
|
74
|
+
"z": "5c2e8d1f3a4b6c10",
|
|
75
|
+
"name": "slow work",
|
|
76
|
+
"pauseType": "random",
|
|
77
|
+
"timeout": "1",
|
|
78
|
+
"timeoutUnits": "seconds",
|
|
79
|
+
"rate": "1",
|
|
80
|
+
"nbRateUnits": "1",
|
|
81
|
+
"rateUnits": "second",
|
|
82
|
+
"randomFirst": "100",
|
|
83
|
+
"randomLast": "900",
|
|
84
|
+
"randomUnits": "milliseconds",
|
|
85
|
+
"drop": false,
|
|
86
|
+
"allowrate": false,
|
|
87
|
+
"outputs": 1,
|
|
88
|
+
"x": 440,
|
|
89
|
+
"y": 100,
|
|
90
|
+
"wires": [
|
|
91
|
+
[
|
|
92
|
+
"5c2e8d1f3a4b6c15"
|
|
93
|
+
]
|
|
94
|
+
]
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
"id": "5c2e8d1f3a4b6c15",
|
|
98
|
+
"type": "redkern-prom-metric",
|
|
99
|
+
"z": "5c2e8d1f3a4b6c10",
|
|
100
|
+
"name": "stop",
|
|
101
|
+
"metric": "5c2e8d1f3a4b6c20",
|
|
102
|
+
"operation": "stopTimer",
|
|
103
|
+
"autoStep": true,
|
|
104
|
+
"step": "",
|
|
105
|
+
"stepType": "str",
|
|
106
|
+
"status": "success",
|
|
107
|
+
"statusType": "str",
|
|
108
|
+
"value": "1",
|
|
109
|
+
"valueType": "num",
|
|
110
|
+
"duration": "",
|
|
111
|
+
"durationType": "msg",
|
|
112
|
+
"durationUnit": "seconds",
|
|
113
|
+
"timer": "",
|
|
114
|
+
"labels": [],
|
|
115
|
+
"x": 590,
|
|
116
|
+
"y": 100,
|
|
117
|
+
"wires": [
|
|
118
|
+
[]
|
|
119
|
+
]
|
|
120
|
+
},
|
|
121
|
+
{
|
|
122
|
+
"id": "5c2e8d1f3a4b6c20",
|
|
123
|
+
"type": "redkern-prom-metric-config",
|
|
124
|
+
"name": "",
|
|
125
|
+
"metricType": "histogram",
|
|
126
|
+
"metricName": "nodered_example_section_seconds",
|
|
127
|
+
"help": "Duration of the example section",
|
|
128
|
+
"labelNames": "",
|
|
129
|
+
"buckets": "0.1, 0.25, 0.5, 1, 2.5",
|
|
130
|
+
"withDuration": false,
|
|
131
|
+
"durationBuckets": "",
|
|
132
|
+
"percentiles": "",
|
|
133
|
+
"maxAgeSeconds": "",
|
|
134
|
+
"ageBuckets": "",
|
|
135
|
+
"maxSeriesPerMetric": 1000,
|
|
136
|
+
"allowlist": []
|
|
137
|
+
}
|
|
138
|
+
]
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// PRM-CARD-1, PRM-CARD-2, PRM-CARD-4: per-metric series limit (existing series keep updating) and optional
|
|
4
|
+
// label allowlists. PRM-CARD-3 (dropped counter, yellow status) lives in registry.js and nodes/prometheus.js.
|
|
5
|
+
|
|
6
|
+
const DEFAULT_MAX_SERIES = 1000;
|
|
7
|
+
const OTHER = 'other';
|
|
8
|
+
|
|
9
|
+
function seriesKey(labelNames, labels) {
|
|
10
|
+
// Unit separator cannot appear in a valid label name and is escaped in values by JSON.
|
|
11
|
+
return JSON.stringify(labelNames.map((name) => labels[name]));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {{ labelNames: string[], maxSeries?: number, allowlist?: Record<string, string[]>, onDrop?: () => void }} options
|
|
16
|
+
*/
|
|
17
|
+
function createCardinalityGuard({ labelNames, maxSeries = DEFAULT_MAX_SERIES, allowlist = {}, onDrop = () => {} }) {
|
|
18
|
+
const known = new Set();
|
|
19
|
+
let limit = normalizeLimit(maxSeries);
|
|
20
|
+
let allowed = normalizeAllowlist(allowlist);
|
|
21
|
+
let dropped = 0;
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
/**
|
|
25
|
+
* Returns the labels to write, or null when the series must be dropped.
|
|
26
|
+
* @param {Record<string, string>} labels
|
|
27
|
+
*/
|
|
28
|
+
admit(labels) {
|
|
29
|
+
const effective = {};
|
|
30
|
+
for (const name of labelNames) {
|
|
31
|
+
const value = labels[name];
|
|
32
|
+
const values = allowed.get(name);
|
|
33
|
+
effective[name] = values && !values.has(value) ? OTHER : value;
|
|
34
|
+
}
|
|
35
|
+
const key = seriesKey(labelNames, effective);
|
|
36
|
+
if (known.has(key)) return effective;
|
|
37
|
+
if (known.size >= limit) {
|
|
38
|
+
dropped += 1;
|
|
39
|
+
onDrop();
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
known.add(key);
|
|
43
|
+
return effective;
|
|
44
|
+
},
|
|
45
|
+
/** Applies new limits from a redeployed config node without resetting existing series (PRM-REG-3). */
|
|
46
|
+
update({ maxSeries: nextMax = DEFAULT_MAX_SERIES, allowlist: nextAllowlist = {} } = {}) {
|
|
47
|
+
limit = normalizeLimit(nextMax);
|
|
48
|
+
allowed = normalizeAllowlist(nextAllowlist);
|
|
49
|
+
},
|
|
50
|
+
get size() { return known.size; },
|
|
51
|
+
get dropped() { return dropped; },
|
|
52
|
+
get limit() { return limit; }
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function normalizeLimit(value) {
|
|
57
|
+
const number = Number(value);
|
|
58
|
+
if (!Number.isSafeInteger(number) || number < 1) return DEFAULT_MAX_SERIES;
|
|
59
|
+
return number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function normalizeAllowlist(allowlist) {
|
|
63
|
+
const map = new Map();
|
|
64
|
+
for (const [name, values] of Object.entries(allowlist || {})) {
|
|
65
|
+
if (!Array.isArray(values) || values.length === 0) continue;
|
|
66
|
+
map.set(name, new Set(values.map(String)));
|
|
67
|
+
}
|
|
68
|
+
return map;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
module.exports = { createCardinalityGuard, DEFAULT_MAX_SERIES, OTHER };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const os = require('node:os');
|
|
4
|
+
|
|
5
|
+
// PRM-DEF-1, PRM-DEF-2, PRM-DEF-3: process/runtime metrics collected into a registry separate from user metrics, so an
|
|
6
|
+
// exporter can switch them off, change the prefix or the host label without touching user series.
|
|
7
|
+
//
|
|
8
|
+
// The client's default metrics install PerformanceObservers that are never disconnected, so one
|
|
9
|
+
// registry is created per (prefix, hostLabel) and reused for the life of the process.
|
|
10
|
+
|
|
11
|
+
const cache = new Map();
|
|
12
|
+
|
|
13
|
+
function hostName() {
|
|
14
|
+
return process.env.HOSTNAME || os.hostname();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {{ promClient: typeof import('@prometheus-io/client'), prefix: string, hostLabel: boolean, deployCount: () => number }} options
|
|
19
|
+
*/
|
|
20
|
+
function defaultMetricsRegistry({ promClient, prefix, hostLabel, deployCount }) {
|
|
21
|
+
const key = JSON.stringify([prefix, hostLabel]);
|
|
22
|
+
const cached = cache.get(key);
|
|
23
|
+
if (cached) {
|
|
24
|
+
cached.deployCount = deployCount;
|
|
25
|
+
return cached.registry;
|
|
26
|
+
}
|
|
27
|
+
const registry = new promClient.Registry();
|
|
28
|
+
const entry = { registry, deployCount };
|
|
29
|
+
const labels = hostLabel ? { host: hostName() } : undefined;
|
|
30
|
+
promClient.collectDefaultMetrics({ register: registry, prefix, ...(labels ? { labels } : {}) });
|
|
31
|
+
new promClient.Counter({
|
|
32
|
+
name: `${prefix}flows_deploy_total`,
|
|
33
|
+
help: 'Node-RED flow starts (startup and every deploy) since the process started.',
|
|
34
|
+
labelNames: hostLabel ? ['host'] : [],
|
|
35
|
+
registers: [registry],
|
|
36
|
+
collect() {
|
|
37
|
+
this.reset();
|
|
38
|
+
const count = entry.deployCount();
|
|
39
|
+
if (hostLabel) this.inc({ host: hostName() }, count);
|
|
40
|
+
else if (count > 0) this.inc(count);
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
cache.set(key, entry);
|
|
44
|
+
return registry;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function clearCache() {
|
|
48
|
+
cache.clear();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
module.exports = { defaultMetricsRegistry, hostName, clearCache };
|
package/lib/palette.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const kit = require('@redkern/node-red-kit');
|
|
4
|
+
const promClient = require('@prometheus-io/client');
|
|
5
|
+
const { createMetricRegistry } = require('./registry.js');
|
|
6
|
+
const { createReceiver } = require('./receiver.js');
|
|
7
|
+
const { defaultMetricsRegistry } = require('./default-metrics.js');
|
|
8
|
+
const { createWarnOnce } = require('./warn-once.js');
|
|
9
|
+
|
|
10
|
+
// One palette context per Node-RED runtime, kept in the module closure (PRM-REG-1, PRM-EXP-3).
|
|
11
|
+
|
|
12
|
+
const DEFAULT_PORT = 9550;
|
|
13
|
+
const SETTINGS_TYPE = 'redkern-prom-exporter';
|
|
14
|
+
const CONTENT_TYPE = 'text/plain; version=0.0.4; charset=utf-8';
|
|
15
|
+
// Admin routes reject the 0.0.4 media type in kit 1.1.0 (KIT-HTTP facade); Prometheus parses plain
|
|
16
|
+
// text/plain as the 0.0.4 text format, so the httpAdmin mode answers with it (docs/spec.md, Deviations).
|
|
17
|
+
const ADMIN_CONTENT_TYPE = 'text/plain; charset=utf-8';
|
|
18
|
+
|
|
19
|
+
const palettes = new WeakMap();
|
|
20
|
+
|
|
21
|
+
function getPalette(RED) {
|
|
22
|
+
let palette = palettes.get(RED);
|
|
23
|
+
if (palette) return palette;
|
|
24
|
+
palette = createPalette(RED);
|
|
25
|
+
palettes.set(RED, palette);
|
|
26
|
+
return palette;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function createPalette(RED) {
|
|
30
|
+
let deployCount = 0;
|
|
31
|
+
let exporter;
|
|
32
|
+
let activeNodes = 0;
|
|
33
|
+
|
|
34
|
+
// PRM-EXP-1, PRM-EXP-4: the dedicated port is the kit internal server (createInternalServer). Its
|
|
35
|
+
// /metrics route has its own token class "metrics" (KIT-HTTP-6). Kit requires a declared route token at
|
|
36
|
+
// init, so the listener is declared only when REDKERN_PROM_METRICS_TOKEN (or the matching setting) is
|
|
37
|
+
// present; without it the palette still works and the admin API mode stays available.
|
|
38
|
+
const tokenConfigured = hasMetricsToken(RED);
|
|
39
|
+
const rk = kit.init(RED, {
|
|
40
|
+
domain: 'prom',
|
|
41
|
+
settingsType: SETTINGS_TYPE,
|
|
42
|
+
secrets: { metrics: { required: false } },
|
|
43
|
+
// Declared so the kit listener may answer with the 0.0.4 media type; this palette never acquires a
|
|
44
|
+
// source lease, it is the receiver (PRM-REG-6).
|
|
45
|
+
metrics: { contentType: CONTENT_TYPE, metrics: render },
|
|
46
|
+
...(tokenConfigured ? {
|
|
47
|
+
internalServer: {
|
|
48
|
+
port: DEFAULT_PORT,
|
|
49
|
+
routes: [{
|
|
50
|
+
method: 'GET',
|
|
51
|
+
path: '/metrics',
|
|
52
|
+
auth: { token: 'metrics' },
|
|
53
|
+
handler: async (_request, response) => response.text(await render(), CONTENT_TYPE)
|
|
54
|
+
}]
|
|
55
|
+
}
|
|
56
|
+
} : {})
|
|
57
|
+
});
|
|
58
|
+
const log = rk.plugin({ id: 'palette' }).log;
|
|
59
|
+
const warn = (key, message) => log.warn(message, { key });
|
|
60
|
+
const warnOnce = createWarnOnce((message, meta) => log.warn(message, meta), 1024);
|
|
61
|
+
|
|
62
|
+
const metrics = createMetricRegistry({ promClient, warn });
|
|
63
|
+
const receiver = createReceiver({ RED, warn, warnOnce });
|
|
64
|
+
|
|
65
|
+
const onFlowsStarted = () => {
|
|
66
|
+
deployCount += 1;
|
|
67
|
+
// PRM-REG-3: metrics whose config nodes disappeared in this deploy are removed only now, so a
|
|
68
|
+
// config node that was stopped and started again keeps its series.
|
|
69
|
+
metrics.sweep();
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
function acquire() {
|
|
73
|
+
if (!rk.enabled) return () => {};
|
|
74
|
+
activeNodes += 1;
|
|
75
|
+
if (activeNodes === 1) {
|
|
76
|
+
if (RED.events && typeof RED.events.on === 'function') RED.events.on('flows:started', onFlowsStarted);
|
|
77
|
+
receiver.start();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let active = true;
|
|
81
|
+
return () => {
|
|
82
|
+
if (!active) return;
|
|
83
|
+
active = false;
|
|
84
|
+
activeNodes -= 1;
|
|
85
|
+
if (activeNodes === 0) {
|
|
86
|
+
if (RED.events && typeof RED.events.removeListener === 'function') RED.events.removeListener('flows:started', onFlowsStarted);
|
|
87
|
+
receiver.stop();
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function render() {
|
|
93
|
+
const texts = [];
|
|
94
|
+
const options = exporter?.options;
|
|
95
|
+
if (options?.defaultMetrics) {
|
|
96
|
+
const registry = defaultMetricsRegistry({
|
|
97
|
+
promClient,
|
|
98
|
+
prefix: options.prefix,
|
|
99
|
+
hostLabel: options.hostLabel,
|
|
100
|
+
deployCount: () => deployCount
|
|
101
|
+
});
|
|
102
|
+
texts.push(await registry.metrics());
|
|
103
|
+
}
|
|
104
|
+
texts.push(await metrics.metrics());
|
|
105
|
+
if (options?.includeGlobalRegistry) texts.push(await promClient.register.metrics());
|
|
106
|
+
return receiver.render(texts);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Registered on first use, once per palette (PRM-EXP-3), so instances without an admin-mode exporter do not
|
|
110
|
+
// log the kit's missing-adminAuth warning.
|
|
111
|
+
let adminRoute;
|
|
112
|
+
const getAdminRoute = () => adminRoute || (adminRoute = rk.createRouteRegistry({
|
|
113
|
+
method: 'GET',
|
|
114
|
+
path: '/metrics',
|
|
115
|
+
permission: rk.names.permRead,
|
|
116
|
+
// Without an admin-mode exporter in the registry, kit answers 503 NO_ACTIVE_ENTRIES before this runs.
|
|
117
|
+
handler: async (_request, response) => {
|
|
118
|
+
response.text(await render(), ADMIN_CONTENT_TYPE);
|
|
119
|
+
}
|
|
120
|
+
}));
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
RED,
|
|
124
|
+
rk,
|
|
125
|
+
log,
|
|
126
|
+
warn,
|
|
127
|
+
warnOnce,
|
|
128
|
+
metrics,
|
|
129
|
+
receiver,
|
|
130
|
+
tokenConfigured,
|
|
131
|
+
acquire,
|
|
132
|
+
get adminRoute() { return getAdminRoute(); },
|
|
133
|
+
render,
|
|
134
|
+
contentType: CONTENT_TYPE,
|
|
135
|
+
/** PRM-EXP-5: one exporter per Node-RED instance. */
|
|
136
|
+
claimExporter(id, options) {
|
|
137
|
+
if (exporter && exporter.id !== id) return false;
|
|
138
|
+
exporter = { id, options };
|
|
139
|
+
return true;
|
|
140
|
+
},
|
|
141
|
+
releaseExporter(id) {
|
|
142
|
+
if (exporter?.id === id) exporter = undefined;
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function hasMetricsToken(RED) {
|
|
148
|
+
const env = kit.readEnv('REDKERN_PROM_METRICS_TOKEN');
|
|
149
|
+
if (typeof env === 'string' && env.trim() !== '') return true;
|
|
150
|
+
const settings = kit.readSettings(RED, SETTINGS_TYPE, { metricsToken: { type: 'str' } });
|
|
151
|
+
return typeof settings.metricsToken === 'string' && settings.metricsToken.trim() !== '';
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
module.exports = { getPalette, DEFAULT_PORT, SETTINGS_TYPE, CONTENT_TYPE, ADMIN_CONTENT_TYPE };
|
package/lib/receiver.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { MIMEType } = require('node:util');
|
|
4
|
+
|
|
5
|
+
// PRM-REG-6: receiver for the kit metrics-source protocol (KIT-MET-1..4).
|
|
6
|
+
|
|
7
|
+
const REGISTER = 'redkern:metrics:register';
|
|
8
|
+
const UNREGISTER = 'redkern:metrics:unregister';
|
|
9
|
+
const DISCOVER = 'redkern:metrics:discover';
|
|
10
|
+
const SOURCE_TIMEOUT_MS = 5000;
|
|
11
|
+
const FAMILY_SUFFIXES = ['_bucket', '_sum', '_count', '_total', '_created', '_info'];
|
|
12
|
+
|
|
13
|
+
function isPrometheusText004(contentType) {
|
|
14
|
+
if (typeof contentType !== 'string') return false;
|
|
15
|
+
try {
|
|
16
|
+
const type = new MIMEType(contentType);
|
|
17
|
+
return type.essence.toLowerCase() === 'text/plain' && type.params.get('version') === '0.0.4';
|
|
18
|
+
} catch {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Splits Prometheus text 0.0.4 into metric families, keeping HELP/TYPE lines with their samples.
|
|
25
|
+
* @param {string} text
|
|
26
|
+
* @returns {Array<{ name: string, lines: string[] }>}
|
|
27
|
+
*/
|
|
28
|
+
function splitFamilies(text) {
|
|
29
|
+
const families = [];
|
|
30
|
+
let current;
|
|
31
|
+
const open = (name) => {
|
|
32
|
+
current = { name, lines: [] };
|
|
33
|
+
families.push(current);
|
|
34
|
+
};
|
|
35
|
+
for (const line of String(text).split('\n')) {
|
|
36
|
+
if (line.trim() === '') continue;
|
|
37
|
+
const meta = line.match(/^#\s+(HELP|TYPE)\s+([a-zA-Z_:][a-zA-Z0-9_:]*)/);
|
|
38
|
+
if (meta) {
|
|
39
|
+
if (!current || current.name !== meta[2]) open(meta[2]);
|
|
40
|
+
current.lines.push(line);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (line.startsWith('#')) {
|
|
44
|
+
if (current) current.lines.push(line);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
const sample = line.match(/^([a-zA-Z_:][a-zA-Z0-9_:]*)/);
|
|
48
|
+
if (!sample) continue;
|
|
49
|
+
const name = sample[1];
|
|
50
|
+
if (!current || !belongsTo(name, current.name)) open(name);
|
|
51
|
+
current.lines.push(line);
|
|
52
|
+
}
|
|
53
|
+
return families;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function belongsTo(sampleName, familyName) {
|
|
57
|
+
if (sampleName === familyName) return true;
|
|
58
|
+
return FAMILY_SUFFIXES.some((suffix) => sampleName === `${familyName}${suffix}`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* @param {{ RED: any, warn: (key: string, message: string) => void, warnOnce: (key: string, message: string) => void }} options
|
|
63
|
+
*/
|
|
64
|
+
function createReceiver({ RED, warn, warnOnce }) {
|
|
65
|
+
const sources = new Map();
|
|
66
|
+
let started = false;
|
|
67
|
+
|
|
68
|
+
function onRegister(descriptor) {
|
|
69
|
+
if (!descriptor || typeof descriptor !== 'object') return;
|
|
70
|
+
if (descriptor.version !== 1) {
|
|
71
|
+
warn('SOURCE_VERSION', `Ignored metrics source with unknown version ${String(descriptor.version)}`);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (typeof descriptor.sourceId !== 'string' || typeof descriptor.metrics !== 'function') {
|
|
75
|
+
warn('SOURCE_INVALID', 'Ignored malformed metrics source');
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (!isPrometheusText004(descriptor.contentType)) {
|
|
79
|
+
warnOnce(`SOURCE_CONTENT_TYPE:${descriptor.sourceId}`, `Ignored metrics source "${String(descriptor.domain)}": content type must be Prometheus text 0.0.4`);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
// Re-announcements after discover keep the original order (PRM-REG-6: sources win in declaration order).
|
|
83
|
+
sources.set(descriptor.sourceId, { domain: String(descriptor.domain), metrics: descriptor.metrics });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function onUnregister(event) {
|
|
87
|
+
if (event && typeof event.sourceId === 'string') sources.delete(event.sourceId);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return {
|
|
91
|
+
start() {
|
|
92
|
+
if (started) return;
|
|
93
|
+
started = true;
|
|
94
|
+
RED.events.on(REGISTER, onRegister);
|
|
95
|
+
RED.events.on(UNREGISTER, onUnregister);
|
|
96
|
+
RED.events.emit(DISCOVER, { version: 1 });
|
|
97
|
+
},
|
|
98
|
+
stop() {
|
|
99
|
+
if (!started) return;
|
|
100
|
+
started = false;
|
|
101
|
+
RED.events.removeListener(REGISTER, onRegister);
|
|
102
|
+
RED.events.removeListener(UNREGISTER, onUnregister);
|
|
103
|
+
sources.clear();
|
|
104
|
+
},
|
|
105
|
+
get size() { return sources.size; },
|
|
106
|
+
domains() { return [...sources.values()].map((source) => source.domain); },
|
|
107
|
+
/**
|
|
108
|
+
* Appends every source's text after the palette's own output, skipping metric families that are
|
|
109
|
+
* already present. Text is concatenated, not merged with Registry.merge, so palettes may use
|
|
110
|
+
* different Prometheus client versions.
|
|
111
|
+
* @param {string[]} ownTexts texts that always win, in order
|
|
112
|
+
*/
|
|
113
|
+
async render(ownTexts) {
|
|
114
|
+
const seen = new Set();
|
|
115
|
+
const parts = [];
|
|
116
|
+
const append = (text, origin) => {
|
|
117
|
+
const kept = [];
|
|
118
|
+
for (const family of splitFamilies(text)) {
|
|
119
|
+
if (seen.has(family.name)) {
|
|
120
|
+
warnOnce(`DUPLICATE:${origin}:${family.name}`, `Metric "${family.name}" from ${origin} duplicates an earlier source and was skipped`);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
seen.add(family.name);
|
|
124
|
+
kept.push(...family.lines);
|
|
125
|
+
}
|
|
126
|
+
if (kept.length) parts.push(`${kept.join('\n')}\n`);
|
|
127
|
+
};
|
|
128
|
+
// Fast path for this palette's own client output: every family has a TYPE line, so the names are
|
|
129
|
+
// read without splitting the text, which is the largest part of a scrape. Split only on a collision.
|
|
130
|
+
for (const text of ownTexts) {
|
|
131
|
+
const names = [...text.matchAll(/^# TYPE ([a-zA-Z_:][a-zA-Z0-9_:]*) /gm)].map((match) => match[1]);
|
|
132
|
+
if (names.some((name) => seen.has(name))) {
|
|
133
|
+
append(text, 'prometheus palette');
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
for (const name of names) seen.add(name);
|
|
137
|
+
if (text.length) parts.push(text.endsWith('\n') ? text : `${text}\n`);
|
|
138
|
+
}
|
|
139
|
+
for (const [sourceId, source] of sources) {
|
|
140
|
+
let text;
|
|
141
|
+
try {
|
|
142
|
+
text = await withTimeout(Promise.resolve().then(() => source.metrics()), SOURCE_TIMEOUT_MS);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
warnOnce(`SOURCE_FAILED:${sourceId}`, `Metrics source "${source.domain}" failed: ${error?.message || 'unknown error'}`);
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (typeof text !== 'string') {
|
|
148
|
+
warnOnce(`SOURCE_NOT_TEXT:${sourceId}`, `Metrics source "${source.domain}" returned a non-text value`);
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
append(text, `source "${source.domain}"`);
|
|
152
|
+
}
|
|
153
|
+
return parts.join('');
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function withTimeout(promise, ms) {
|
|
159
|
+
let timer;
|
|
160
|
+
return Promise.race([
|
|
161
|
+
promise,
|
|
162
|
+
new Promise((_, reject) => {
|
|
163
|
+
timer = setTimeout(() => reject(Object.assign(new Error('metrics source timed out'), { code: 'SOURCE_TIMEOUT' })), ms);
|
|
164
|
+
timer.unref?.();
|
|
165
|
+
})
|
|
166
|
+
]).finally(() => clearTimeout(timer));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
module.exports = { createReceiver, splitFamilies, isPrometheusText004, REGISTER, UNREGISTER, DISCOVER };
|