pidfiles.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*!
  2. * Cluster - pidfiles
  3. * Copyright (c) 2011 LearnBoost <dev@learnboost.com>
  4. * MIT Licensed
  5. */
  6. /**
  7. * Module dependencies.
  8. */
  9. var fs = require('fs')
  10. , mkdir = require('mkdirp').mkdirp;
  11. /**
  12. * Save pidfiles to the given `dir` or `./pids`.
  13. *
  14. * Examples:
  15. *
  16. * // save to ./pids
  17. * cluster(server)
  18. * .use(cluster.pidfiles())
  19. * .listen(3000);
  20. *
  21. * // save to /tmp
  22. * cluster(server)
  23. * .use(cluster.pidfiles('/tmp'))
  24. * .listen(3000);
  25. *
  26. * // save to /var/run/node
  27. * cluster(server)
  28. * .use(cluster.logger('/var/run/node'))
  29. * .listen(3000);
  30. *
  31. * @param {String} dir
  32. * @return {Function}
  33. * @api public
  34. */
  35. module.exports = function(dir){
  36. return function(master){
  37. dir = master.pidfiles = master.resolve(dir || 'pids');
  38. // augment master
  39. master.pidof = function(name){
  40. var dir = master.pidfiles
  41. , path = dir + '/' + name + '.pid'
  42. , pid = fs.readFileSync(path, 'ascii');
  43. return parseInt(pid, 10);
  44. };
  45. master.workerpids = function(){
  46. var dir = master.pidfiles;
  47. return fs.readdirSync(dir).filter(function(file){
  48. return file.match(/^worker\./);
  49. }).map(function(file){
  50. return parseInt(fs.readFileSync(dir + '/' + file, 'ascii'), 10);
  51. });
  52. };
  53. mkdir(dir, 0755, function(err){
  54. if (err) throw err;
  55. // save worker pids
  56. master.on('worker', function(worker){
  57. var path = dir + '/worker.' + worker.id + '.pid';
  58. fs.writeFile(path, worker.proc.pid.toString(), 'ascii', function(err){
  59. if (err) throw err;
  60. master.emit('worker pidfile');
  61. });
  62. });
  63. master.on('listening', function(){
  64. // save master pid
  65. fs.writeFile(dir + '/master.pid', process.pid.toString(), 'ascii', function(err){
  66. if (err) throw err;
  67. master.emit('pidfile');
  68. });
  69. });
  70. });
  71. }
  72. };