-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
influx-metrics.js
81 lines (74 loc) · 2.1 KB
/
influx-metrics.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
import os from 'os'
import got from 'got'
import generateInstanceId from './instance-id-generator.js'
import { promClientJsonToInfluxV2 } from './metrics/format-converters.js'
import log from './log.js'
export default class InfluxMetrics {
constructor(metricInstance, config) {
this._metricInstance = metricInstance
this._config = config
this._instanceId = this.getInstanceId()
}
async sendMetrics() {
const request = {
url: this._config.url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: await this.metrics(),
timeout: { request: this._config.timeoutMillseconds },
username: this._config.username,
password: this._config.password,
throwHttpErrors: false,
}
let response
try {
response = await got.post(request)
} catch (error) {
log.error(
new Error(`Cannot push metrics. Cause: ${error.name}: ${error.message}`)
)
}
if (response && response.statusCode >= 300) {
log.error(
new Error(
`Cannot push metrics. ${request.url} responded with status code ${response.statusCode}`
)
)
}
}
startPushingMetrics() {
this._intervalId = setInterval(
() => this.sendMetrics(),
this._config.intervalSeconds * 1000
)
}
async metrics() {
return promClientJsonToInfluxV2(await this._metricInstance.metrics(), {
env: this._config.envLabel,
application: 'shields',
instance: this._instanceId,
})
}
getInstanceId() {
const {
hostnameAliases = {},
instanceIdFrom,
instanceIdEnvVarName,
} = this._config
let instance
if (instanceIdFrom === 'env-var') {
instance = process.env[instanceIdEnvVarName]
} else if (instanceIdFrom === 'hostname') {
const hostname = os.hostname()
instance = hostnameAliases[hostname] || hostname
} else if (instanceIdFrom === 'random') {
instance = generateInstanceId()
}
return instance
}
stopPushingMetrics() {
if (this._intervalId) {
clearInterval(this._intervalId)
this._intervalId = undefined
}
}
}