test.restart.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * Module dependencies.
  3. */
  4. var cluster = require('../')
  5. , http = require('http')
  6. , fs = require('fs');
  7. require('./common');
  8. var server = http.createServer(function(req, res){
  9. setTimeout(function(){
  10. res.writeHead(200);
  11. res.end('Hello World');
  12. }, 1000);
  13. });
  14. cluster = cluster(server)
  15. .set('workers', 2)
  16. .use(cluster.pidfiles())
  17. .listen(3002);
  18. var a, b
  19. , options = { host: 'localhost', port: 3002 };
  20. function getPID(name) {
  21. var pid = fs.readFileSync(__dirname + '/pids/' + name, 'ascii');
  22. return parseInt(pid, 10);
  23. }
  24. function movePID(name) {
  25. var pid = getPID(name);
  26. fs.writeFileSync(__dirname + '/pids/old.' + name, pid.toString(), 'ascii');
  27. }
  28. if (cluster.isChild) {
  29. cluster.on('restart', function(){
  30. http.get(options, function(res){
  31. res.statusCode.should.equal(200);
  32. var a = getPID('old.worker.0.pid')
  33. , b = getPID('old.worker.1.pid');
  34. a.should.not.equal(getPID('worker.0.pid'));
  35. b.should.not.equal(getPID('worker.1.pid'));
  36. cluster.close();
  37. });
  38. });
  39. } else {
  40. var pending = 2;
  41. cluster.on('worker pidfile', function(){
  42. --pending || (function(){
  43. movePID('worker.0.pid')
  44. movePID('worker.1.pid');
  45. // issue some requests
  46. var n = 20
  47. , pending = n;
  48. while (n--) {
  49. http.get(options, function(res){
  50. res.statusCode.should.equal(200);
  51. --pending || cluster.restart();
  52. });
  53. }
  54. })();
  55. });
  56. }