-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsignals-handler.js
More file actions
96 lines (80 loc) · 1.99 KB
/
signals-handler.js
File metadata and controls
96 lines (80 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
const psTree = require('ps-tree');
module.exports = class SignalsHandler {
terminating = false;
pids = [];
constructor(timeout, logger) {
this.timeout = timeout;
this.logger = logger;
process.on('SIGTERM', this.shutdown.bind(this));
process.on('SIGINT', this.shutdown.bind(this));
}
removeExitedProcessesIds() {
this.pids = this.pids.filter(pid => {
try {
process.kill(pid, 0)
return true;
} catch (e) {
return false;
}
})
}
async forceShutdown() {
if (!this.pids.length) {
return;
}
const rootPid = this.pids[0];
return new Promise((resolve, reject) => {
psTree(rootPid, async (err, children) => {
try {
for (const {PID} of children) {
this.logger.debug('KILL', PID);
try {
process.kill(PID, 'SIGKILL');
} catch (e) {
}
}
this.logger.debug('KILL', rootPid);
try {
process.kill(rootPid, 'SIGKILL');
} catch (e) {
}
this.removeExitedProcessesIds();
await this.forceShutdown();
resolve();
} catch (e) {
reject(e);
}
})
});
}
shutdown() {
if (this.terminating) {
return;
}
this.logger.debug('SHUTDOWN', this.timeout)
this.terminating = true;
psTree(process.pid, (err, children) => {
for (const {PID} of children) {
this.pids.push(PID);
try {
process.kill(PID, 'SIGTERM');
} catch (e) {
}
}
});
const shutdownTime = new Date();
const interval = setInterval(async () => {
const force = Date.now() - shutdownTime >= this.timeout * 1000
this.removeExitedProcessesIds();
if (force) {
this.logger.debug('FORCE SHUTDOWN')
await this.forceShutdown();
}
if (!this.pids.length) {
clearInterval(interval);
process.exit(0);
}
}, 500)
}
}