Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cluster: fix error on worker disconnect/destroy #32793

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/internal/cluster/child.js
Expand Up @@ -228,16 +228,23 @@ function _disconnect(masterInitiated) {

// Extend generic Worker with methods specific to worker processes.
Worker.prototype.disconnect = function() {
_disconnect.call(this);
if (![ 'disconnecting', 'destroying' ].includes(this.state)) {
himself65 marked this conversation as resolved.
Show resolved Hide resolved
this.state = 'disconnecting';
_disconnect.call(this);
}

return this;
};

Worker.prototype.destroy = function() {
this.exitedAfterDisconnect = true;
if (this.state === 'destroying')
return;

this.exitedAfterDisconnect = true;
if (!this.isConnected()) {
process.exit(0);
} else {
this.state = 'destroying';
send({ act: 'exitedAfterDisconnect' }, () => process.disconnect());
process.once('disconnect', () => process.exit(0));
}
Expand Down
48 changes: 48 additions & 0 deletions test/parallel/test-cluster-concurrent-disconnect.js
@@ -0,0 +1,48 @@
'use strict';
himself65 marked this conversation as resolved.
Show resolved Hide resolved

// Ref: https://github.com/nodejs/node/issues/32106

const common = require('../common');

const assert = require('assert');
const cluster = require('cluster');
const os = require('os');

if (cluster.isMaster) {
const workers = [];
const numCPUs = os.cpus().length;
let waitOnline = numCPUs;
for (let i = 0; i < numCPUs; i++) {
const worker = cluster.fork();
workers[i] = worker;
worker.once('online', common.mustCall(() => {
if (--waitOnline === 0)
for (const worker of workers)
if (worker.isConnected())
worker.send(i % 2 ? 'disconnect' : 'destroy');
}));

// These errors can occur due to the nature of the test, we might be trying
// to send messages when the worker is disconnecting.
worker.on('error', (err) => {
assert.strictEqual(err.syscall, 'write');
assert.strictEqual(err.code, 'EPIPE');
});

worker.once('disconnect', common.mustCall(() => {
for (const worker of workers)
if (worker.isConnected())
worker.send('disconnect');
}));

worker.once('exit', common.mustCall((code, signal) => {
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
}));
}
} else {
process.on('message', (msg) => {
if (cluster.worker.isConnected())
cluster.worker[msg]();
});
}