-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
97 lines (82 loc) · 2.56 KB
/
index.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import express from 'express';
import cors from 'cors';
import * as client from 'prom-client';
import moment from 'moment';
import * as calculate from './models/application-calculate.js';
import { BUCKET } from './utils/influxdb-util.js';
import { fetchData } from './models/fetch.js';
const app = express();
app.use(express.json());
app.use(cors());
const register = new client.Registry();
const { collectDefaultMetrics } = client;
collectDefaultMetrics({
app: 'node-exporter-2.0',
timeout: 10000,
gcDurationBuckets: [1, 2, 5, 7, 9],
register,
});
const httpTotalRequest = new client.Gauge({
name: 'Http_Total_Requests',
help: 'http total request',
});
const guageRequestPerSecond = new client.Gauge({
name: 'Request_Per_Second',
help: 'Request per second',
labelNames: ['time'],
});
const guageResponseTime = new client.Gauge({
name: 'Max_Response_Time',
help: 'ms',
labelNames: ['api'],
});
register.registerMetric(httpTotalRequest);
register.registerMetric(guageResponseTime);
register.registerMetric(guageRequestPerSecond);
async function setMetrics() {
try {
const totalRequest = await calculate.getTotalRequest();
httpTotalRequest.set(totalRequest);
const apiResponseTimes = await calculate.getResponseTime();
for (const api in apiResponseTimes) {
const data = apiResponseTimes[api];
if (data.name !== undefined) {
guageResponseTime.set({ api: data.name }, data.max);
}
}
const fluxQuery = `from(bucket: "${BUCKET}")
|> range(start: -1d)
|> filter(fn: (r) => r.item == "request_per_second")
|> last()
`;
const requestsPerSecond = await calculate.getRequestPerSecond();
const lastData = await fetchData(fluxQuery);
let lastTime;
let unixLastTime;
if (lastData.length !== 0) {
lastTime = lastData[0]._time;
unixLastTime = moment(lastTime, 'YYYY-MM-DDTHH:mm:ssZ').unix();
}
for (const second in requestsPerSecond) {
const count = requestsPerSecond[second];
// 和db最後一筆比對
if (unixLastTime !== undefined && second <= unixLastTime) continue;
guageRequestPerSecond.set({ time: second }, count);
}
} catch (error) {
console.error('Error from nginx exporter', error.message);
}
}
app.get('/metrics', async (req, res) => {
try {
await setMetrics();
res.set('Content-Type', register.contentType);
res.send(await register.metrics());
} catch (error) {
console.error(error);
res.status(500).send('Error setting up metrics');
}
});
app.listen(9101, () => {
console.log('The port in openning in 9101');
});