-
Notifications
You must be signed in to change notification settings - Fork 0
/
master.js
92 lines (78 loc) · 2.2 KB
/
master.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
// Fabrica bootloader
// Load server through command line.
'use strict';
// if (process.env.NODE_ENV === 'production') {
// require('newrelic');
// }
require('coffee-script/register');
/**
* Absolute imports.
* See https://gist.github.com/branneman/8048520#6-the-hack
*/
process.env.NODE_PATH = '.';
require('module').Module._initPaths();
/**
* Environment variables.
* Yes, please.
*/
var nconf = require('app/config/nconf');
/**
* Logging. Bunyan.
* Set global logger.
*/
var logger = require('app/config/bunyan')();
global.logger = logger;
logger.level(nconf.get('BUNYAN_LVL') || 'debug');
/**
* Set mongoose here, not in server script.
*/
var mongoose = require('app/config/mongoose')(logger);
/**
* Upstart servers.
* Use clusters unless NO_CLUSTER env variable is set.
*/
function startServerWhenMongooseConnects(server) {
function startServer() {
server.start();
}
if (mongoose.connection.readyState === 2) {
// state is connecting → wait
mongoose.connection.once('connected', startServer);
} else if (mongoose.connection.readyState === 1) {
startServer();
} else {
throw new Error("Unexpected mongo readyState of "+
mongoose.connection.readyState);
}
}
// Using clusters in debug mode leads to "Failed to open socket on port 5858,
// waiting 1000 ms before retrying"
if (process.env.NODE_ENV === 'production' && !process.env.NO_CLUSTER) {
// if (!process.env.NO_CLUSTER) {
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
process.env.__CLUSTERING = true;
if (cluster.isMaster) {
// If clustering and CONSUME_MAIN is set, consumer must be called here.
if (nconf.get('CONSUME_MAIN')) {
// require('./app/consumer.js');
}
for (var i=0; i<numCPUs; ++i) {
cluster.fork();
}
cluster.on('disconnect', function (worker, code, signal) {
console.warn('Worker pid='+worker.process.pid+' died.\nForking...');
cluster.fork();
});
} else {
var server = require('app/server.js');
startServerWhenMongooseConnects(server);
}
} else {
if (nconf.get('CONSUME_MAIN')) {
// logger.info('Calling consumer from web process.');
// require('./app/consumer.js');
}
var server = require('app/server.js');
startServerWhenMongooseConnects(server);
}