division

Simple and powerful wrapper over node.js cluster API. This module is inspired by impressive but abandoned project Cluster created by visionmedia (TJ Holowaychuk)

npm install division
8 downloads in the last day
30 downloads in the last week
211 downloads in the last month

division

Simple and powerful wrapper over node.js cluster API.
This module is inspired by impressive but abandoned project Cluster created by @visionmedia.

Installation

$ npm install division

Running Tests

First go to module directory and install development dependencies:

$ npm install

Then you can test module typing:

$ npm test

Features

The most valuable feature: you don't need to change your code to working within cluster.

Other features:

  • works with node version >= 0.8
  • standalone (without 3rd-party dependencies)
  • zero-downtime restart
  • maintains worker count
  • forceful shutdown support
  • graceful shutdown support
  • bundled extensions
    • debug: enable verbose debugging informations
    • watch: reload cluster when files was changed
    • signals: add ability to control cluster with POSIX signals

Example

More examples you can find in examples directory.

Standard configuration example

var division = require('division');
var cluster = new division();

// Configuration for development environment
cluster.configure('development', function () {
  // Put your development configuration here
  cluster.set('args', ['--some-process-args', 'send-to-workers']);
});

// Configuration for production environment
cluster.configure('production', function () {
  // Put your production configuration here
  cluster.enable('silent');
});

// Configuration for all environments
// TIP: this is pointing to cluster
cluster.configure(function () {
  this.set('path', 'app.js');
});

// You can also set settings without configuration block
cluster.set('size', 2);

// Use extensions
// TIP: You can chain (almost) all methods
cluster.use('debug').use('signals');

// Start your application as a cluster!
cluster.run(function () {
  // `this` is pointing to the Master instance
});

You can set environment while launching application - in this way:

$ NODE_ENV=production node cluster.js

Minimal configuration example

var division = require('division');
// You can pass settings in constructor
var cluster = new division({ path : 'app.js' });

cluster.run();

API Reference

[ division | Master | Worker ]

Division class

[ Attributes | Methods ]

Attributes

[ version | environment | settings ]

version

Constant String
Contain current version number of division module.

environment

Constant String, default: 'development'
Contain name of current runtime environment (NODE_ENV).

NOTE: This could be set only when starting application. This cannot be changed when application is running.

settings

Read-Only Object, default: { extensions: [], size: Math.max(2, require('os').cpus().length) }
Contain current division configuration. List of currently available configuration keys:

  • path ( String ) — path to workers file
  • args ( Array ) — string arguments passed to workers
  • size ( Number ) — amount of workers processes to be run
  • silent ( Boolean ) — whether or not to send output to parent stdio
  • timeout ( Number ) — time in ms to kill worker process, which don't want to close itself after close

NOTE: Settings are read-only when directly called. They can be changed only by class methods or by constructor call.

NOTE: path, args and silent can be modified until run method is not called. After that, changes will not take effects.

Methods

[ configure | set | get | use | enable | disable | enabled | disabled | run ]

configure

Conditionally perform the following action if NODE_ENV matches environment or if there is no environment set.

parameters: environment optional String, action required Function
return: division instance (for chaining)

set

Set setting to value.

parameters: setting required String, value required Mixed
return: division instance (for chaining)

get

Get value from setting.

parameters: setting required String
return: value of setting field

use

Use the given extension. If extension is string - this method try to require extension library; if function then this method invoke that function in Master instance scope.

parameters: extension required String or Function, parameters... optional list of mixed values
return: division instance (for chaining)

enable

Set setting to true.

parameters: setting required String
return: division instance (for chaining)

disable

Set setting to false.

parameters: setting required String
return: division instance (for chaining)

enabled

Check if setting is truthy.

parameters: setting required String
return: Boolean value

disabled

Check if setting is falsy.

parameters: setting required String
return: Boolean value

run

Run configured cluster process. action function is invoked in Master instance scope.

NOTE: This could be called only once in whole application life.

parameters: action optional Function
return: Master instance

Master class

Master is returned when you call run method from Division and it is also set as a scope for callback function of this method.

[ Attributes | Methods | Events ]

Attributes

[ pid | startup ]

pid

Constant String
Contain current master process ID (PID number)

startup

Constant Number
Contain timestamp number indicating start of cluster process.

Methods

[ addSignalListener | increase | decrease | restart | close | destroy | kill | maintenance | publish | broadcast ]

addSignalListener

Listen for process event or POSIX signal and firing callback in Master scope.

parameters: event_or_signal required String, callback required Function
return: Master instance (for chaining)

increase

Increase number of active workers by amount; by default amount is equal 1.

parameters: amount optional Number
return: Master instance (for chaining)

decrease

Decrease number of active workers by amount; by default amount is equal 1.

parameters: amount optional Number
return: Master instance (for chaining)

restart

Gracefully restarts all workers.

return: Master instance (for chaining)

close

Gracefully close all workers.

return: Master instance (for chaining)

destroy

Forcefully destroy all workers.

return: Master instance (for chaining)

kill

Send POSIX signal to all workers; by default signal is equal SIGTERM.

parameters: signal optional String
return: Master instance (for chaining)

maintenance

Maintain active workers amount, re-spawning or closing if necessary.

return: Master instance (for chaining)

publish

Send event message to Worker process with specified id.

parameters: id required Number, event required String, parameters... optional list of mixed values
return: Master instance (for chaining)

broadcast

Send event message to all Worker processes.

parameters: event required String, parameters... optional list of mixed values
return: Master instance (for chaining)

Events

Master inherit from Event Emitter and all events (listed below) are called with the Master scope.

[ error | increase | decrease | restart | close | destroy | fork | online | listening | disconnect | exit ]

error

Event emitted when some error occurred.

Callback parameters: error String containing error stack trace.

increase

Event emitted when number of workers is going to be increased.

Callback parameters: amount Number of workers that need to be added to current group.

decrease

Event emitted when number of workers is going to be decreased.

Callback parameters: amount Number of workers that need to be removed from current group.

restart

Event emitted when worker processes are going to be restarted.

close

Event emitted when cluster process is going to be gracefully closed.

destroy

Event emitted when cluster process is going to be forcefully destroyed.

fork

Event emitted when new cluster worker process was forked.

Callback parameters: worker Worker instance for newly created worker.

online

Event emitted when new cluster worker process is ready to do his job.

Callback parameters: worker Worker instance for newly created worker.

listening

Event emitted when worker start listening for incoming connections.

Callback parameters: worker Worker instance for this worker, address Object describing address on which worker is listening.

disconnect

Event emitted when worker process stop listen for incoming connections.

Callback parameters: worker Worker instance for disconnected worker.

exit

Event emitted when worker process has quit.

Callback parameters: worker Worker instance for closed worker, code Number with exit status code, signal String with POSIX signal (eg. SIGKILL) which caused that process exited.

Worker class

Worker is returned in few events emitted from Master instance.

[ Attributes | Methods | Events ]

Attributes

[ id | pid | startup | status ]

id

Constant Number
Contain current cluster worker ID number.

pid

Constant String
Contain current worker process ID (PID) number.

startup

Constant Number
Contain timestamp number indicating start of Worker process.

status

Read-Only String
Contain current Worker status. Available statuses:

  • none - when worker process is creating
  • online - when worker process is successfully forked
  • listening - when worker process is listening for connections
  • disconnected - when worker process is disconnected (properly closed)
  • dead - when worker process died (killed by error or signal)

Methods

[ close | kill | publish ]

close

Gracefully close worker. But if worker doesn't close within timeout (in ms), then it would be forcefully killed;
by default timeout is equal 2000.

parameters: timeout optional Number, decrease optional Boolean
return: Worker instance (for chaining)

kill

Send POSIX signal to that worker; by default signal is equal SIGTERM.

parameters: signal optional String
return: Worker instance (for chaining)

publish

Send message object (with two fields: event and parameters) to worker process.
To receive messages you must have specified message listener in your application:

process.on("message", function (msg) {
  var event = msg.event, parameters = msg.parameters;

  // do something with your message
});

parameters: event required String, parameters... optional list of mixed values
return: Worker instance (for chaining)

Events

Worker inherit from Event Emitter and all events (listed below) are called with the Worker scope.

[ close | kill | publish ]

close

Event emitted when worker process is going to be gracefully closed.

kill

Event emitted when worker process is going to receive POSIX signal.

Callback parameters: signal String with the name of signal.

publish

Event emitted when worker process is going to receive message object.

Callback parameters: event String with the event name, parameters Array of mixed values.

npm loves you