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