Advertisement
Guest User

Untitled

a guest
Nov 12th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var express         = require('express'),
  2.     cluster         = require('cluster'),
  3.     net             = require('net'),
  4.     sio             = require('socket.io'),
  5.     sio_redis       = require('socket.io-redis'),
  6.     farmhash        = require('farmhash'),
  7.     bodyParser      = require('body-parser'),
  8.     mysql           = require('mysql');
  9.  
  10. let handle          = require('./controllers/apicontroller.js');
  11. let track           = require('./controllers/useagecontroller.js');
  12.  
  13. var port = 8081,
  14.     num_processes = require('os').cpus().length;
  15.  
  16. var pool  = mysql.createPool({
  17.    connectionLimit : 150,
  18.    host: "",
  19.    user: "",
  20.    password: "",
  21.    database: ""
  22. });
  23.  
  24. if (cluster.isMaster) {
  25.     // This stores our workers. We need to keep them to be able to reference
  26.     // them based on source IP address. It's also useful for auto-restart,
  27.     // for example.
  28.     var workers = [];
  29.  
  30.     // Helper function for spawning worker at index 'i'.
  31.     var spawn = function(i) {
  32.         workers[i] = cluster.fork();
  33.     cluster.on('online', function(worker) {
  34.         console.log('Worker ' + worker.process.pid + ' is online');
  35.     });
  36.         // Optional: Restart worker on exit
  37.         workers[i].on('exit', function(code, signal) {
  38.             console.log('respawning worker', i);
  39.             spawn(i);
  40.         });
  41.     };
  42.  
  43.     // Spawn workers.
  44.     for (var i = 0; i < num_processes; i++) {
  45.         spawn(i);
  46.     }
  47.  
  48.     // Helper function for getting a worker index based on IP address.
  49.     // This is a hot path so it should be really fast. The way it works
  50.     // is by converting the IP address to a number by removing non numeric
  51.   // characters, then compressing it to the number of slots we have.
  52.     //
  53.     // Compared against "real" hashing (from the sticky-session code) and
  54.     // "real" IP number conversion, this function is on par in terms of
  55.     // worker index distribution only much faster.
  56.     var worker_index = function(ip, len) {
  57.         return farmhash.fingerprint32(ip[i]) % len; // Farmhash is the fastest and works with IPv6, too
  58.     };
  59.  
  60.     // Create the outside facing server listening on our port.
  61.     var server = net.createServer({ pauseOnConnect: true }, function(connection) {
  62.         // We received a connection and need to pass it to the appropriate
  63.         // worker. Get the worker for this connection's source IP and pass
  64.         // it the connection.
  65.         var worker = workers[worker_index(connection.remoteAddress, num_processes)];
  66.    console.log('<--- added this');
  67.         worker.send('sticky-session:connection', connection);
  68.  
  69.     }).listen(port);
  70. } else {
  71.   process.setMaxListeners(0);
  72.     // Note we don't use a port here because the master listens on it for us.
  73.     var app = new express();
  74.  
  75.   app.use(bodyParser.json());
  76.  
  77.   app.use(function(req, res, next) {
  78.     res.setHeader('Access-Control-Allow-Origin', '*');
  79.     res.header("Access-Control-Allow-Credentials: true");
  80.     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  81.     next();
  82.   });
  83.  
  84.   app.post('/api/v1/relay', function(request, response){
  85.     console.log('Worker ' + process.pid + ': Processing from na-regional')
  86.  
  87.     //check customers subscription
  88.     let key = request.body['public_key']
  89.     let queryingString = 'SELECT * FROM users_app WHERE public_key = ?';
  90.  
  91.  
  92.     pool.getConnection(function(err, connection) {
  93.       // Use the connection
  94.       connection.query(queryingString, [key], function(err, result, fields) {
  95.         if (err) throw err;
  96.  
  97.         if(request.body['public_key'] !== result[0]['public_key'] ||
  98.           request.body['private_key'] !== result[0]['private_key'] ||
  99.           !request.body['channel'] || !request.body['event']){
  100.             //log this to a file later get origin for tracking
  101.             console.log('bad request from: ');
  102.             return response.sendStatus(400);
  103.         }
  104.         //get the user id of this customers
  105.         var identifier = result[0]['users_app_id'];
  106.         var customer_id = result[0]['user_id'];
  107.         handle.thisRequest(request, response, io, connection,
  108.                            identifier, customer_id, app);
  109.        });
  110.         // And done with the connection.
  111.         connection.release();
  112.       });
  113.   });
  114.  
  115.   //for load testing
  116.   app.get('/loaderio-721652caf56e83ad1cf084c6984fa5c4/', function(request, response){
  117.       response.send('loaderio-721652caf56e83ad1cf084c6984fa5c4');
  118.   });
  119.  
  120.     // Don't expose our internal server to the outside.
  121.     var server = app.listen(0, 'localhost'),
  122.         io = sio(server);
  123.  
  124.     // Tell Socket.IO to use the redis adapter. By default, the redis
  125.     // server is assumed to be on localhost:6379. You don't have to
  126.     // specify them explicitly unless you want to change them.
  127.     io.adapter(sio_redis({ host: 'localhost', port: 6379 }));
  128.  
  129.     // Here you might use Socket.IO middleware for authorization etc.
  130.   io.sockets.on('connection', function (socket) {
  131.         var origin = socket.request.headers['origin'];
  132.         console.log('A client has connected to from: ' + origin);
  133.         io.emit('demo-2', 'Authorizing your connection..');
  134.  
  135.         pool.getConnection(function(err, connection) {
  136.           var key = socket.request.headers['origin'];
  137.           var getAppInformation = 'SELECT * FROM users_app WHERE origin = ?';
  138.  
  139.           connection.query(getAppInformation, [key], function(err, result, fields) {
  140.               if (err) throw err
  141.  
  142.               if(result.length < 1){
  143.                 io.emit('demo-2', 'You are not authorized on this network. Disconnecting.')
  144.                 return socket.disconnect()
  145.               }
  146.  
  147.               io.emit('demo-2', 'Authorized.')
  148.               var status     = "connection";
  149.               var identifier = result[0]['users_app_id'];
  150.               //var identifier = result['users_app_id'];
  151.               track.customersConnections(identifier, status, pool);
  152.           });
  153.         // And done with the connection.
  154.         connection.release();
  155.         });
  156.  
  157.  
  158.       socket.once('disconnect', function () {
  159.         var origin = socket.request.headers['origin'];
  160.         console.log('A client has disconnected from from: ' + origin);
  161.  
  162.         pool.getConnection(function(err, connection) {
  163.           var status = "disconnection";
  164.           var key = socket.request.headers['origin'];
  165.           var getAppInformation = 'SELECT * FROM users_app WHERE origin = ?';
  166.  
  167.           connection.query(getAppInformation, [key], function(err, result, fields) {
  168.               if (err) throw error
  169.               if(result.length < 1){
  170.                 return
  171.               }
  172.  
  173.               io.emit('demo-2', 'Authorized.')
  174.               var status     = "disconnection";
  175.               var identifier = result[0]['users_app_id'];
  176.               //var identifier = result['users_app_id'];
  177.               track.customersConnections(identifier, status, pool);
  178.           });
  179.         // And done with the connection.
  180.         connection.release();
  181.         });
  182.       });
  183.   });
  184.  
  185.     // Listen to messages sent from the master. Ignore everything else.
  186.     process.on('message', function(message, connection) {
  187.         if (message !== 'sticky-session:connection') {
  188.             return;
  189.         }
  190.  
  191.         // Emulate a connection event on the server by emitting the
  192.         // event with the connection the master sent us.
  193.         server.emit('connection', connection);
  194.  
  195.         connection.resume();
  196.     });
  197. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement