Advertisement
Guest User

Untitled

a guest
Nov 12th, 2017
127
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.         worker.send('sticky-session:connection', connection);
  67.     }).listen(port);
  68. } else {
  69.   process.setMaxListeners(0);
  70.     // Note we don't use a port here because the master listens on it for us.
  71.     var app = new express();
  72.  
  73.   app.use(bodyParser.json());
  74.  
  75.   app.use(function(req, res, next) {
  76.     res.setHeader('Access-Control-Allow-Origin', '*');
  77.     res.header("Access-Control-Allow-Credentials: true");
  78.     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  79.     next();
  80.   });
  81.  
  82.   app.post('/api/v1/relay', function(request, response){
  83.     console.log('Worker ' + cluster.worker.id + ': Processing from na-regional')
  84.  
  85.     //check customers subscription
  86.     let key = request.body['public_key']
  87.     let queryingString = 'SELECT * FROM users_app WHERE public_key = ?';
  88.  
  89.  
  90.     pool.getConnection(function(err, connection) {
  91.       // Use the connection
  92.       connection.query(queryingString, [key], function(err, result, fields) {
  93.         if (err) throw err;
  94.  
  95.         if(request.body['public_key'] !== result[0]['public_key'] ||
  96.           request.body['private_key'] !== result[0]['private_key'] ||
  97.           !request.body['channel'] || !request.body['event']){
  98.             //log this to a file later get origin for tracking
  99.             console.log('bad request from: ');
  100.             return response.sendStatus(400);
  101.         }
  102.         //get the user id of this customers
  103.         var identifier = result[0]['users_app_id'];
  104.         var customer_id = result[0]['user_id'];
  105.         handle.thisRequest(request, response, io, connection,
  106.                            identifier, customer_id, app);
  107.        });
  108.         // And done with the connection.
  109.         connection.release();
  110.       });
  111.   });
  112.  
  113.   //for load testing
  114.   app.get('/loaderio-721652caf56e83ad1cf084c6984fa5c4/', function(request, response){
  115.       response.send('loaderio-721652caf56e83ad1cf084c6984fa5c4');
  116.   });
  117.  
  118.     // Don't expose our internal server to the outside.
  119.     var server = app.listen(0, 'localhost'),
  120.         io = sio(server);
  121.  
  122.     // Tell Socket.IO to use the redis adapter. By default, the redis
  123.     // server is assumed to be on localhost:6379. You don't have to
  124.     // specify them explicitly unless you want to change them.
  125.     io.adapter(sio_redis({ host: 'localhost', port: 6379 }));
  126.  
  127.     // Here you might use Socket.IO middleware for authorization etc.
  128.   io.sockets.on('connection', function (socket) {
  129.         var origin = socket.request.headers['origin'];
  130.         console.log('A client has connected to from: ' + origin);
  131.         io.emit('demo-2', 'Authorizing your connection..');
  132.  
  133.         pool.getConnection(function(err, connection) {
  134.           var key = socket.request.headers['origin'];
  135.           var getAppInformation = 'SELECT * FROM users_app WHERE origin = ?';
  136.  
  137.           connection.query(getAppInformation, [key], function(err, result, fields) {
  138.               if (err) throw err
  139.  
  140.               if(result.length < 1){
  141.                 io.emit('demo-2', 'You are not authorized on this network. Disconnecting.')
  142.                 return socket.disconnect()
  143.               }
  144.  
  145.               io.emit('demo-2', 'Authorized.')
  146.               var status     = "connection";
  147.               var identifier = result[0]['users_app_id'];
  148.               //var identifier = result['users_app_id'];
  149.               track.customersConnections(identifier, status, pool);
  150.           });
  151.         // And done with the connection.
  152.         connection.release();
  153.         });
  154.  
  155.  
  156.       socket.once('disconnect', function () {
  157.         var origin = socket.request.headers['origin'];
  158.         console.log('A client has disconnected from from: ' + origin);
  159.  
  160.         pool.getConnection(function(err, connection) {
  161.           var status = "disconnection";
  162.           var key = socket.request.headers['origin'];
  163.           var getAppInformation = 'SELECT * FROM users_app WHERE origin = ?';
  164.  
  165.           connection.query(getAppInformation, [key], function(err, result, fields) {
  166.               if (err) throw error
  167.               if(result.length < 1){
  168.                 return
  169.               }
  170.  
  171.               io.emit('demo-2', 'Authorized.')
  172.               var status     = "disconnection";
  173.               var identifier = result[0]['users_app_id'];
  174.               //var identifier = result['users_app_id'];
  175.               track.customersConnections(identifier, status, pool);
  176.           });
  177.         // And done with the connection.
  178.         connection.release();
  179.         });
  180.       });
  181.   });
  182.  
  183.     // Listen to messages sent from the master. Ignore everything else.
  184.     process.on('message', function(message, connection) {
  185.         if (message !== 'sticky-session:connection') {
  186.             return;
  187.         }
  188.  
  189.         // Emulate a connection event on the server by emitting the
  190.         // event with the connection the master sent us.
  191.         server.emit('connection', connection);
  192.  
  193.         connection.resume();
  194.     });
  195. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement