Gathering detailed insights and metrics for @godaddy/terminus
Gathering detailed insights and metrics for @godaddy/terminus
Gathering detailed insights and metrics for @godaddy/terminus
Gathering detailed insights and metrics for @godaddy/terminus
Graceful shutdown and Kubernetes readiness / liveness checks for any Node.js HTTP applications
npm install @godaddy/terminus
57.1
Supply Chain
99.6
Quality
83.2
Maintenance
100
Vulnerability
100
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,848 Stars
172 Commits
96 Forks
28 Watching
13 Branches
59 Contributors
Updated on 15 Nov 2024
JavaScript (96.89%)
TypeScript (2.71%)
Dockerfile (0.4%)
Cumulative downloads
Total Downloads
Last day
-8%
31,441
Compared to previous day
Last week
4.6%
180,949
Compared to previous week
Last month
1.1%
775,432
Compared to previous month
Last year
14.9%
8,561,364
Compared to previous year
1
Adds graceful shutdown and Kubernetes readiness / liveness checks for any HTTP applications.
Install via npm:
1npm i @godaddy/terminus --save
1const http = require('http'); 2const { createTerminus } = require('@godaddy/terminus'); 3 4function onSignal () { 5 console.log('server is starting cleanup'); 6 return Promise.all([ 7 // your clean logic, like closing database connections 8 ]); 9} 10 11function onShutdown () { 12 console.log('cleanup finished, server is shutting down'); 13} 14 15function healthCheck ({ state }) { 16 // `state.isShuttingDown` (boolean) shows whether the server is shutting down or not 17 return Promise.resolve( 18 // optionally include a resolve value to be included as 19 // info in the health check response 20 ) 21} 22 23const server = http.createServer((request, response) => { 24 response.end( 25 `<html> 26 <body> 27 <h1>Hello, World!</h1> 28 </body> 29 </html>` 30 ); 31}) 32 33const options = { 34 // health check options 35 healthChecks: { 36 '/healthcheck': healthCheck, // a function accepting a state and returning a promise indicating service health, 37 verbatim: true, // [optional = false] use object returned from /healthcheck verbatim in response, 38 __unsafeExposeStackTraces: true // [optional = false] return stack traces in error response if healthchecks throw errors 39 }, 40 caseInsensitive, // [optional] whether given health checks routes are case insensitive (defaults to false) 41 42 statusOk, // [optional = 200] status to be returned for successful healthchecks 43 statusOkResponse, // [optional = { status: 'ok' }] status response to be returned for successful healthchecks 44 statusError, // [optional = 503] status to be returned for unsuccessful healthchecks 45 statusErrorResponse, // [optional = { status: 'error' }] status response to be returned for unsuccessful healthchecks 46 47 // cleanup options 48 timeout: 1000, // [optional = 1000] number of milliseconds before forceful exiting 49 signal, // [optional = 'SIGTERM'] what signal to listen for relative to shutdown 50 signals, // [optional = []] array of signals to listen for relative to shutdown 51 useExit0, // [optional = false] instead of sending the received signal again without beeing catched, the process will exit(0) 52 sendFailuresDuringShutdown, // [optional = true] whether or not to send failure (503) during shutdown 53 beforeShutdown, // [optional] called before the HTTP server starts its shutdown 54 onSignal, // [optional] cleanup function, returning a promise (used to be onSigterm) 55 onShutdown, // [optional] called right before exiting 56 onSendFailureDuringShutdown, // [optional] called before sending each 503 during shutdowns 57 58 // both 59 logger // [optional] logger function to be called with errors. Example logger call: ('error happened during shutdown', error). See terminus.js for more details. 60}; 61 62createTerminus(server, options); 63 64server.listen(PORT || 3000);
1const http = require('http'); 2const { createTerminus, HealthCheckError } = require('@godaddy/terminus'); 3 4createTerminus(server, { 5 healthChecks: { 6 '/healthcheck': async function () { 7 const errors = [] 8 return Promise.all([ 9 // all your health checks goes here 10 ].map(p => p.catch((error) => { 11 // silently collecting all the errors 12 errors.push(error) 13 return undefined 14 }))).then(() => { 15 if (errors.length) { 16 throw new HealthCheckError('healthcheck failed', errors) 17 } 18 }) 19 } 20 } 21});
1const http = require("http"); 2const express = require("express"); 3const { createTerminus, HealthCheckError } = require('@godaddy/terminus'); 4const app = express(); 5 6app.get("/", (req, res) => { 7 res.send("ok"); 8}); 9 10const server = http.createServer(app); 11 12function healthCheck({ state }) { 13 return Promise.resolve(); 14} 15 16const options = { 17 healthChecks: { 18 "/healthcheck": healthCheck, 19 verbatim: true, 20 __unsafeExposeStackTraces: true, 21 }, 22 headers: { 23 "Access-Control-Allow-Origin": "*", 24 "Access-Control-Allow-Methods": "OPTIONS, POST, GET", 25 }, 26}; 27 28terminus.createTerminus(server, options); 29 30server.listen(3000);
1const http = require('http'); 2const express = require('express'); 3const { createTerminus } = require('@godaddy/terminus'); 4const app = express(); 5 6app.get('/', (req, res) => { 7 res.send('ok'); 8}); 9 10const server = http.createServer(app); 11 12const options = { 13 // opts 14}; 15 16createTerminus(server, options); 17 18server.listen(PORT || 3000);
1const http = require('http'); 2const Koa = require('koa'); 3const { createTerminus } = require('@godaddy/terminus'); 4const app = new Koa(); 5 6const server = http.createServer(app.callback()); 7 8const options = { 9 // opts 10}; 11 12createTerminus(server, options); 13 14server.listen(PORT || 3000);
If you want to use (cluster
)[https://nodejs.org/api/cluster.html] to use more than one CPU, you need to use terminus
per worker.
This is heavily inspired by https://medium.com/@gaurav.lahoti/graceful-shutdown-of-node-js-workers-dd58bbff9e30.
See example/express.cluster.js
.
When Kubernetes or a user deletes a Pod, Kubernetes will notify it and wait for gracePeriod
seconds before killing it.
During that time window (30 seconds by default), the Pod is in the terminating
state and will be removed from any Services by a controller.
The Pod itself needs to catch the SIGTERM
signal and start failing any readiness probes.
If the ingress controller you use route via the Service, it is not an issue for your case. At the time of this writing, we use the nginx ingress controller which routes traffic directly to the Pods.
During this time, it is possible that load-balancers (like the nginx ingress controller) don't remove the Pods "in time", and when the Pod dies, it kills live connections.
To make sure you don't lose any connections, we recommend delaying the shutdown with the number of milliseconds that's defined by the readiness probe in your deployment configuration.
To help with this, terminus exposes an option called beforeShutdown
that takes any Promise-returning function.
Also it makes sense to use the useExit0 = true
option to signal Kubernetes that the container exited gracefully.
Otherwise APM's will send you alerts, in some cases.
1function beforeShutdown () { 2 // given your readiness probes run every 5 second 3 // may be worth using a bigger number so you won't 4 // run into any race conditions 5 return new Promise(resolve => { 6 setTimeout(resolve, 5000) 7 }) 8} 9createTerminus(server, { 10 beforeShutdown, 11 useExit0: true 12})
Due to inherent platform limitations, terminus
has limited support for Windows.
You can expect SIGINT
to work, as well as SIGBREAK
and to some extent SIGHUP
.
However SIGTERM
will never work on Windows because killing a process in the task manager is unconditional, i.e., there's no way for an application to detect or prevent it.
Here's some relevant documentation from libuv
to learn more about what SIGINT
, SIGBREAK
etc. signify and what's supported on Windows - http://docs.libuv.org/en/v1.x/signal.html.
Also, see https://nodejs.org/api/process.html#process_signal_events.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
packaging workflow detected
Details
Reason
security policy file detected
Details
Reason
SAST tool detected but not run on all commits
Details
Reason
Found 10/17 approved changesets -- score normalized to 5
Reason
dependency not pinned by hash detected -- score normalized to 1
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
19 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More