This repository has been archived by the owner on Aug 11, 2021. It is now read-only.
/
index.js
88 lines (77 loc) · 2.05 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
'use strict'
const http = require('http')
const assert = require('assert')
const Promise = require('bluebird')
const exec = require('child_process').exec
const logger = require('bole')('monitor')
let contributor = null
module.exports = function startMonitor (port, callback) {
const monitor = http.createServer()
let commitHash = ''
let listening = () => {}
let ready = new Promise(resolve => {
listening = resolve
})
monitor.on('request', (req, res) => {
if (req.url !== '/_monitor/ping') {
return
}
req.handled = true
res.end(process.env.PING_RESPONSE || 'pong')
})
monitor.on('request', (req, res) => {
if (req.url !== '/_monitor/status') {
return
}
req.handled = true
const getExtra = (
contributor
? Promise.try(() => contributor())
: Promise.resolve({})
)
const getStatus = getExtra.then(obj => {
return Object.assign({
pid: process.pid,
uptime: process.uptime(),
rss: process.memoryUsage(),
cmdline: process.argv,
git: commitHash
}, obj)
})
return getStatus.then(status => {
res.writeHead(200, {'content-type': 'application/json'})
res.end(JSON.stringify(status))
})
})
monitor.on('request', (req, res) => {
logger.info(req)
if (req.handled) {
return
}
res.writeHead(404)
res.end('')
})
function gitHash () {
return new Promise(resolve => {
exec('git rev-parse --short HEAD', function (err, stdout, stderr) {
resolve((!err && stdout) ? stdout.trim() : undefined)
})
})
}
Promise.resolve(process.env.BUILD_HASH)
.then(envHash => envHash || gitHash())
.then(hash => {
commitHash = hash
monitor.listen(port, () => {
listening()
callback()
})
})
return Object.assign(monitor, {
contribute: (_contributor) => {
assert(typeof _contributor === 'function', 'contributor must be a function')
contributor = _contributor
},
stop: () => ready.then(() => new Promise(resolve => monitor.close(resolve)))
})
}