Manages native cluster
module.
Automatically restarts workers and gracefully reloads them on SIGHUP.
You can disable automatic reload and use clusterManager.reload
method manually.
Module is designed in the way that you always have latest working version of cluster after restarting. Old workers are killed only when new are successfully started.
This module is inspired by and partially copied from https://github.com/isaacs/cluster-master.
npm install git://github.com/daeq/node-cluster-manager
var clusterManager = require('cluster-manager');
clusterManager("./app.js");
This example will run 1 worker per CPU executing app.js script.
If you send SIGHUP to cluster process, it gracefully restarts workers one by one.
kill -HUP <cluster script pid>
Reload stops if newly loaded worker exits with error. In that case previously started workers continue running and nothing bad happens. Worker is considered successfully started when it begins listening (fires 'listening' event) or when it runs without error for some time (defaults to 5 seconds). You can change this time in config.
var clusterManager = require('cluster-manager')
clusterManager({
exec: "./app.js",
size: 8,
env: {
NODE_ENV: "production"
},
args: ["--id", "5"],
silent: true,
gracefullyStopTime: 10000,
successfullyStartTime: 200,
onMessage: function(msg) {
console.log("Received message from worker: ", msg)
},
reloadOnHup: true,
beforeReload: function(callback) {
// Prepare environment or something
callback()
},
afterReload: function(err) {
if(err) {
console.log("Something bad happened while reloading: ", err)
}
}
})
Parameters:
exec
- path to script which will be executed by workers. Required (passed to cluster.setupMaster)size
- number of workers. Defaults to number of CPUenv
- environment variables which will be passed to workers.args
- command-line arguments which will be passed to workers (passed to cluster.setupMaster)silent
- whether or not worker's output is sent to main process output (passed to cluster.setupMaster)gracefullyStopTime
- time that cluster manager will wait after sendingdisconnect
command to worker before killing itsuccessfullyStartTime
- worker will be considered successfully started if it runs this amount of time without exitingonMessage
- messages received from workers will be passed herereloadOnHup
- whether or not reload cluster when SIGHUP received (defaults to true)beforeReload
- if specified, this function is called after SIGHUP received before reload starts. It should callcallback
when ready to reload.afterReload
- if specified, this functin is called after reload is finished.err
will be set if reload wasn't completed successfully