This repository has been archived by the owner on Aug 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 232
/
index.js
292 lines (239 loc) · 7.51 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
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
'use strict';
let dashboard;
// log up as high as possible, even though it's kind of ugly, because
// otherwise you get lots of artifacts in your dashboard (if enabled)
let oldlog = global.console.log;
let oldinfo = global.console.info;
let olderror = global.console.error;
let oldwarn = global.console.warn;
// If we created a server dashboard (using --dashboard), log to its log
// instead of using console.log, to stdout. Override it globally (gasp)
// here.
global.console.log = global.console.info = function() {
if (dashboard) {
dashboard.log.apply(dashboard, arguments);
} else {
oldlog.apply(this, arguments);
}
}
global.console.error = function() {
if (dashboard) {
dashboard.error.apply(dashboard, arguments);
} else {
olderror.apply(this, arguments);
}
}
global.console.warn = function() {
if (dashboard) {
dashboard.warn.apply(dashboard, arguments);
} else {
olderror.apply(this, arguments);
}
}
// Register that we're using es6, so babel can compile import statements.
// The `ignore` set to false allows babel to compile npm modules, and the `only`
// forces it to only compile files with a `.es6.js` or `.jsx` extension.
require('babel-register')({
ignore: false,
only: /.+(?:(?:\.es6\.js)|(?:.jsx))$/,
extensions: ['.js', '.es6.js', '.jsx' ],
sourceMap: true,
presets: [
'es2015',
'react',
],
plugins: [
'transform-object-rest-spread',
'transform-async-to-generator',
'transform-class-properties',
'syntax-trailing-function-commas',
'transform-react-constant-elements',
'transform-react-inline-elements',
],
});
const throttle = require('lodash/function/throttle');
const numCPUs = process.env.PROCESSES || require('os').cpus().length;
// App config
const config = require('./src/server/config').default(numCPUs);
const errorLog = require('./src/lib/errorLog').default;
function parseStack(err) {
if (err.stack) {
const location = err.stack.split('\n')[1].split(':');
return { url: location[0], line: location[1]};
}
return {};
}
// If we miss catching an exception, format and log it before exiting the
// process.
process.on('uncaughtException', function (err) {
console.log('Caught exception', err, err.stack);
const parsed = parseStack(err);
const line = parsed.line;
const url = parsed.url;
if (config) {
errorLog({
error: err,
userAgent: 'SERVER',
message: err.message,
line: line,
url: url,
}, {
hivemind: config.statsURL,
});
}
process.exit();
});
process.on('unhandledRejection', function(reason) {
const parsed = parseStack(reason);
const line = parsed.line;
const url = parsed.url;
const message = typeof reason === 'object' ? JSON.stringify(reason) : reason;
if (config) {
errorLog({
url,
line,
error: 'Unhandled Promise rejection',
userAgent: 'SERVER',
message: 'Unhandled Promise rejection: ' + message,
}, {
hivemind: config.statsURL,
});
}
});
// Check node version
require('./version');
// Require in the express server.
const Server = require('./src/server').default;
let Console;
const cluster = require('cluster');
let failedProcesses = 0;
function start(config) {
let server = new Server(config);
server.start();
return server;
}
if (cluster.isMaster) {
// Use `silent` so that child processes write to the master process's stdout
// instead of writing directly to stdout. This way, if we fired up a dashboard,
// we can write to the dashboard's logger instead.
cluster.setupMaster({
silent: true
});
const StatsdClient = require('statsd-client');
const statsd = new StatsdClient(config.statsd || {
_socket: { send: ()=>{}, close: ()=>{} }
});
let processes = [];
// If we used `node index.js --console`, instantiate a dashboard.
if (process.argv[2] && process.argv[2] === '--console') {
Console = require('./src/server/console').default;
dashboard = new Console(config);
dashboard.start();
}
// Write to either dashboard or stdout.
function stdout (data) {
if (dashboard) {
dashboard.log(data);
} else {
process.stdout.write(data);
}
}
// Write to either dashboard or stdout.
function stderr (data) {
if (dashboard) {
dashboard.error(data);
} else {
process.stderr.write(data);
}
}
for (let i = 0; i < numCPUs; i++) {
let fork = cluster.fork();
// Set the stdout to the above functions so that we write to the right
// place.
fork.process.stdout.on('data', stdout);
fork.process.stderr.on('data', stderr);
processes.push(fork.process.pid);
}
// Send the process info to the dashboard so it can monitor CPU / Memory usage.
if (dashboard) {
dashboard.setProcesses(processes);
}
console.log(`listening on ${config.port} on ${config.processes} processes (pids: master: ${process.pid}, workers: ${processes.join(',')}).`);
if (config.keys.length === 1 && config.keys[0] === 'lambeosaurus') {
console.warn('WARNING: Using default security keys.');
}
let activeRequests = {};
let sendRequests = throttle(function(requests) {
if (requests) {
statsd.increment('activeRequests', requests);
}
}, 10000);
// To communicate between worker threads and the master thread, specifically
// for the dashboard, we have to send messages; so we bind to `Server` events
// below, and fire them through the process to here. The dashboard, if running,
// can then do things with the data sent in.
cluster.on('message', function(message) {
if (message.type) {
switch (message.type) {
case 'log:request':
if (dashboard) {
return dashboard.logRequest(message.args);
}
console.log(message.args[0], message.args[1], message.args[2]);
break;
case 'log:activeRequests':
if (!activeRequests[message.pid]) {
activeRequests[message.pid] = [];
}
activeRequests[message.pid].push(message.requests);
if (activeRequests[message.pid].length > 40) {
activeRequests[message.pid] = activeRequests[message.pid].slice(-40);
}
let latestTotal = 0;
for (let a in activeRequests) {
latestTotal += activeRequests[a][activeRequests[a].length - 1];
}
sendRequests(latestTotal);
if (dashboard) {
dashboard.updateActiveRequests(activeRequests);
}
break;
}
}
});
// If a worker dies, log it!
cluster.on('exit', function(worker, code, signal) {
if (failedProcesses < 20) {
console.log('Worker ' + worker.process.pid + ' died, restarting.');
let fork = cluster.fork();
fork.process.stdout.on('data', stdout);
fork.process.stderr.on('data', stderr);
failedProcesses++;
if (dashboard) {
dashboard.failProcess(worker.process.pid);
dashboard.addProcess(fork.process.pid);
}
} else {
console.log('Workers died too many times, exiting.');
process.exit();
}
});
} else {
// If we're not a master process, create a server that can listen for http
// requests. Also bind some events to worker messages that can then be
// logged.
let server = start(config);
server.app.on('log:request', function() {
process.send({
type: 'log:request',
args: Array.prototype.slice.call(arguments)
});
});
server.app.on('log:activeRequests', function(requests) {
process.send({
type: 'log:activeRequests',
requests: requests,
pid: process.pid,
});
});
}