diff --git a/package-lock.json b/package-lock.json index ad54ee26..10e0f87c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1212,6 +1212,11 @@ "version": "https://registry.npmjs.org/interpret/-/interpret-1.0.4.tgz", "integrity": "sha1-ggzdWIuGj/sZGoCVBtbJyPISsbA=" }, + "ip": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/ip/-/ip-1.1.5.tgz", + "integrity": "sha1-vd7XARQpCCjAoDnnLvJfWq7ENUo=" + }, "ip-regex": { "version": "https://registry.npmjs.org/ip-regex/-/ip-regex-1.0.3.tgz", "integrity": "sha1-3FiQdvZZ9BnCIgOaMzFvHHOH7/0=" @@ -2368,6 +2373,15 @@ "version": "https://registry.npmjs.org/statuses/-/statuses-1.3.1.tgz", "integrity": "sha1-+vUbnrdKrvOzrPStX2Gr8ky3uT4=" }, + "sticky-session": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/sticky-session/-/sticky-session-1.1.2.tgz", + "integrity": "sha1-cWznOEUrvp7t7FBjEYlaPWSAPeE=", + "requires": { + "debug": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "ip": "1.1.5" + } + }, "stream-consume": { "version": "https://registry.npmjs.org/stream-consume/-/stream-consume-0.1.0.tgz", "integrity": "sha1-pB6tGm1ggc63n2WwYZAbbY89HQ8=" diff --git a/package.json b/package.json index a53c918b..06e4002b 100644 --- a/package.json +++ b/package.json @@ -49,6 +49,7 @@ "request": "^2.72.0", "socket.io": "^2.0.3", "socket.io-redis": "^5.2.0", + "sticky-session": "^1.1.2", "uniqid": "^4.1.1" } } diff --git a/server/app.js b/server/app.js index aa7216c8..35ae9b3a 100644 --- a/server/app.js +++ b/server/app.js @@ -1,35 +1,73 @@ -var app = require('./index.js'); -var path = require('path'); -var publicPath = path.join(__dirname, 'public'); -var debug = require('debug')('king:server'); -var http = require('http'); -//var config = require('../config/index'); +var express = require('express'), + cluster = require('cluster'), + net = require('net'), + socketio = require('socket.io'), + socket_redis = require('socket.io-redis'); -/** -* Get port from environment and store in Express. -*/ -//var env = app.get('env'); -var port = 8080; -app.set('port', port); + var path = require('path'); + var publicPath = path.join(__dirname, 'public'); + + var http = require('http'); + +var port = 8080, + num_processes = require('os').cpus().length; -var cluster = require('cluster'); if (cluster.isMaster) { - var numWorkers = require('os').cpus().length; - for (var i = 0; i < numWorkers; i++) cluster.fork(); - console.log('[CLUSTER] Master cluster setting up ' + numWorkers + ' workers...'); + // This stores our workers. We need to keep them to be able to reference + // them based on source IP address. It's also useful for auto-restart, + // for example. + var workers = []; - cluster.on('online', function(worker) { - console.log('[CLUSTER] Worker ' + worker.process.pid + ' is online'); - }); - cluster.on('exit', function(worker, code, signal){ - console.log('[CLUSTER] Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal); - console.log('[CLUSTER] Starting a new worker'); - cluster.fork(); - }); + // Helper function for spawning worker at index 'i'. + var spawn = function(i) { + workers[i] = cluster.fork(); + + // Optional: Restart worker on exit + workers[i].on('exit', function(code, signal) { + console.log('respawning worker', i); + spawn(i); + }); + }; + + // Spawn workers. + for (var i = 0; i < num_processes; i++) { + spawn(i); + } + + // Helper function for getting a worker index based on IP address. + // This is a hot path so it should be really fast. The way it works + // is by converting the IP address to a number by removing non numeric + // characters, then compressing it to the number of slots we have. + // + // Compared against "real" hashing (from the sticky-session code) and + // "real" IP number conversion, this function is on par in terms of + // worker index distribution only much faster. + var worker_index = function(ip, len) { + var s = ''; + for (var i = 0, _len = ip.length; i < _len; i++) { + if (!isNaN(ip[i])) { + s += ip[i]; + } + } + + return Number(s) % len; + }; + + // Create the outside facing server listening on our port. + var server = net.createServer({ pauseOnConnect: true }, function(connection) { + // We received a connection and need to pass it to the appropriate + // worker. Get the worker for this connection's source IP and pass + // it the connection. + var worker = workers[worker_index(connection.remoteAddress, num_processes)]; + worker.send('sticky-session:connection', connection); + }).listen(port); } else { - /** - * Create HTTP server. - */ + // Note we don't use a port here because the master listens on it for us. + var app = require('./index.js'); + + // Here you might use middleware, attach routes, etc + + // Don't expose our internal server to the outside. try { var cert_config = require(path.join(path.join(__dirname, 'config'), 'cert_config.js')); var fs = require('fs'); @@ -65,58 +103,45 @@ if (cluster.isMaster) { }); var http = require('http'); server = http.Server(app); - add = ",http://localhost:80*,http://localhost:8080*,localhost:8080*, localhost:8082*,http://zoff.dev:80*,http://zoff.dev:8080*,zoff.dev:8080*, zoff.dev:8082*"; - } - var port = 8080; - - /** - * Listen on provided port, on all network interfaces. - */ - server.listen(port); - server.on('error', onError); - server.on('listening', onListening); - - /** - * Socket.io - */ - var io = app.socketIO; - io.listen(server); - //socketIO.set('transports', ['websocket']); -} - - -/** -* Event listener for HTTP server "error" event. -*/ - -function onError(error) { - if (error.syscall !== 'listen') { - throw error; + //add = ",http://localhost:80*,http://localhost:8080*,localhost:8080*, localhost:8082*,http://zoff.dev:80*,http://zoff.dev:8080*,zoff.dev:8080*, zoff.dev:8082*"; } - var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; + server.listen(); - // handle specific listen errors with friendly messages - switch (error.code) { - case 'EACCES': - console.error(bind + ' requires elevated privileges'); - process.exit(1); - break; - case 'EADDRINUSE': - console.error(bind + ' is already in use'); - process.exit(1); - break; - default: - throw error; - } -} - -/** -* Event listener for HTTP server "listening" event. -*/ - -function onListening() { - var addr = server.address(); - var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; - debug('Listening on ' + bind); + var socketIO = app.socketIO; + var redis = require('socket.io-redis'); + socketIO.adapter(redis({ host: 'localhost', port: 6379 })); + //socketIO.set( 'origins', '*localhost:8080' ); + socketIO.listen(server); + + // Tell Socket.IO to use the redis adapter. By default, the redis + // server is assumed to be on localhost:6379. You don't have to + // specify them explicitly unless you want to change them. + //io.adapter(socket_redis({ host: 'localhost', port: 6379 })); + + // Here you might use Socket.IO middleware for authorization etc. + + /*io.on('connection', function(socket) { + console.log('New client connection detected on process ' + process.pid); + + socket.emit('welcome', {message: 'Welcome to BlueFrog Chat Room'}); + socket.on('new.message', function(message) { + socket.emit('new.message', message); + }) + + });*/ + + + // Listen to messages sent from the master. Ignore everything else. + process.on('message', function(message, connection) { + if (message !== 'sticky-session:connection') { + return; + } + + // Emulate a connection event on the server by emitting the + // event with the connection the master sent us. + server.emit('connection', connection); + + connection.resume(); + }); } diff --git a/server/index.js b/server/index.js index 86bbe889..97350459 100755 --- a/server/index.js +++ b/server/index.js @@ -32,11 +32,10 @@ app.use(cookieParser()); /* Starting DB and socketio */ io = require('socket.io')({ pingTimeout: 25000, - path: '/zoff', -}); //, "origins": ("https://zoff.me:443*,https://zoff.me:8080*,zoff.me:8080*,https://remote.zoff.me:443*,https://remote.zoff.me:8080*,https://fb.zoff.me:443*,https://fb.zoff.me:8080*,https://admin.zoff.me:443*,https://admin.zoff.me:8080*" + add)}); + //path: '/zoff', + //"origins": ("https://zoff.me:443*,https://zoff.me:8080*,zoff.me:8080*,https://remote.zoff.me:443*,https://remote.zoff.me:8080*,https://fb.zoff.me:443*,https://fb.zoff.me:8080*,https://admin.zoff.me:443*,https://admin.zoff.me:8080*, http://localhost:8080*")}); +}); db = require('./handlers/db.js'); -redis = require('socket.io-redis'); -io.adapter(redis({ host: 'localhost', port: 6379 })); var socketIO = require('./handlers/io.js'); socketIO();