-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
72 lines (61 loc) · 2.12 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
const app = require('express')()
const moment = require('moment')
const metrics = require('graphite')
.createClient(`plaintext://${process.env.METRIC_HOST}:${process.env.METRIC_PORT}/`)
const GracefulShutdownManager = require('@moebius/http-graceful-shutdown').GracefulShutdownManager;
const redis = require("redis")
.createClient({
"url": process.env.redis_uri,
"password": process.env.redis_password,
"retry_strategy": () => 1000
});
const port = process.env.SERVICE_PORT
const instanceTraceId = traceId();
app.get('/counter', (req, res) => {
redis.incr('counter', (err, counter) => {
log(`Counting: ${counter}`, req.headers["x-trace-id"]);
writeMetric(counter);
setTimeout( ()=> res.send({counter}), 5000);
});
});
var ready = false;
redis.on('ready', () => {
log('Redis is ready');
ready = true;
});
redis.on('end', () => {
log('Redis disconnected');
ready = false;
});
app.get('/health/ready', (req, res) => {
log(`Checking readiness: ${ready}`);
res.status(ready ? 200 : 503);
res.send();
});
app.get('/health/live', (req, res) => {
log('Checking liveness');
res.send()
});
const server = app.listen(port, () => log(`Listening on port ${port}`));
const shutdownManager = new GracefulShutdownManager(server);
process.on('SIGTERM', () => {
log("Shutdown requested");
ready = false;
setTimeout(() => shutdownManager.terminate(() => log('Server gracefully terminated')), 10000);
});
function log(message, traceId) {
traceId = traceId || instanceTraceId;
Object.assign(this, process.env)
var timestamp = moment().format("YYYY-MM-DD hh:mm:ss,SSS");
console.log(`${timestamp} ${SYSTEM_INSTANCE} contador ${SYSTEM_ENV} ${SERVICE_INSTANCE} INFO ${traceId} ${message}`);
}
function writeMetric(counter) {
Object.assign(this, process.env)
var metric = new Object();
metric[`${SYSTEM_INSTANCE}.contador.${SYSTEM_ENV}.${SERVICE_INSTANCE}.counter.value`] = counter;
metrics.write(metric);
}
function traceId() {
return Math.random().toString(36).substring(2, 8);
}
log(`Process started with PID ${process.pid}`);