1 |
|
2 | process.chdir(__dirname);
|
3 |
|
4 |
|
5 | var cluster = require('cluster');
|
6 | require('colors');
|
7 | require('string-format');
|
8 |
|
9 | var settings = require('./config/settings');
|
10 |
|
11 | var createMaster = function(cluster) {
|
12 | console.log('Starting directory:', process.cwd());
|
13 | console.log('NodeJS-%s-%s-%s', process.version, process.platform, process.arch);
|
14 |
|
15 |
|
16 | for (var i = 0; i < settings.cluster.maxWorkers; ++i) {
|
17 | cluster.fork();
|
18 | }
|
19 |
|
20 |
|
21 | cluster.on('online', function(worker) {
|
22 | console.log('The worker #%d(pid=%d) is online', worker.id, worker.process.pid);
|
23 | });
|
24 |
|
25 |
|
26 | cluster.on('listening', function(worker, address) {
|
27 | console.log('The worker #%d(pid=%d) is listening on ' + '%s:%d'.bold.red, worker.id, worker.process.pid, address.address, address.port);
|
28 | });
|
29 |
|
30 |
|
31 | cluster.on('disconnect', function(worker) {
|
32 | console.log('The worker #%d(pid=%d) has disconnected', worker.id, worker.process.pid);
|
33 | });
|
34 |
|
35 |
|
36 | cluster.on('exit', function(worker, code, signal) {
|
37 | var exitCode = worker.process.exitCode;
|
38 | console.log('The worker #%d(pid=%d) died (%d). restarting...', worker.id, worker.process.pid, exitCode);
|
39 | cluster.fork();
|
40 | });
|
41 | };
|
42 |
|
43 | var createServer = function() {
|
44 | var app = require('./app')();
|
45 | var server = require('http').createServer(app);
|
46 |
|
47 | server.setMaxListeners(0);
|
48 |
|
49 | server.listen(settings.port, function() {
|
50 |
|
51 | if (settings.uid) {
|
52 | process.setuid(settings.uid);
|
53 | }
|
54 | if (settings.gid) {
|
55 | process.setgid(settings.gid);
|
56 | }
|
57 | var address = server.address();
|
58 | console.log('Server is listening on %s:%d', address.address, address.port);
|
59 | });
|
60 | };
|
61 |
|
62 | if (settings.cluster.enable) {
|
63 | if (cluster.isMaster) {
|
64 | createMaster(cluster);
|
65 |
|
66 |
|
67 | Object.keys(cluster.workers).forEach(function(id) {
|
68 | cluster.workers[id].on('message', function(msg) {
|
69 | if (msg.cmd === 'bonjour') {
|
70 | console.log('Received a bonjour command from worker #%d(pid=%d)', this.id, this.process.pid);
|
71 | this.send({reply: 'ok'});
|
72 | }
|
73 | });
|
74 | });
|
75 |
|
76 | } else if (cluster.isWorker) {
|
77 | createServer();
|
78 |
|
79 |
|
80 | process.send({cmd: 'bonjour'});
|
81 | process.on('message', function(msg) {
|
82 | console.log('Received a bonjour reply from master: %s', JSON.stringify(msg));
|
83 | });
|
84 | }
|
85 | } else {
|
86 |
|
87 |
|
88 | createServer();
|
89 | }
|