Saturday 6 May 2017

How to find request header in node.js net.createserver?

I have a problem while using apache reverse proxies to handle virtualhosts for multiple applications on the same server in conjunction with node.js (I'm unable to resolve remote addresses and pass connections to other threads - doing either one seems to work well enough.) This seems to come down to parsing the HTTP header x-forwarded-for created by the Apache reverse proxy engine.

To start, my node.js application makes use of the following packages (so avoiding additional packages is a must, this combination alone is already a house of cards)

  • socket.io
  • socket.io-redis
  • cluster
  • redis
  • express

Now, for the actual issue - this code works flawlessly without a reverse proxy:

const server = net.createServer({pauseOnConnect: true}, function (connection) {
    console.log('Connection from ' + connection.remoteAddress.toString());
    var worker = workers[worker_index(connection.remoteAddress, worker_count)];
    worker.send('sticky-session:connection', connection);
}).listen(port, host);

However the net module doesn't parse out HTTP headers, needed to determine the remoteAddress for sticky sessions from behind an apache reverse proxy.

The ideal solution for this would function like:

const server = require('http').createServer(function (connection) {
    console.log('Connection from ' + (connection.headers['x-forwarded-for'] || '127.0.0.1'));
    var worker = workers[worker_index((connection.headers['x-forwarded-for'] || '127.0.0.1'), worker_count)];
    worker.send('sticky-session:connection', connection);
}).listen(port, host);

However it seems connections from the http module cannot be passed across threads as those from the net module can be. A solution which allows the passing of http-derived connections across threads in a cluster would likewise be appreciated.

Just please don't suggest sticky-session, sticky-session-reverse-proxy, socket-io-sticky-session or anything derived from them, none work without breaking connections to either socket.io, express or in the cases of the more dated ones, cluster.

By the way, workers is populated by:

var workers = [];
for (var i = 0; i < worker_count; i++) {
    workers.push(cluster.fork({ 'ID': i }));
}



via CoryG

No comments:

Post a Comment