diff --git a/lib/util/lifecycle.js b/lib/util/lifecycle.js index 23887dab..2e68ffc8 100644 --- a/lib/util/lifecycle.js +++ b/lib/util/lifecycle.js @@ -6,6 +6,7 @@ var _ = require('lodash') function Lifecycle() { this.observers = [] + this.ending = false process.on('SIGINT', this.graceful.bind(this)) process.on('SIGTERM', this.graceful.bind(this)) } @@ -20,24 +21,36 @@ Lifecycle.prototype.share = function(name, emitter, options) { if (opts.end) { emitter.on('end', function() { - log.fatal('%s ended; we shall share its fate', name) - this.fatal() + 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) { - log.fatal('%s had an error', name, err.stack) - this.fatal() + 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() })) @@ -49,6 +62,7 @@ Lifecycle.prototype.graceful = function() { Lifecycle.prototype.fatal = function() { log.fatal('Shutting down due to fatal error') + this.ending = true process.exit(1) }