Node.js + Cluster :: Restarting workers without downtime?

For the reasons that I will be here, I want workers to start with a cluster (in node.js), to live for 1 hour each, before restarting themselves.

The caveat is that I need to have zero downtime. Thus, simply executing destroy () for each worker is unacceptable, since it removes the cluster before restarting the workers.

Here is my base code:

if(cluster.isMaster) { for(var i=0; i<2; i++) { cluster.fork(); } return; } require('./api').startup(settings, process.argv, function(error, api){ if(error) { console.log('API failed to start: '+error); } else { console.log('API is running'); } }); 

The api.js script implements express to run the fairly standard RESTful JSON API.

+4
source share
1 answer

The way I did this was to make sure that at least 2 workers were working for me, and then reboot only once.

This bit of code will automatically restart workers who commit suicide through cluster.worker.destroy ()

 cluster.on('exit', function(worker, code, signal) { if (worker.suicide === true) { console.log(new Date()+' Worker committed suicide'); cluster.fork(); } }); 

From there, it's a simple matter for every worker to commit suicide using setTimeout () (or any other condition you want to use). My approach was to get the boss to kill the workers:

 function killWorker(worker) { return function() { worker.destroy(); }; } // This should be run on cluster.isMaster only function killWorkers() { var delay = 0; for (var id in cluster.workers) { var func = killWorker(cluster.workers[id]); if(delay==0) func(); else setTimeout(func, delay); delay += 60000 * 5;// 5 minute delay, inserted to give time for each worker to re-spool itself } } 

As you can see, this inserts a 5-minute delay between workers reloading, which gives each worker enough time to restart himself - this means that there should never be a case where all workers are omitted.

+9
source

Source: https://habr.com/ru/post/1440127/


All Articles