diff --git a/src/index.js b/src/index.js index 985c4ef..03afe77 100644 --- a/src/index.js +++ b/src/index.js @@ -6,6 +6,7 @@ let metrics; let readinessChecks = []; let healthChecks = []; +let isShuttingDown = false; const prometheusContentType = 'text/plain; version=0.0.4'; @@ -38,6 +39,10 @@ const getMiddleware = () => (req, res, next) => { return Promise.resolve().then(() => res.sendStatus(200)); } + if (isShuttingDown) { + return Promise.resolve().then(() => res.sendStatus(500)); + } + const promisedChecks = readinessChecks.map((check) => new Promise((resolve, reject) => doReadinessCheck(check) .then(resolve) @@ -85,10 +90,16 @@ const getMiddleware = () => (req, res, next) => { return next(); }; +// Listen for requests to kill the process and initiate the safe shutdown. +process.on('SIGTERM', () => { + isShuttingDown = true; +}); + const reset = () => { metrics = undefined; readinessChecks = []; healthChecks = []; + isShuttingDown = false; }; module.exports = { diff --git a/test/index.js b/test/index.js index 07cf39d..0a07471 100644 --- a/test/index.js +++ b/test/index.js @@ -57,8 +57,8 @@ describe('bw-monitoring', () => { it('should return 500 if any check fails', (done) => { mon.addReadinessCheck({ name: 'bob', check: (ok) => ok() }); mon.addReadinessCheck({ name: 'bob2', check: (ok, warning) => warning() }); - mon.addReadinessCheck({ name: 'bob2', check: (ok, warning, critical) => critical() }); - mon.addReadinessCheck({ name: 'bob2', check: (ok, warning, critical, unknown) => unknown() }); + mon.addReadinessCheck({ name: 'bob3', check: (ok, warning, critical) => critical() }); + mon.addReadinessCheck({ name: 'bob4', check: (ok, warning, critical, unknown) => unknown() }); const mid = mon.getMiddleware(); mid(req, res, next) .then(() => { @@ -66,6 +66,25 @@ describe('bw-monitoring', () => { done(); }); }); + + it('should return 500 after receiving SIGTERM', (done) => { + mon.addReadinessCheck({ name: 'bob', check: (ok) => ok() }); + const mid = mon.getMiddleware(); + mid(req, res, next) + .then(() => { + assert(res.sendStatus.calledWith(200)); + }) + .then(() => { + process.once('SIGTERM', () => { + mid(req, res, next) + .then(() => { + assert(res.sendStatus.calledWith(500)); + done(); + }); + }); + }); + process.kill(process.pid, 'SIGTERM'); + }); }); describe('/checkz endpoint', () => {