forked from nodester/nodester
-
Notifications
You must be signed in to change notification settings - Fork 0
/
master.js
90 lines (71 loc) · 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
#!/usr/bin/env node
/*
* Nodester OpenSource Node.js hosting service
* http://nodester.com
* http://github.com/nodester
*/
/*jshint node:true, noempty:true, laxcomma:true, laxbreak:false */
"use strict";
var cluster = require('cluster')
, path = require('path')
, cp = require('child_process')
, config = require('./config').opt
, pkg = require('./package')
, spawn = cp.spawn
, clusterConf = config.cluster || {}
, logger = require('bunyan').createLogger(config.log || {name: 'nodester'})
, pro = []
, workers = [];
// Share the app package to the childs
process.pkg = pkg;
process.appName = pkg.name;
process.appVersion = pkg.version;
process.root = __dirname;
// Map Bunyan to console.loh
console.error = logger.error.bind(logger);
console.log = logger.info.bind(logger);
console.warn = logger.warn.bind(logger);
// Get cpu cores
clusterConf.size = require('os').cpus().length;
function messageHandler (msg, id){
// Emit to the whole network
keys().forEach(function(id){
get(id).send(msg);
});
}
function keys (){
return Object.keys(cluster.workers);
}
function get (id){
return cluster.workers[id];
}
console.log('[*]', new Date(), 'Starting');
console.log('[*] Spawing servers on node-' + process.version);
// START ALL THE THINGS
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < clusterConf.size; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.pid + ' died');
keys().forEach(function (id){
if (get(id).pid === worker.pid) delete cluster.workers[id];
cluster.fork();
});
});
keys().forEach(function(id) {
get(id).on('message', messageHandler);
});
} else {
require('./app');
pro.push(+new Date);
}
console.log('[*] Processing %d process', pro.length);
process.on('SIGINT',function(){
for (var i=0; i < workers.length; i++) {
console.log('dieing');
workers[i].destroy();
}
process.exit(1);
});