-
Notifications
You must be signed in to change notification settings - Fork 29.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
cluster: wait for all servers closing before disconnect
Fix for iojs/io,js#1305 Before this, cluster bahaves not the way it is docummented Then disconnect is triggered, worker must wait for every server is closed before doing disconnect actually. See test case and discussion in the above mentioned issue
- Loading branch information
Showing
2 changed files
with
79 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
var common = require('../common'); | ||
var assert = require('assert'); | ||
var cluster = require('cluster'); | ||
var net = require('net'); | ||
|
||
if (cluster.isWorker) { | ||
net.createServer(function(socket) { | ||
// Wait for any data, then close connection | ||
socket.on('data', socket.end.bind(socket)); | ||
}).listen(common.PORT, common.localhostIPv4); | ||
} else if (cluster.isMaster) { | ||
|
||
var connectionDone; | ||
var checks = { | ||
disconnectedOnClientsEnd: false, | ||
workerDied: false | ||
}; | ||
|
||
// helper function to check if a process is alive | ||
var alive = function(pid) { | ||
try { | ||
process.kill(pid, 0); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
}; | ||
|
||
// start worker | ||
var worker = cluster.fork(); | ||
|
||
// Disconnect worker when it is ready | ||
worker.once('listening', function() { | ||
net.createConnection(common.PORT, common.localhostIPv4, function() { | ||
var socket = this; | ||
setTimeout(function() { | ||
worker.disconnect(); | ||
setTimeout(function() { | ||
socket.write('.'); | ||
connectionDone = true; | ||
}, 1000); | ||
}, 1000); | ||
}); | ||
}); | ||
|
||
// Check worker events and properties | ||
worker.once('disconnect', function() { | ||
checks.disconnectedOnClientsEnd = connectionDone; | ||
}); | ||
|
||
// Check that the worker died | ||
worker.once('exit', function() { | ||
checks.workerDied = !alive(worker.process.pid); | ||
process.nextTick(function() { | ||
process.exit(0); | ||
}); | ||
}); | ||
|
||
process.once('exit', function() { | ||
assert.ok(checks.disconnectedOnClientsEnd, 'The worker disconnected before all clients are ended'); | ||
assert.ok(checks.workerDied, 'The worker did not die'); | ||
}); | ||
} |