forked from openstf/stf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlifecycle.js
73 lines (59 loc) · 1.41 KB
/
lifecycle.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
var Promise = require('bluebird')
var logger = require('./logger')
var log = logger.createLogger('util:lifecycle')
var _ = require('lodash')
function Lifecycle() {
this.observers = []
this.ending = false
process.on('SIGINT', this.graceful.bind(this))
process.on('SIGTERM', this.graceful.bind(this))
}
Lifecycle.prototype.share = function(name, emitter, options) {
var opts = _.assign({
end: true
, error: true
}
, options
)
if (opts.end) {
emitter.on('end', function() {
if (!this.ending) {
log.fatal('%s ended; we shall share its fate', name)
this.fatal()
}
}.bind(this))
}
if (opts.error) {
emitter.on('error', function(err) {
if (!this.ending) {
log.fatal('%s had an error', name, err.stack)
this.fatal()
}
}.bind(this))
}
if (emitter.end) {
this.observe(function() {
emitter.end()
})
}
return emitter
}
Lifecycle.prototype.graceful = function() {
log.info('Winding down for graceful exit')
this.ending = true
var wait = Promise.all(this.observers.map(function(fn) {
return fn()
}))
return wait.then(function() {
process.exit(0)
})
}
Lifecycle.prototype.fatal = function() {
log.fatal('Shutting down due to fatal error')
this.ending = true
process.exit(1)
}
Lifecycle.prototype.observe = function(promise) {
this.observers.push(promise)
}
module.exports = new Lifecycle()