WatchDog.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict'
  2. const debug = require('debug')('interactor:watchdog')
  3. const child = require('child_process')
  4. const path = require('path')
  5. const RECONNECT_TENTATIVES_BEFORE_RESURRECT = 6
  6. process.env.PM2_AGENT_ONLINE = true
  7. module.exports = class WatchDog {
  8. static start (p) {
  9. this.pm2_binary_path = p.pm2_binary_path
  10. this.ipm2 = p.conf.ipm2
  11. this.relaunching = false
  12. this.autoDumpTime = 5 * 60 * 1000
  13. /**
  14. * Handle PM2 connection state changes
  15. */
  16. this.ipm2.on('ready', _ => {
  17. debug('Connected to PM2')
  18. this.relaunching = false
  19. this.autoDump()
  20. })
  21. debug('Launching')
  22. this.reconnect_tentatives = 0
  23. this.ipm2.on('reconnecting', _ => {
  24. debug('PM2 is disconnected - Relaunching PM2')
  25. if (this.dump_interval) {
  26. clearInterval(this.dump_interval)
  27. }
  28. if (this.reconnect_tentatives++ >= RECONNECT_TENTATIVES_BEFORE_RESURRECT &&
  29. this.relaunching === false) {
  30. this.relaunching = true
  31. this.resurrect()
  32. }
  33. })
  34. }
  35. static stop() {
  36. clearInterval(this.dump_interval)
  37. }
  38. static resurrect () {
  39. debug(`Trying to launch PM2: ${path.resolve(__dirname, '../../../../bin/pm2')}`)
  40. child.exec(`node ${this.pm2_binary_path} resurrect`, (err, sto, ste) => {
  41. if (err) console.error(err)
  42. console.log(sto, ste)
  43. this.reconnect_tentatives = 0
  44. setTimeout(_ => {
  45. this.relaunching = false
  46. }, 10 * 1000)
  47. })
  48. }
  49. static autoDump () {
  50. this.dump_interval = setInterval(_ => {
  51. if (this.relaunching === true) return
  52. this.ipm2.pm2Interface.dump(function (err) {
  53. return err ? debug('Error when dumping', err) : debug('PM2 process list dumped')
  54. })
  55. }, this.autoDumpTime)
  56. }
  57. }