Repository navigation
Expand file tree
/
Copy pathprocutil.js
More file actions
94 lines (76 loc) · 1.98 KB
/
Copy pathprocutil.js
File metadata and controls
94 lines (76 loc) · 1.98 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
var util = require('util')
var cp = require('child_process')
var Promise = require('bluebird')
var log = require('./logger').createLogger('util:procutil')
function ExitError(code) {
Error.call(this)
this.name = 'ExitError'
this.code = code
this.message = util.format('Exit code "%d"', code)
Error.captureStackTrace(this, ExitError)
}
util.inherits(ExitError, Error)
// Export
module.exports.ExitError = ExitError
// Export
module.exports.fork = function(filename, args) {
log.info('Forking "%s %s"', filename, args.join(' '))
var resolver = Promise.defer()
var proc = cp.fork.apply(cp, arguments)
function sigintListener() {
proc.kill('SIGINT')
}
function sigtermListener() {
proc.kill('SIGTERM')
}
process.on('SIGINT', sigintListener)
process.on('SIGTERM', sigtermListener)
proc.on('error', function(err) {
resolver.reject(err)
proc.kill()
})
proc.on('exit', function(code, signal) {
if (signal) {
resolver.resolve(code)
}
else if (code > 0 && code !== 130 && code !== 143) {
resolver.reject(new ExitError(code))
}
else {
resolver.resolve(code)
}
})
return resolver.promise.cancellable()
.finally(function() {
process.removeListener('SIGINT', sigintListener)
process.removeListener('SIGTERM', sigtermListener)
})
.catch(Promise.CancellationError, function() {
return new Promise(function(resolve) {
proc.on('exit', function() {
resolve()
})
proc.kill()
})
})
}
// Export
module.exports.gracefullyKill = function(proc, timeout) {
function killer(signal) {
var deferred = Promise.defer()
function onExit() {
deferred.resolve()
}
proc.once('exit', onExit)
proc.kill(signal)
return deferred.promise.finally(function() {
proc.removeListener('exit', onExit)
})
}
return killer('SIGTERM')
.timeout(timeout)
.catch(function() {
return killer('SIGKILL')
.timeout(timeout)
})
}