Giter Club home page Giter Club logo

terminus's Introduction

Join Slack

Build Status

Greenkeeper badge

terminus

Adds graceful shutdown and Kubernetes readiness / liveness checks for any HTTP applications.

Installation

Install via npm:

$ npm i @godaddy/terminus --save

Usage

const http = require('http');
const { createTerminus } = require('@godaddy/terminus');

function onSignal () {
  console.log('server is starting cleanup');
  return Promise.all([
    // your clean logic, like closing database connections
  ]);
}

function onShutdown () {
  console.log('cleanup finished, server is shutting down');
}

function healthCheck () {
  return Promise.resolve(
    // optionally include a resolve value to be included as
    // info in the health check response
  )
}

const server = http.createServer((request, response) => {
  response.end(
    `<html>
      <body>
        <h1>Hello, World!</h1>
       </body>
     </html>`
   );
})

const options = {
  // health check options
  healthChecks: {
    '/healthcheck': healthCheck,    // a function returning a promise indicating service health,
    verbatim: true // [optional = false] use object returned from /healthcheck verbatim in response
  },
  caseInsensitive, // [optional] whether given health checks routes are case insensitive (defaults to false) 

  // cleanup options
  timeout: 1000,                   // [optional = 1000] number of milliseconds before forceful exiting
  signal,                          // [optional = 'SIGTERM'] what signal to listen for relative to shutdown
  signals,                         // [optional = []] array of signals to listen for relative to shutdown
  beforeShutdown,                  // [optional] called before the HTTP server starts its shutdown
  onSignal,                        // [optional] cleanup function, returning a promise (used to be onSigterm)
  onShutdown,                      // [optional] called right before exiting
  onSendFailureDuringShutdown,     // [optional] called before sending each 503 during shutdowns

  // both
  logger                           // [optional] logger function to be called with errors
};

createTerminus(server, options);

server.listen(PORT || 3000);

With custom error messages

const http = require('http');
const { createTerminus, HealthCheckError } = require('@godaddy/terminus');

createTerminus(server, {
  healthChecks: {
    '/healthcheck': async function () {
      const errors = []
      return Promise.all([
        // all your health checks goes here
      ].map(p => p.catch((error) => {
        // silently collecting all the errors
        errors.push(error)
        return undefined
      }))).then(() => {
        if (errors.length) {
          throw new HealthCheckError('healthcheck failed', errors)
        }
      })
    }
  }
});

With express

const http = require('http');
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('ok');
});

const server = http.createServer(app);

const options = {
  // opts
};

createTerminus(server, options);

server.listen(PORT || 3000);

With koa

const http = require('http');
const Koa = require('koa');
const app = new Koa();

const server = http.createServer(app.callback());

const options = {
  // opts
};

createTerminus(server, options);

server.listen(PORT || 3000);

How to set Terminus up with Kubernetes?

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.

function beforeShutdown () {
  // given your readiness probes run every 5 second
  // may be worth using a bigger number so you won't
  // run into any race conditions
  return new Promise(resolve => {
    setTimeout(resolve, 5000)
  })
}
createTerminus(server, {
  beforeShutdown
})

Learn more

Limited Windows support

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.

terminus's People

Contributors

greenkeeper[bot] avatar gergelyke avatar lukaszewczak avatar vernak2539 avatar itaditya avatar valeriangalliat avatar remojansen avatar rxmarbles avatar seanlatimer avatar shawnkoon avatar silasbw avatar snyk-bot avatar sudo-suhas avatar tamirtian avatar tnguyen14 avatar davidnghk01 avatar jon-cooke avatar meskill avatar tony-kerz avatar peterkuiper avatar brunnerlivio avatar 9renpoto avatar jacopodaeli avatar jacob-hd avatar mushketyk avatar lin826 avatar ryuheechul avatar disintegrator avatar zaninime avatar gdoron avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.