forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandleKillSignals.js
112 lines (97 loc) · 2.34 KB
/
handleKillSignals.js
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const log = require('./log');
const SHUTDOWN_TIMEOUT = 10e3;
let shuttingDown = false;
const teardowns = [];
function isShuttingDown() {
return shuttingDown;
}
/**
* shutdown === the termination handler
* Terminate server on receipt of the specified signal.
* @param {string} signal Signal to terminate on.
*/
async function shutdown(signal, origin) {
if (typeof signal === 'string') {
log.info({
name: 'kill signal',
msg: `Handling signal: ${signal} from ${origin}.`,
});
}
// At the first soft kill signal, we try to shutdown the service gracefully.
if ((signal === 'SIGTERM' || signal === 'SIGINT') && !shuttingDown) {
shuttingDown = true;
log.info({
name: 'kill signal',
msg: `Shutdown server gracefully. ${SHUTDOWN_TIMEOUT}ms before killing it.`,
});
const timer = setTimeout(() => {
log.fatal({
name: 'kill signal',
msg: 'Force shutdown',
});
shutdown();
}, SHUTDOWN_TIMEOUT);
// ASC
const teardownsSorted = teardowns.slice().sort((a, b) => a.nice - b.nice);
// Serial resolution of the teardowns
for (let i = 0; i < teardownsSorted.length; i += 1) {
// eslint-disable-next-line no-await-in-loop
await teardownsSorted[i].callback();
}
clearTimeout(timer);
process.exit(0);
return;
}
process.exit(1);
}
function addTeardown(teardown) {
teardowns.push(teardown);
}
function removeTeardown(teardown) {
const index = teardowns.indexOf(teardown);
teardowns.splice(index, 1);
}
function handleKillSignals() {
// Process on exit and signals.
// https://nodejs.org/api/process.html#process_event_exit
process.on('exit', (code) => {
const msg = `💀 Node stopped with code ${code}`;
if (code === 0) {
log.info({
name: 'kill signal',
msg,
});
} else {
log.fatal({
name: 'kill signal',
msg,
});
}
});
// Removed 'SIGPIPE' from the list - bugz 852598.
[
'SIGHUP',
'SIGINT',
'SIGQUIT',
'SIGILL',
'SIGTRAP',
'SIGABRT',
'SIGBUS',
'SIGFPE',
'SIGUSR1',
'SIGSEGV',
'SIGUSR2',
'SIGTERM',
].forEach((signal) => {
process.on(signal, () => {
shutdown(signal, 'signal');
});
});
}
module.exports = {
handleKillSignals,
isShuttingDown,
shutdown,
addTeardown,
removeTeardown,
};