-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
214 lines (194 loc) · 5.34 KB
/
app.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/**
* Index file of API, program begins here
* @module app
*/
'use strict'
require('loadenv')()
if (process.env.NEW_RELIC_LICENSE_KEY) {
require('newrelic')
}
const cluster = require('cluster')
const createCount = require('callback-count')
const ApiServer = require('server')
const envIs = require('101/env-is')
const error = require('error')
const keyGen = require('key-generator')
const logger = require('middlewares/logger')(__filename)
const mongooseControl = require('models/mongo/mongoose-control')
const monitor = require('monitor-dog')
const noop = require('101/noop')
const redisClient = require('models/redis')
const redisPubSub = require('models/redis/pubsub')
const log = logger.log
// express server, handles web HTTP requests
const apiServer = new ApiServer()
/**
* @class
*/
function Api () {
// bind `this` so it can be used directly as event handler
this._handleStopSignal = this._handleStopSignal.bind(this)
}
/**
* - Listen to incoming HTTP requests
* - Initialize datadog system monitoring
* - Set self as "active api"
* - Listen to all events (docker events from docks)
* - Generate GitHub ssh keys
* @param {Function} cb
*/
Api.prototype.start = function (cb) {
cb = cb || error.logIfErr
var self = this
var count = createCount(callback)
log.trace('start')
// start github ssh key generator
keyGen.start(count.inc().next)
// start sending socket count
monitor.startSocketsMonitor()
// connect to mongoose
mongooseControl.start(count.inc().next)
// express server start
apiServer.start(count.inc().next)
// all started callback
function callback (err) {
if (err) {
log.error({
err: err
}, 'fatal error: API failed to start')
error.log(err)
if (cb) {
cb(err)
} else {
process.exit(1)
}
return
}
log.trace('API started')
console.log('API started')
self.listenToSignals()
cb()
}
}
/**
* Stop listening to requests and drain all current requests gracefully
* @param {Function} cb
*/
Api.prototype.stop = function (cb) {
log.trace('stop')
cb = cb || error.logIfErr
var self = this
var count = createCount(closeDbConnections)
// stop github ssh key generator
keyGen.stop(count.inc().next)
// stop sending socket count
monitor.stopSocketsMonitor()
// express server
apiServer.stop(count.inc().next)
function closeDbConnections (err) {
if (!err) {
// so far the stop was successful
// finally disconnect from he databases
var dbCount = createCount(cb)
// FIXME: redis clients cannot be reconnected once they are quit this breaks the tests.
if (!envIs('test')) {
// disconnect from redis
redisClient.quit()
redisClient.on('end', dbCount.inc().next)
redisPubSub.quit()
redisPubSub.on('end', dbCount.inc().inc().next) // calls twice
}
var next = dbCount.inc().next
mongooseControl.stop(function (err) {
if (err) { return next(err) }
self.stopListeningToSignals()
next()
})
return
}
cb(err)
}
}
/**
* listen to process SIGINT
*/
Api.prototype.listenToSignals = function () {
process.on('SIGINT', this._handleStopSignal)
process.on('SIGTERM', this._handleStopSignal)
}
/**
* stop listening to process SIGINT
*/
Api.prototype.stopListeningToSignals = function () {
process.removeListener('SIGINT', this._handleStopSignal)
process.removeListener('SIGTERM', this._handleStopSignal)
}
/**
* SIGINT event handler
*/
Api.prototype._handleStopSignal = function () {
log.info('STOP SIGNAL: recieved')
var self = this
process.removeAllListeners('uncaughtException')
this.stop(function (err) {
if (err) {
log.error({
err: err
}, 'STOP SIGNAL: stop failed')
return
}
log.info('STOP SIGNAL: stop succeeded, process should exit gracefully')
if (cluster.isWorker) {
// workers need to be exited manually
self._waitForActiveHandlesAndExit()
} else {
process.exit()
}
})
}
/**
* wait for active handles to reach 2 or less
*/
Api.prototype._waitForActiveHandlesAndExit = function (cb) {
cb = cb || noop
var poller = setInterval(function () {
var handles = process._getActiveHandles()
log.info({ count: handles.length, items: handles }, 'Active handles')
if (process._getActiveHandles().length <= 2) {
// there are 2 active handles
// 1 is the interval and 1 is the clustered process
clearInterval(poller)
log.info('Worker process exited gracefully')
process.exit() // clean exit
}
}, 1000)
}
/**
* Returns PrimusSocket constructor function that can be used for
* primus Client instantiation.
* @return {Function} - PrimusSocket class
*/
Api.prototype.getPrimusSocket = function () {
return apiServer.socketServer.primus.Socket
}
// we are exposing here apiServer as a singletond
var api = module.exports = new Api()
if (!module.parent) { // npm start
api.start()
}
// should not occur in practice, using domains to catch errors
process.on('uncaughtException', function (err) {
log.fatal({
err: err
}, 'stopping app due too uncaughtException')
// hack to force loggly to release buffer
for (var i = 0; i < process.env.BUNYAN_BATCH_LOG_COUNT; i++) {
log.info('---')
}
error.log(err)
var oldApi = api
oldApi.stop(function () {
log.trace('API stopped')
process.exit(1)
})
})