-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathzero_downtime.js
63 lines (54 loc) · 1.45 KB
/
zero_downtime.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
var cluster = require('cluster'),
restartWorkers = function restartWorkers() {
var wid, workerIds = [];
// create a copy of current running worker ids
for(wid in cluster.workers) {
workerIds.push(wid);
}
workerIds.forEach(function(wid) {
cluster.workers[wid].send({
text: 'shutdown',
from: 'master'
});
setTimeout(function() {
if(cluster.workers[wid]) {
cluster.workers[wid].kill('SIGKILL');
}
}, 5000);
});
};
if(cluster.isMaster) {
var numWorkers = require('os').cpus().length,
fs = require('fs'),
i, worker;
console.log('Master cluster setting up ' + numWorkers + ' workers...');
for(i = 0; i < numWorkers; i++) {
worker = cluster.fork();
worker.on('message', function() {
console.log('arguments', arguments);
});
}
// set up listener of file changes for restarting workers
fs.readdir('.', function(err, files) {
files.forEach(function(file) {
fs.watch(file, function() {
restartWorkers();
});
});
});
cluster.on('exit', function(_worker, code, signal) {
console.log('Worker ' + _worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
console.log('Starting a new worker');
worker = cluster.fork();
worker.on('message', function() {
console.log('arguments', arguments);
});
});
} else {
process.on('message', function(message) {
if(message.text === 'shutdown') {
process.exit(0);
}
});
console.log('Worker ' + process.pid + ' is alive!');
}