This repository has been archived by the owner on Nov 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
app-cluster.js
89 lines (73 loc) · 2.33 KB
/
app-cluster.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
var cluster = require('cluster');
var net = require('net');
var userconfig = require('./loadConfig');
var config = require('./config')(userconfig);
if(cluster.isMaster) {
var workers = [];
var num = require('os').cpus().length;
// Master will spawn `num` workers
for (var i = 0; i < num; i++) {
!function spawn(i) {
workers[i] = cluster.fork();
// Restart worker on exit
workers[i].on('exit', function() {
console.error('Worker '+i+' died');
spawn(i);
});
}(i);
}
var seed = ~~(Math.random() * 1e9);
net.createServer(function(c) {
// Get int31 hash of ip
var worker,
ipHash = hash(c.remoteAddress, seed);
//TODO: do we need this, error handling should be done in the worker no?
// https://github.com/indutny/sticky-session/pull/12
// handle errors like ECONNRESET on the socket
c.on('error', function (err) {
console.error('sticky: socket error', err);
});
// Pass connection to worker
worker = workers[ipHash % workers.length];
worker.send('sticky:connection', c);
}).listen(config.port, config.hostname, function(err) {
if(err) {
console.log(err.stack || err);
return;
}
console.log("Server's master process started on port "+config.port);
});
} else {
require('./loadApp')(userconfig, function(err, app, model, config, closeApp) {
if(err) {
console.error(err.stack || err);
return;
}
var server = app.server;
// Worker process
process.on('message', function(msg, socket) {
if(msg !== 'sticky:connection') return;
server.emit('connection', socket);
});
// do not bind to port
server.listen();
console.log("Worker ready");
}, false);
}
function hash(ip, seed) {
var nums = (ip || '').split(/\./g);
var hash = nums.reduce(function(r, num) {
r += parseInt(num, 10);
r %= 2147483648;
r += (r << 10)
r %= 2147483648;
r ^= r >> 6;
return r;
}, seed);
hash += hash << 3;
hash %= 2147483648;
hash ^= hash >> 11;
hash += hash << 15;
hash %= 2147483648;
return hash >>> 0;
}