Showing posts with label load-balancing. Show all posts
Showing posts with label load-balancing. Show all posts

Monday, April 2, 2018

Catching disconnects with Apache Load Balancer and node/io.socket backend

Leave a Comment

NOTE: I have solved most of the problem, but am still encountering an issue with catching the disconnects as noted towards the bottom of this post in the Update section.

NOTE 2: As requested I have posted a more complete view of my setup. See the heading at the bottom of this post.

I am trying to set up a load balancer in Apache but it is not working for socket.io. My Apache code looks like this:

<VirtualHost *:80>         ServerAdmin webmaster@example.com         ServerName jpl.example.com          ProxyRequests off          Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED         <Proxy "balancer://mycluster">                 BalancerMember "http://203.0.113.22:3000" route=1                 BalancerMember "http://203.0.113.23:3000" route=2         </Proxy>          ProxyPass "/test/" "balancer://mycluster/"         ProxyPassReverse "/test/" "balancer://mycluster/"      </VirtualHost> 

Problems with socket.io

The issue I am facing is that on the backend I have a node.js server that uses socket.io connections for long polling in both subdir1/index.html and subdir2.index.html. Unfortunately, socket.io likes to be only running from the root directory:

http://203.0.113.22:3000/socket.io/ 

It is unable to find it if I try running it from:

http://jpl.example.com/test/socket.io 

The start of my index.js file on the server looks like this:

// Setup basic express server var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); 

Part of my /subdir1/index.html (also being loaded from the server) originally looked like this:

<script src="/socket.io/socket.io.js"></script> <script>     var socket = io.connect();     socket.on('notification', function (data) { 

But I was now getting an error when accessing it through the proxy. The error was:

http://jpl.example.com/socket.io/socket.io.js 404 (Not Found) 

I have tried changing it to this:

<script src="/test/socket.io/socket.io.js"></script> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script>     var refresh_value = 0;     var refresh_time = 0;     //var socket = io.connect();     var socket = io.connect('http://example.com/', {path: "/test/"});     socket.on('notification', function (data) { 

It no longer gives me an error, but there is no indication that it is communicating with the socket.

What am I doing wrong here and how can I get this to work?

Update

I have now mostly solved the problem with using:

var socket = io.connect('http://example.com/', {path: "/test/socket.io"}); 

instead of:

var socket = io.connect('http://example.com/', {path: "/test/"}); 

Final problem:

Things are now working but I am still experiencing the following issue:

It takes about a minute before it detects that a client has actually closed a page. Without a Proxy and Apache load balancer I do not have this issue. I have tried various things such as setting KeepAlive to "no" and modifying the VirtualHost at the top of this page with the following:

        <Proxy "balancer://mycluster">                 BalancerMember "http://203.0.113.22:3000" route=1 max=128 ttl=300 retry=60 connectiontimeout=5 timeout=300 ping=2                 BalancerMember "http://203.0.113.23:3000" route=2 max=128 ttl=300 retry=60 connectiontimeout=5 timeout=300 ping=2         </Proxy> 

But it still takes about a minute before it recognizes that a client has left the page. What can I do to solve this problem?

A more complete view of my setup

As requested, to help diagnose the problem I am posting a more complete view of my setup. I have eliminated as much as I thought I could while providing as much detail as I could:

My current Apache file:

<VirtualHost *:80>     # Admin email, Server Name (domain name), and any aliases     ServerAdmin webmaster@example.com     ServerName jpl.example.com      ProxyRequests off      Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED     <Proxy "balancer://mycluster">         BalancerMember "http://203.0.113.22:3000" route=1 keepalive=On smax=1 connectiontimeout=10 retry=600 timeout=900 ttl=900         BalancerMember "http://203.0.113.23:3000" route=2 keepalive=On smax=1 connectiontimeout=10 retry=600 timeout=900 ttl=900         ProxySet stickysession=ROUTEID     </Proxy>      <Proxy "balancer://myws">         BalancerMember "ws://203.0.113.22:3000" route=1 keepalive=On smax=1 connectiontimeout=10 retry=600 timeout=900 ttl=900         BalancerMember "ws://203.0.113.23:3000" route=2 keepalive=On smax=1 connectiontimeout=10 retry=600 timeout=900 ttl=900         ProxySet stickysession=ROUTEID     </Proxy>      RewriteEngine On     RewriteCond %{REQUEST_URI}  ^/test/socket.io                [NC]     RewriteCond %{QUERY_STRING} transport=websocket        [NC]     RewriteRule /(.*)           balancer://myws/$1 [P,L]      ProxyPass "/test/" "balancer://mycluster/"     ProxyPassReverse "/test/" "balancer://mycluster/"  </VirtualHost> 

On each of those servers I have a node installation. The main index.js looks like this:

/************ Set Variables ******************/  // Setup basic express server var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); var port = process.env.PORT || 3000; var fs                  = require('fs'),     mysql               = require('mysql'),     connectionsArray    = [],     connection          = mysql.createConnection({         host        : 'localhost',         user        : 'myusername',         password    : 'mypassword',         database    : 'mydatabase',         port        : 3306     }),     POLLING_INTERVAL = 5000;   server.listen(port, function () {         console.log("-----------------------------------");         console.log('Server listening at port %d', port); });  // Routing app.use(express.static(__dirname + "/public"));   /*********  Connect to DB ******************/ connection.connect(function(err) {         if (err == null){                 console.log("Connected to Database!");         }         else {                 console.log( err );                 process.exit();         } });    /***********************  Looping *********************/  var pollingLoop = function () {          var query = connection.query('SELECT * FROM spec_table'),         specs = [];          query         .on('error', function(err) {                 console.log( err );                 updateSockets( err );         })          .on('result', function( spec ) {                 specs.push( spec );         })          .on('end',function(){                 pollingLoop2(specs);         });  };  var pollingLoop2 = function (specs) {          // Make the database query         var query = connection.query('SELECT * FROM info_table'),         infos = [];          // set up the query listeners         query         .on('error', function(err) {                 console.log( err );                 updateSockets( err );         })          .on('result', function( info ) {                 infos.push( info );         })          .on('end',function(){                 if(connectionsArray.length) {                         setTimeout( pollingLoop, POLLING_INTERVAL );                         updateSockets({specs:specs, infos:infos});                 }         });  };  /***************  Create new websocket ****************/ //This is where I can tell who connected and who disconnected.  io.sockets.on('connection', function ( socket ) {          var socketId = socket.id;          var clientIp = socket.request.connection.remoteAddress;          var time = new Date();         console.log(time);         console.log("\033[32mJOINED\033[0m: "+ clientIp + " (Socket ID: " + socketId + ")");          // start the polling loop only if at least there is one user connected         if (!connectionsArray.length) {                 pollingLoop();         }          socket.on('disconnect', function () {                 var socketIndex = connectionsArray.indexOf( socket );                  var time = new Date();                 console.log(time);                 console.log("\033[31mLEFT\033[0m: "+ clientIp + " (Socket ID: " + socketId + ")");                  if (socketIndex >= 0) {                         connectionsArray.splice( socketIndex, 1 );                 }                 console.log('    Number of connections: ' + connectionsArray.length);         });          connectionsArray.push( socket );         console.log('    Number of connections: ' + connectionsArray.length);  });   /********* Function updateSockets ************/  var updateSockets = function ( data ) {          connectionsArray.forEach(function( tmpSocket ){                 tmpSocket.volatile.emit( 'notification' , data );         });  }; 

Finally, in my public/dir1/index.html file I have something that looks like this:

//HTML code here <script src="/test/socket.io/socket.io.js"></script> <script>     var socket = io.connect('', {path: "/test/socket.io"});     socket.on('notification', function (data) {             $.each(data.specs,function(index,spec){                     //Other js code here             })     }) </script> //More HTML code here 

With this particular setup the connection works, but it takes over a minute before I can detect that a page is closed. Also, with this set up there is an error logged to the console:

WebSocket connection to 'ws://jpl.example.com/test/socket.io/?EIO=3&transport=websocket&sid=QE5aCExz3nAGBYcZAAAA' failed: Connection closed before receiving a handshake response ws @ socket.io.js:5325 

What am I doing wrong and how can I fix my code so that I can detect disconnects the moment they occur?

Note: It works just fine if I do not use a subdirectory /test/.

Please also note: this is only a subdirectory appearing in the URL. It does not exist in the file system anywhere.

Also, I am open to tips and suggestions if you notice areas in my code that I could be writing better.

3 Answers

Answers 1

So after some hit and trials, I was able to get a config which works fine. The changes required

Base Path on Server

You need to use the base path on server as well to make this smooth

var io = require('socket.io')(server, { path: '/test/socket.io'}); 

And then below is the updated Apache config I used

<VirtualHost *:8090>     # Admin email, Server Name (domain name), and any aliases     ServerAdmin webmaster@example.com      ProxyRequests off     #Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED    Header add Set-Cookie "SERVERID=sticky.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED      <Proxy "balancer://mycluster">         BalancerMember "http://127.0.0.1:3001" route=1 keepalive=On smax=1 connectiontimeout=10 retry=600 timeout=900 ttl=900         BalancerMember "http://127.0.0.1:3000" route=2 keepalive=On smax=1 connectiontimeout=10 retry=600 timeout=900 ttl=900         ProxySet stickysession=SERVERID     </Proxy>      <Proxy "balancer://myws">         BalancerMember "ws://127.0.0.1:3001" route=1 keepalive=On smax=1 connectiontimeout=10 retry=600 timeout=900 ttl=900         BalancerMember "ws://127.0.0.1:3000" route=2 keepalive=On smax=1 connectiontimeout=10 retry=600 timeout=900 ttl=900         ProxySet stickysession=SERVERID     </Proxy>      RewriteEngine On     RewriteCond %{HTTP:Upgrade} =websocket [NC]     RewriteRule /(.*) balancer://myws/$1 [P,L]      RewriteCond %{HTTP:Upgrade} !=websocket [NC]     RewriteRule /(.*)                balancer://mycluster/$1 [P,L]     ProxyTimeout 3 </VirtualHost> 

And now the disconnects are immediate

Disconnect

Answers 2

Im not that familiar with Apaches mod_proxy, but I think your issue is related to your paths.

I setup a little test to see if I could help (and have a play), in my test I will proxy both HTTP and ws traffic to a single backend. Which is what your doing plus websockets.

Servers (LXD Containers):

  • 10.158.250.99 is the proxy.
  • 10.158.250.137 is the node.

First, enable the apache mods on the proxy:

sudo a2enmod proxy sudo a2enmod proxy_http sudo a2enmod proxy_wstunnel sudo a2enmod proxy_balancer sudo a2enmod lbmethod_byrequests 

Then change 000-default.conf:

sudo nano /etc/apache2/sites-available/000-default.conf 

This is what I used after clearing out the comments:

<VirtualHost *:80>     ServerAdmin webmaster@localhost     DocumentRoot /var/www/html      ErrorLog ${APACHE_LOG_DIR}/error.log     CustomLog ${APACHE_LOG_DIR}/access.log combined      <Proxy balancer://mycluster>         BalancerMember http://10.158.250.137:7779     </Proxy>       ProxyPreserveHost On      # web proxy - forwards to mycluser nodes     ProxyPass /test/ balancer://mycluster/     ProxyPassReverse /test/ balancer://mycluster/      # ws proxy - forwards to web socket server     ProxyPass /ws/  "ws://10.158.250.137:7778"  </VirtualHost> 

What the above config is doing:

  • Visit the proxy http://10.158.250.99 it will show default Apache page.
  • Visit the proxy http://10.158.250.99/test/ it will forward the HTTP request to http://10.158.250.137:7779.
  • Visit the proxy http://10.158.250.99/ws and it will make a websocket connection to ws://10.158.250.137:7778 and tunnel it though.

So for my app im using phptty as it uses HTTP and WS, its uses xterm.js frontend which connects to websocket http://10.158.250.99/ws to give a tty in the browser.

Here Is a screen of it all working, using my LXDui electron app to control it all.

enter image description here

So check your settings against what I have tried and see if it's different, its always good to experiment abit to see how things work before trying to apply them to your idea.

Hope it helps.

Answers 3

I think your delay problem to detect the client has closed the page comes from your default kernel tcp keepalive configuration of your proxy apache node. I think in your system, if you check the value of sys.net.ipv4.tcp_keepalive_time, you may have the value 60 that should be the 60 seconds waited before the first keepalive packet is sent to detect if the client has closed the connection. From your problem details, mod_proxy looks to have an issue because it seems to not forward the RST packet that you correctly manage without the mod_proxy module. Without solving that forward RST packet issue on mod_proxy, you may only be able to reduce the delay by decreasing the parameter tcp_keepalive_time in example to 5, to wait up to 5 second before to start to check if the tcp connection is closed. Check also the number of failed keepalive probes parameters before to state the connection has been closed, it could also impact the total delay. This is tcp_keepalive_probes parameter.

Read More

Sunday, February 4, 2018

HTTP status code names are missing when using Nginx

Leave a Comment

I'm using Nginx to

redirect all HTTP requests to HTTPS

in my spring boot application.This is the nginx configuration that i'm using,with that i was able to redirect all requests to Https but when i do it i get the status code returned correctly but it doesnt have the status code name anymore.if i remove nginx and run spring boot application alone i can get the http status with its code name and code.

server {    listen 80 default_server;   listen [::]:80 default_server;   server_name _ ;    access_log /var/log/nginx/access.log;   error_log /var/log/nginx/error.log;    proxy_set_header X-Forwarded-Proto $scheme;   proxy_set_header X-Real-IP $remote_addr;   proxy_set_header Host $host;   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;     if ( $http_x_forwarded_proto != 'https' ) {     return 307 https://$host$request_uri;   }    location / {     proxy_set_header X-Forwarded-Proto http;     proxy_pass http://localhost:7070;       expires -1;   }  } 

what am i doing wrong in here should i use proxy_redirect instead of proxy_pass, or am i missing anything in here.that'd be great if you can help.

1 Answers

Answers 1

In the same config file

listen on 80 to redirect req to https (443)

server {     listen 80;     listen [::]:80;     server_name your_url.com www.your_url.com;      return 301 https://your_url.com$request_uri; } 

listen on 433

server {     listen 443 ssl default_server;     listen [::]:443 ssl default_server;      location / {             # proxy pass to your app              proxy_pass http://localhost:7070;             proxy_http_version 1.1;             proxy_set_header Upgrade $http_upgrade;             proxy_set_header Connection 'upgrade';             proxy_set_header Host $host;             proxy_cache_bypass $http_upgrade;     } 

This is the way I do it, and works perfectly for me, cheers!

Read More

Thursday, October 19, 2017

Load Balancer sticky sessions and very old webservices

Leave a Comment

With a hardware LoadBalancer, you can configure sticky sessions which will make sure the same session will always go to the same server.

But will this work with webservices also (rather than webservers)?

i.e. I have WebServices hosted behind a Load Balancer.

Will Webservice calls coming from different native clients (not browser clients) always go to the same webservice server?

These are very old style Webservices - uses RPC/Encoding - the native client program uses Axis 1.4 for the client stubs.

3 Answers

Answers 1

Webservice calls coming from different native clients (not browser clients) always go to the same webservice server should be possible.

To maintain the session stickiness, mostly load balance inject the server identifier in cookie while responding back to the client(kindly note cookie is not a browser feature it is HTTP feature defined by this specification) and should be supported by the HTTP client which is used by Axis 1.4 underneath).

I suggest you to to analyze how your load balance works and based on that you may have to change your needs to change your clients. If your load-balance uses the cookie based approach, this answer you may found useful.

Hope this helps.

Answers 2

If you can keep your application stateless,make it it's good in both performance and scalability.

Benefits of stateless :

  • Scalability. You can have as many servers as we want without having to share a user session. Each of them can process request (e.g. load balancing via round robin).

  • Saves server resources. We do not need to allocate memory on the server side (again - scalability).

  • No need to recover after a server restart.

Session stickiness can be tricky to get right. For example, if your web servers are running on multi-core machines, and you have several processes handling web traffic, you'll need a way to be sticky to both a specific machine and a single process on that machine. So make sure your system degrades well in cases where stickiness doesn't work correctly.

Good discussion you can find here : Sticky and NON-Sticky sessions

Sticky session pro and cons : Pros and Cons of Sticky Session / Session Affinity load blancing strategy?

Now come to your question :

Will Webservice calls coming from different native clients (not browser clients) always go to the same webservice server?

Yes in sticky session .

These are very old style Webservices - uses RPC/Encoding - the native client program uses Axis 1.4 for the client stubs.

Session configuration you need load balancer/server and it can handle any old or new type of applications

this work with webservices also (rather than webservers)?

No its configuration you need to make on server level.

Answers 3

It will work as long as your native client correctly manage the session, ie. set the correct http header for each request.

Generally sticky session is managed by the load balancer by modifying the session cookie to add the server identity.

HA-proxy example

There must be a dedicated documentation for your load balancer.

Read More

Saturday, October 14, 2017

Nginx, load-balancing using sticky and least connections algorithms simulteniously

Leave a Comment

We use Nginx as load-balancer for our websocket application. Every backend server keeps session information so every request from client must be forwarded on the same server. So we use ip_hash directive to achieve this:

upstream app {     ip_hash;     server 1; } 

The problem appears when we want to add another backend server:

upstream app {     ip_hash;     server 1;     server 2; } 

New connections go to server 1 and server 2 - but this is not what we need in this situation as load on server 1 continues to increase - we still need sticky sessions but least_conn algorithm enabled too - so our two servers receive approximately equal load.

We also considered using Nginx-sticky-module but the documentaton says that if no sticky cookie available it will fall back to round-robin default Nginx algorithm - so it also does not solve a problem.

So the question is can we combine sticky and least connections logic using Nginx? Do you know which other load balancers solve this problem?

2 Answers

Answers 1

Probably using the split_clients module could help

upstream app {     ip_hash;     server 127.0.0.1:8001; }  upstream app_new {     ip_hash;     server 127.0.0.1:8002; }  split_clients "${remote_addr}AAA" $upstream_app {     50% app_new;     *   app; } 

This will split your traffic and create the variable $upstreap_app the one you could use like:

server {    location /some/path/ {    proxy_pass http://$upstream_app; } 

This is a workaround to the least_conn and the load balancer that work with sticky sessions, the "downside" is that if more servers need to be added, a new stream needs to be created, for example:

split_clients "${remote_addr}AAA" $upstream_app {     30% app_another_server;     30% app_new;     *   app; } 

For testing:

for x in {1..10}; do \   curl "0:8080?token=$(LC_ALL=C; cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)"; done 

More info about this module could be found in this article (Performing A/B testing)

Answers 2

You can easily achieve this using HAProxy and I indeed suggest going through it thoroughly to see how your current setup can benefit.

With HA Proxy, you'd have something like:

backend nodes     # Other options above omitted for brevity     cookie SRV_ID prefix     server web01 127.0.0.1:9000 cookie check     server web02 127.0.0.1:9001 cookie check     server web03 127.0.0.1:9002 cookie check 

Which simply means that the proxy is tracking requests to-and-fro the servers by using a cookie.

However, if you don't want to use HAProxy, I'd suggest you setup you change your session implementation to use an in-memory DB such as redis/memcached. This way, you can use leastconn or any other algorithm without worrying about sessions.

Read More

Friday, March 31, 2017

Proxy TCP stream (MySQL and Redis) with Nginx

Leave a Comment

I read about Nginx Fabric Model and it brings my attention to reconfigure how an application communicates to MySQL and Redis. If local Nginx instance can proxy HTTP traffic efficiently and fast, now it can also proxy TCP without worrying of network, even using database slave as master in case of emergency and potentially encapsulate database sharding. All the benefits can simplify application configuration and its logic, network (congestion, latency, timeouts, retries) won't be a focus in features development anymore.

I use latest Docker and set of containers: Nginx, Redis, MySQL. I tried the following configuration:

user  nginx; worker_processes  1;  error_log  /var/log/nginx/error.log info; pid        /var/run/nginx.pid;   events {   worker_connections  1024; }  stream {   upstream redis {     # prefer first server but limit connections     server 172.17.0.8:6379 weight=2 max_conns=1;     server 172.17.0.3:6379;   }    upstream mysql {     # use second server in case of failure     server 172.17.0.4:3306;     server 172.17.0.5:3306 backup;   }    server {     listen 6379 so_keepalive=on;     proxy_pass redis;   }    server {     listen 3306 so_keepalive=on;     proxy_pass mysql;   } } 

I have some questions:

  • logging - how can I know which endpoint is in use, how many times did Nginx retry a particular request?

  • real-time stats - is it possible to get throughput for stream module?

  • from database sharding perspective - is it possible to dispatch request to sharded database based on some logic apart from $remote_addr?

Last question is quite important, I found modules ngx_stream_map_module and ngx_stream_split_clients_module but $remote_addr is not suitable for sharding, can we intercept cookie from http section and reuse in stream section where we don't have any headers? Can we inject Lua code in the stream section? Is ngx_stream_ssl_preread_module a solution for this problem, how to make it work for connection without encryption?

0 Answers

Read More

Thursday, March 31, 2016

Create Azure Load Balancer for existing VMs in Azure Preview Portal

Leave a Comment

I wouldn't generally ask such questions on SO but my patience has run out as I have lost a day on this. Does anyone know how on earth someone can create a simple Load Balancer to load balance two existing VMs. The VMs are Rabbit MQs and I need to put a load balancer in front to distribute the traffic accordingly.

I wish I could give bounty to anyone that helps out.

Thanks

1 Answers

Answers 1

In your resource group, click + New to add a new resource and then search for "Load Balancer".

I have just tested, it seems to work :

azure load balancer

Once created, you can configure it to create your load balancing rules (and target your VMs).

Hope this helps,

Julien

Read More

Tuesday, March 8, 2016

how to load balance jboss4.2.2AS on amazon ec2 with distributed caching

Leave a Comment

I have an old application which is hard to upgrade to a newer version of jboss. I want to keep the jboss version same(to 4.2.2 AS) and load balance it on amazon EC2 with distributed caching.

I am able to load balance it, but I am struggling with distributed caching. Can anyone please help me with this?

For caching I am using the following libraries: org.hibrnate.cacheable and org.jbosss.cache.

Is it possible to implement distributed caching on jboss4.2.2 with these libraries? If yes, then how should I go about it?

0 Answers

Read More