Browse Source

More cluster event consistency

Regarding discussion in #3198.  Passing the worker as an argument
to an event emitted on the worker is redundant, and an unnecessary
break in consistency vs the events on the ChildProcess objects.

It was removed from 'exit', but 'listening' and others were
overlooked.  This corrects that oversight.
v0.9.1-release
isaacs 13 years ago
parent
commit
3d84c3db25
  1. 60
      doc/api/cluster.markdown
  2. 6
      lib/cluster.js
  3. 30
      test/simple/test-cluster-basic.js

60
doc/api/cluster.markdown

@ -19,7 +19,7 @@ all share server ports.
cluster.fork(); cluster.fork();
} }
cluster.on('exit', function(worker) { cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.pid + ' died'); console.log('worker ' + worker.pid + ' died');
}); });
} else { } else {
@ -77,17 +77,17 @@ When a new worker is forked the cluster module will emit a 'fork' event.
This can be used to log worker activity, and create you own timeout. This can be used to log worker activity, and create you own timeout.
var timeouts = []; var timeouts = [];
var errorMsg = function () { function errorMsg() {
console.error("Something must be wrong with the connection ..."); console.error("Something must be wrong with the connection ...");
}); }
cluster.on('fork', function (worker) { cluster.on('fork', function(worker) {
timeouts[worker.uniqueID] = setTimeout(errorMsg, 2000); timeouts[worker.uniqueID] = setTimeout(errorMsg, 2000);
}); });
cluster.on('listening', function (worker) { cluster.on('listening', function(worker, address) {
clearTimeout(timeouts[worker.uniqueID]); clearTimeout(timeouts[worker.uniqueID]);
}); });
cluster.on('exit', function (worker) { cluster.on('exit', function(worker, code, signal) {
clearTimeout(timeouts[worker.uniqueID]); clearTimeout(timeouts[worker.uniqueID]);
errorMsg(); errorMsg();
}); });
@ -102,7 +102,7 @@ The difference between 'fork' and 'online' is that fork is emitted when the
master tries to fork a worker, and 'online' is emitted when the worker is master tries to fork a worker, and 'online' is emitted when the worker is
being executed. being executed.
cluster.on('online', function (worker) { cluster.on('online', function(worker) {
console.log("Yay, the worker responded after it was forked"); console.log("Yay, the worker responded after it was forked");
}); });
@ -120,7 +120,7 @@ object and the `address` object contains the following connection properties:
`address`, `port` and `addressType`. This is very useful if the worker is listening `address`, `port` and `addressType`. This is very useful if the worker is listening
on more than one address. on more than one address.
cluster.on('listening', function (worker, address) { cluster.on('listening', function(worker, address) {
console.log("A worker is now connected to " + address.address + ":" + address.port); console.log("A worker is now connected to " + address.address + ":" + address.port);
}); });
@ -143,11 +143,14 @@ connections.
## Event: 'exit' ## Event: 'exit'
* `worker` {Worker object} * `worker` {Worker object}
* `code` {Number} the exit code, if it exited normally.
* `signal` {String} the name of the signal (eg. `'SIGHUP'`) that caused
the process to be killed.
When any of the workers die the cluster module will emit the 'exit' event. When any of the workers die the cluster module will emit the 'exit' event.
This can be used to restart the worker by calling `fork()` again. This can be used to restart the worker by calling `fork()` again.
cluster.on('exit', function(worker) { cluster.on('exit', function(worker, code, signal) {
var exitCode = worker.process.exitCode; var exitCode = worker.process.exitCode;
console.log('worker ' + worker.pid + ' died ('+exitCode+'). restarting...'); console.log('worker ' + worker.pid + ' died ('+exitCode+'). restarting...');
cluster.fork(); cluster.fork();
@ -225,14 +228,14 @@ In the cluster all living worker objects are stored in this object by there
callback(cluster.workers[uniqueID]); callback(cluster.workers[uniqueID]);
} }
} }
eachWorker(function (worker) { eachWorker(function(worker) {
worker.send('big announcement to all workers'); worker.send('big announcement to all workers');
}); });
Should you wish to reference a worker over a communication channel, using Should you wish to reference a worker over a communication channel, using
the worker's uniqueID is the easiest way to find the worker. the worker's uniqueID is the easiest way to find the worker.
socket.on('data', function (uniqueID) { socket.on('data', function(uniqueID) {
var worker = cluster.workers[uniqueID]; var worker = cluster.workers[uniqueID];
}); });
@ -285,7 +288,7 @@ This example will echo back all messages from the master:
worker.send('hi there'); worker.send('hi there');
} else if (cluster.isWorker) { } else if (cluster.isWorker) {
process.on('message', function (msg) { process.on('message', function(msg) {
process.send(msg); process.send(msg);
}); });
} }
@ -296,7 +299,7 @@ This function will kill the worker, and inform the master to not spawn a
new worker. The boolean `suicide` lets you distinguish between voluntary new worker. The boolean `suicide` lets you distinguish between voluntary
and accidental exit. and accidental exit.
cluster.on('exit', function (worker) { cluster.on('exit', function(worker, code, signal) {
if (worker.suicide === true) { if (worker.suicide === true) {
console.log('Oh, it was just suicide\' – no need to worry'). console.log('Oh, it was just suicide\' – no need to worry').
} }
@ -324,30 +327,30 @@ that would normally not allow the worker to do any cleanup if needed.
var worker = cluser.fork(); var worker = cluser.fork();
var timeout; var timeout;
worker.on('listening', function () { worker.on('listening', function(address) {
worker.disconnect(); worker.disconnect();
timeout = setTimeout(function () { timeout = setTimeout(function() {
worker.send('force kill'); worker.send('force kill');
}, 2000); }, 2000);
}); });
worker.on('disconnect', function () { worker.on('disconnect', function() {
clearTimeout(timeout); clearTimeout(timeout);
}); });
} else if (cluster.isWorker) { } else if (cluster.isWorker) {
var net = require('net'); var net = require('net');
var server = net.createServer(function (socket) { var server = net.createServer(function(socket) {
// connection never end // connection never end
}); });
server.listen(8000); server.listen(8000);
server.on('close', function () { server.on('close', function() {
// cleanup // cleanup
}); });
process.on('message', function (msg) { process.on('message', function(msg) {
if (msg === 'force kill') { if (msg === 'force kill') {
server.destroy(); server.destroy();
} }
@ -377,15 +380,15 @@ in the master process using the message system:
}, 1000); }, 1000);
// Count requestes // Count requestes
var messageHandler = function (msg) { function messageHandler(msg) {
if (msg.cmd && msg.cmd == 'notifyRequest') { if (msg.cmd && msg.cmd == 'notifyRequest') {
numReqs += 1; numReqs += 1;
} }
}; }
// Start workers and listen for messages containing notifyRequest // Start workers and listen for messages containing notifyRequest
cluster.autoFork(); cluster.autoFork();
Object.keys(cluster.workers).forEach(function (uniqueID) { Object.keys(cluster.workers).forEach(function(uniqueID) {
cluster.workers[uniqueID].on('message', messageHandler); cluster.workers[uniqueID].on('message', messageHandler);
}); });
@ -403,35 +406,30 @@ in the master process using the message system:
### Event: 'online' ### Event: 'online'
* `worker` {Worker object}
Same as the `cluster.on('online')` event, but emits only when the state change Same as the `cluster.on('online')` event, but emits only when the state change
on the specified worker. on the specified worker.
cluster.fork().on('online', function (worker) { cluster.fork().on('online', function() {
// Worker is online // Worker is online
}; };
### Event: 'listening' ### Event: 'listening'
* `worker` {Worker object}
* `address` {Object} * `address` {Object}
Same as the `cluster.on('listening')` event, but emits only when the state change Same as the `cluster.on('listening')` event, but emits only when the state change
on the specified worker. on the specified worker.
cluster.fork().on('listening', function (worker, address) { cluster.fork().on('listening', function(address) {
// Worker is listening // Worker is listening
}; };
### Event: 'disconnect' ### Event: 'disconnect'
* `worker` {Worker object}
Same as the `cluster.on('disconnect')` event, but emits only when the state change Same as the `cluster.on('disconnect')` event, but emits only when the state change
on the specified worker. on the specified worker.
cluster.fork().on('disconnect', function (worker) { cluster.fork().on('disconnect', function() {
// Worker has disconnected // Worker has disconnected
}; };
@ -445,7 +443,7 @@ Emitted by the individual worker instance, when the underlying child process
is terminated. See [child_process event: 'exit'](child_process.html#child_process_event_exit). is terminated. See [child_process event: 'exit'](child_process.html#child_process_event_exit).
var worker = cluster.fork(); var worker = cluster.fork();
worker.on('exit', function (code, signal) { worker.on('exit', function(code, signal) {
if( signal ) { if( signal ) {
console.log("worker was killed by signal: "+signal); console.log("worker was killed by signal: "+signal);
} else if( code !== 0 ) { } else if( code !== 0 ) {

6
lib/cluster.js

@ -184,7 +184,7 @@ if (cluster.isMaster) {
messageHandler.online = function(message, worker) { messageHandler.online = function(message, worker) {
worker.state = 'online'; worker.state = 'online';
debug('Worker ' + worker.process.pid + ' online'); debug('Worker ' + worker.process.pid + ' online');
worker.emit('online', worker); worker.emit('online');
cluster.emit('online', worker); cluster.emit('online', worker);
}; };
@ -213,7 +213,7 @@ if (cluster.isMaster) {
worker.state = 'listening'; worker.state = 'listening';
// Emit listening, now that we know the worker is listening // Emit listening, now that we know the worker is listening
worker.emit('listening', worker, { worker.emit('listening', {
address: message.address, address: message.address,
port: message.port, port: message.port,
addressType: message.addressType addressType: message.addressType
@ -297,7 +297,7 @@ function Worker(customEnv) {
this.process.once('exit', function(exitCode, signalCode) { this.process.once('exit', function(exitCode, signalCode) {
prepareExit(self, 'dead'); prepareExit(self, 'dead');
self.emit('exit', exitCode, signalCode); self.emit('exit', exitCode, signalCode);
cluster.emit('exit', self); cluster.emit('exit', self, exitCode, signalCode);
}); });
this.process.once('disconnect', function() { this.process.once('disconnect', function() {
prepareExit(self, 'disconnected'); prepareExit(self, 'disconnected');

30
test/simple/test-cluster-basic.js

@ -122,14 +122,26 @@ else if (cluster.isMaster) {
checks.worker.events[name] = true; checks.worker.events[name] = true;
//Check argument //Check argument
if (name == 'exit') { checks.worker.equal[name] = (worker === this);
checks.worker.equal[name] = (
worker.process.exitCode === arguments[0] && switch (name) {
worker.process.signalCode === arguments[1] && case 'exit':
worker === this assert.equal(arguments[0], worker.process.exitCode);
); assert.equal(arguments[1], worker.process.signalCode);
} else { assert.equal(arguments.length, 2);
checks.worker.equal[name] = worker === arguments[0]; break;
case 'listening':
assert.equal(arguments.length, 1);
var expect = { address: '127.0.0.1',
port: common.PORT,
addressType: 4 };
assert.deepEqual(arguments[0], expect);
break;
default:
assert.equal(arguments.length, 0);
break;
} }
}); });
}); });
@ -145,7 +157,7 @@ else if (cluster.isMaster) {
//Check cluster event arguments //Check cluster event arguments
forEach(checks.cluster.equal, function(check, name) { forEach(checks.cluster.equal, function(check, name) {
assert.ok(check, 'The cluster event "' + name + '" did not emit ' + assert.ok(check, 'The cluster event "' + name + '" did not emit ' +
'with corrent argument'); 'with correct argument');
}); });
//Check worker states //Check worker states

Loading…
Cancel
Save