joyent/node — pull request #1879 by visionmedia (2011-10-13 14:09:45+00:00)
Title: refactored cluster module

- improved extensibility
- added -n, --workers
- added -r, --require
- added worker incr / decr functionality
- added worker removal functionality
- refactored / exposed worker spawning
- delegate arbitrary messages
- message master when listening

The main goal of this commit is to make cluster.js
extensible. not to make assumptions with re-spawning
logic etc, but to facilitate it. logging and other
related tasks are then delegated as well.

To "plugin" in master logic you use `--require`, as `$ node cluster`
will not exec the script for the master process. ex:

$ node cluster app

vs:

$ node cluster -r master app

where _./master.js_ contains `process.on()` event
listeners for logging, logic for re-spawning etc.

I'm not 100% sold on `--require`, but it would be more
abstract than cluster-specific module loading etc.
The one benefit of doing something cluster-specific,
is that you could truly encapsulate cluster "plugins"
which may contain both master and worker logic. For example
suppose you have a plugin _./stats.js_ which may aggregate/relay/display
request/connection statistics etc in master, and send messages to master
from the worker(s). perhaps it would look something like this:

```js
exports.master = function(){
process.on('message', function(){ // socket.io UI blah blah })
};
```

```js
exports.worker = function(server){
server.on('connection', function(){
... process.send(whatever)
});
};
```

these `--require`d scripts would be useful as mentioned for restart logic
and other tasks as well, ex:

```js
process.on('worker killed', function(worker){
console.log(' worker %d killed', worker.id);
require('cluster').spawn();
});
```

or things like REPLs which can manipulate the cluster with the
methods I've exposed in this patch.

cheers!