-
Notifications
You must be signed in to change notification settings - Fork 9
/
common.js
78 lines (60 loc) · 2.05 KB
/
common.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import axios from 'axios';
const METRICS_TAG = process.env.METRICS_TAG;
// Metrics helper functions
function getMetricPayload(name, labels, value) {
const labelsStrs = [];
for (const [k, v] of Object.entries(labels)) {
if (!v) {
continue;
}
labelsStrs.push(`${k}="${v}"`);
}
const allLabelsStr = labelsStrs.join(",");
return `${name}{${allLabelsStr}} ${value}`;
}
function getMetricsConfig() {
const metricsConfigs = [];
// URL and Token
const firstUrl = process.env.METRICS_URL;
const firstToken = process.env.METRICS_AUTH_TOKEN;
if (firstUrl && firstToken) {
metricsConfigs.push({ url: firstUrl, token: firstToken });
}
// Additional URLs and Tokens with index (_2, _3, etc.)
let index = 2;
while (true) {
const url = process.env[`METRICS_URL_${index}`];
const token = process.env[`METRICS_AUTH_TOKEN_${index}`];
if (!url || !token) {
break; // Stop if either the URL or token is missing for the current index
}
metricsConfigs.push({ url, token });
index++;
}
return metricsConfigs;
}
async function pushMetrics(payloads) {
const metricsConfigs = getMetricsConfig();
if (metricsConfigs.length === 0) {
console.log("No valid METRICS_URL and METRICS_AUTH_TOKEN pairs! Skipping dump...");
return;
}
for (const { url, token } of metricsConfigs) {
const headers = {
"Authorization": `Bearer ${token}`,
"apikey": `${token}`
};
const fullUrl = `${url}/api/v1/import/prometheus/metrics/job/e2elatency-${METRICS_TAG}/`;
const data = payloads + '\n';
try {
await axios.post(fullUrl, data, { headers });
} catch (error) {
console.error(`Error pushing metrics to ${fullUrl}: `, error.message);
}
}
return 200;
}
async function sleepAsync(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
export { getMetricPayload, pushMetrics, sleepAsync };