-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (70 loc) · 1.65 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
'use strict'
const http = require('http')
const config = require('./lib/config')
const {CONTENT_TYPE, createRegistry} = require('./lib/prom')
const {NAME, VERSION} = require('./lib/constants')
const collector = require('./lib/collector')
const log = require('./lib/log').child('server')
const server = http.createServer((req, res) => {
if (req.url === '/health_check') {
return handleHealthCheck(req, res)
}
if (req.url === '/metrics') {
return handleMetrics(req, res)
}
res.writeHead(404, {
'content-type': 'application/json'
})
res.end(JSON.stringify({
message: 'Not found'
}))
})
function handleHealthCheck(req, res) {
res.writeHead(200, {
'content-type': 'application/json'
})
res.end(JSON.stringify({
name: NAME
, version: VERSION
}))
}
async function handleMetrics(req, res) {
const registry = createRegistry()
try {
await collector.collect(registry)
res.writeHead(200, {
'content-type': CONTENT_TYPE
})
res.end(registry.metrics())
} catch (err) {
log.error(err, {
err
, message: 'failed to collect metrics'
})
res.writeHead(500)
res.end('Unable to fetch metrics')
} finally {
registry.clear()
}
}
server.listen(config.get('port'), () => {
log.info('listen', config.get('port'))
})
server.on('clientError', (err, socket) => {
log.error(err, {
err
, message: 'clientError'
})
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
})
server.on('error', (err) => {
log.error(err, {err})
})
process.once('SIGTERM', () => {
log.warn('signal', 'SIGTERM')
server.close()
})
process.once('SIGINT', () => {
log.warn('signal', 'SIGINT')
server.close()
})