-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
120 lines (102 loc) · 2.75 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
/**
* Launch cluster and workers.
* React on SIGINT and SIGTERM.
* restart worker if worker exit.
*/
'use strict';
require('dotenv').config();
const fs = require('fs');
const spawn = require('child_process').spawn;
if (!process.env.DEVEL && process.env.LOGFILE && !process.env.BACKGROUND) {
var spawnArgvs = [];
for (var i in process.argv) {
if (i > 0) {
spawnArgvs.push(process.argv[i]);
}
}
var env = process.env;
env.BACKGROUND = true;
spawn(process.argv0, spawnArgvs, {
stdio: 'ignore',
detached: true,
env: env,
}).unref();
process.exit();
}
if (process.env.DEVEL) {
if (process.env.DEVEL_DEBUG) {
process.env.DEBUG = process.env.DEVEL_DEBUG;
} else {
process.env.DEBUG = '*';
}
}
if (process.env.BACKGROUND) {
process.env.DEBUG_COLORS = false;
var logFile = fs.createWriteStream(process.env.LOGFILE, { flags: 'a' });
process.stdout.write = process.stderr.write = logFile.write.bind(logFile);
}
const cluster = require('cluster');
const WebHttp = require('./includes/web.js');
const debugF = require('debug');
/**
* Constructor.
* Prepare data for deploy.
*/
function Cluster(data) {
var self = this;
self.data = data;
if (cluster.isMaster) {
if (data.pid) {
fs.writeFileSync(data.pid + "", process.pid + "");
}
let numCPUs = 1;
if (data.count) {
numCPUs = data.count;
} else {
numCPUs = require('os').cpus().length;
}
self.debug.log('Starting up %s workers.', numCPUs);
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('online', function(worker) {
self.debug.log('Worker %s is online', worker.process.pid);
});
cluster.on('exit', function(worker, code, signal) {
self.debug.log('Worker %s died. code %s signal %s', worker.process.pid, code, signal);
self.debug.log('Starting a new worker');
cluster.fork();
});
cluster.on('listening', function(worker, address) {
if (self.data.callbacks['init']) {
self.data.callbacks['init'](cluster, worker, address);
}
});
process.on('SIGINT', function() {
self.debug.log('Caught interrupt signal');
if (data.pid) {
fs.unlinkSync(data.pid);
}
process.exit();
});
} else {
var webServer = new WebHttp(self.data);
process.on('SIGINT', function() {
self.debug.worker('Caught interrupt signal');
webServer.stop();
});
process.on('SIGTERM', function() {
self.debug.worker('Caught termination signal');
webServer.stop();
}
);
}
return cluster;
}
Cluster.prototype.debug = {
log: debugF('cluster:main'),
worker: debugF('cluster:worker')
};
// Processed by tokens data structure
Cluster.prototype.data = {};
module.exports = Cluster;