Skip to content

Commit 9c0a1b8

Browse files
Olegassam-github
authored andcommitted
cluster: wait on servers closing before disconnect
Before this, cluster behaves not the way it is documented. When disconnect is triggered, worker must wait for every server is closed before doing disconnect actually. Reviewed-By: Sam Roberts <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> PR-URL: #1400 Fixes: #1305
1 parent d9ddd7d commit 9c0a1b8

File tree

2 files changed

+58
-2
lines changed

2 files changed

+58
-2
lines changed

lib/cluster.js

+16-2
Original file line numberDiff line numberDiff line change
@@ -627,12 +627,26 @@ function workerInit() {
627627

628628
Worker.prototype.disconnect = function() {
629629
this.suicide = true;
630+
var waitingHandles = 0;
631+
632+
function checkRemainingHandles() {
633+
waitingHandles--;
634+
if (waitingHandles === 0) {
635+
process.disconnect();
636+
}
637+
}
638+
630639
for (var key in handles) {
631640
var handle = handles[key];
632641
delete handles[key];
633-
handle.close();
642+
waitingHandles++;
643+
handle.owner.close(checkRemainingHandles);
634644
}
635-
process.disconnect();
645+
646+
if (waitingHandles === 0) {
647+
process.disconnect();
648+
}
649+
636650
};
637651

638652
Worker.prototype.destroy = function() {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
'use strict';
2+
3+
var common = require('../common');
4+
var assert = require('assert');
5+
var cluster = require('cluster');
6+
var net = require('net');
7+
8+
if (cluster.isWorker) {
9+
net.createServer(function(socket) {
10+
// Wait for any data, then close connection
11+
socket.on('data', socket.end.bind(socket));
12+
}).listen(common.PORT, common.localhostIPv4);
13+
} else if (cluster.isMaster) {
14+
15+
var connectionDone;
16+
var ok;
17+
18+
// start worker
19+
var worker = cluster.fork();
20+
21+
// Disconnect worker when it is ready
22+
worker.once('listening', function() {
23+
net.createConnection(common.PORT, common.localhostIPv4, function() {
24+
var socket = this;
25+
worker.disconnect();
26+
setTimeout(function() {
27+
socket.write('.');
28+
connectionDone = true;
29+
}, 1000);
30+
});
31+
});
32+
33+
// Check worker events and properties
34+
worker.once('disconnect', function() {
35+
assert.ok(connectionDone, 'disconnect should occur after socket close');
36+
ok = true;
37+
});
38+
39+
process.once('exit', function() {
40+
assert.ok(ok);
41+
});
42+
}

0 commit comments

Comments
 (0)