health

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2024 License: MIT Imports: 7 Imported by: 0

README

= health-go

A simple lightweight library for exposing health checks over HTTP for Go applications.

This library has the concept of three different statuses:

* UP - Application/System is up and operational as expected
* DEGREDADED - Application/System is operational and usable, but not components or features are working or performing as expected.
* DOWN - Application/System is not operational and not usable.

There is an overall status and a status per component. A component can be thought of as a subsystem or feature of the application. Examples might include a database like Mongo, Postgres, Cassandra, or a distributed cache like Redis. A component can either be marked as critical or non-critical. A non-critical component will never result in the overall application health being considered down. However, if a critical component fails its health check then the overall health will be considered down.

== Usage

Using health-go is simple and straight forward. The components can be registered when calling `New()` or by calling `Register` with the components to Register. When registering components they should be named in such a way it's easy to identify and understand what the component/subsystem is. When registering a component a non-nil `CheckFunc` must be provided. A `CheckFunc` is simply a function type that accepts a `context.Context` and returns a `error`. This provides a lot of flexibility to create your own health checks to meet your requirements. As an example, in some cases maybe pinging a Redis cluster is enough to validate it is up and operational. However, perhaps in other cases, you want to ensure it's also writable/readable, so you perform a more complex healthcheck by setting, fetching, and then deleting a value.

The `Health` type implements `http.Handler` so it can be easily used with the standard library http package, or any third party libraries that are compatible with the standard library. It also conveniently has a `HandlerFunc` method if you prefer to use those over `Handler`.

The below example shows how to set up a healthcheck for Redis and considers Redis a critical component, meaning if Redis is down the application is considered down.

[source,go]
----
package main

import (
	"context"
	"net/http"

	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/redis/go-redis/v9"

	"github.com/jkratz55/health-go"
)

func main() {

	rdb := redis.NewClient(&redis.Options{
		Addr: "localhost:6379",
	})

	hc := health.New()
	hc.Register(health.Component{
		Name:     "redis",
		Critical: true,
		Check: func(ctx context.Context) health.Status {
			res, err := rdb.Ping(ctx).Result()
			if err != nil {
				return health.StatusDown
			}
			if res != "PONG" {
				return health.StatusDown
			}
			return health.StatusUp
		},
	})

	if err := health.EnablePrometheus(hc); err != nil {
		panic(err)
	}

	go func() {
		promServer := http.Server{
			Addr:    ":8082",
			Handler: promhttp.Handler(),
		}
		promServer.ListenAndServe()
	}()

	http.HandleFunc("/health", hc.HandlerFunc())
	http.ListenAndServe(":8080", nil)
}

----

Example Response

[source,json]
----
{
  "status": "UP",
  "uptime": "11.961392833s",
  "components": [
    {
      "name": "redis",
      "critical": true,
      "status": "UP"
    }
  ]
}
----

=== Prometheus Support

This library provides prometheus support out of the box by calling `EnablePrometheus` and passing the `Health` type. This will create a gauge for the overall status, and a gauge for each component.

[source,text]
----
# HELP health_component_status Indicator of status of the application components. 0 is down, 1 is up.
# TYPE health_component_status gauge
health_component_status{component="redis"} 1
# HELP health_status Indicator of overall status of the application instance. 0 is down, 1 is degraded, 2 is up.
# TYPE health_status gauge
health_status 2
----

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EnablePrometheus

func EnablePrometheus(h *Health) error

EnablePrometheus exposes the overall status and status of each component as Prometheus metrics using the default Prometheus registry.

The overall status is exposed as a gauge named "health_status" with a value of 0 for down, 1 for degraded, and 2 for up.

The status of each component is exposed as a gauge named "health_component_status" with a value of 0 for down, 1 for up.

Types

type CheckFunc

type CheckFunc func(ctx context.Context) error

CheckFunc is a function type that checks/verifies the health of a component and or service. If an error is returned, the component/service is considered unhealthy and down.

type Component

type Component struct {

	// Name or identifier of the component. Each component should have a unique
	// name. Otherwise, the response from ServeHTTP will be not be particularly
	// helpful in identifying which component is in a bad state.
	Name string

	// Determines if the component is critical to the overall health and
	// functionality of the system. If a component is marked as critical, and
	// it fails its check, the overall status of the system will be down.
	Critical bool

	// Timeout for the health check. If the health check takes longer than the
	// timeout, the check is considered to have failed. The default value is
	// 5 seconds.
	Timeout time.Duration

	// Interval between health checks. If the interval is set to zero, a default
	// interval of 15 seconds will be used. The Interval must be greater than
	// the Timeout.
	Interval time.Duration

	// The health check of the component.
	//
	// A nil Check will cause a panic.
	Check CheckFunc
	// contains filtered or unexported fields
}

Component represents a single component that can be checked for health.

type ComponentStatus

type ComponentStatus struct {
	Name     string `json:"name"`
	Critical bool   `json:"critical"`
	Status   Status `json:"status"`
}

ComponentStatus represents the status of a component.

type Components

type Components []*Component

Components is a collection of components that can be checked for health.

Components implements http.Handler and can be used to serve as a readiness or liveness health check endpoint.

func (Components) ComponentStatus

func (c Components) ComponentStatus(ctx context.Context) []ComponentStatus

ComponentStatus returns the status of each component.

func (Components) ServeHTTP

func (c Components) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (Components) Status

func (c Components) Status(ctx context.Context) Status

Status returns the overall status of the components.

type Health

type Health struct {
	// contains filtered or unexported fields
}

Health monitors the health of services/components that an application depends on and tracks their status to determine the overall health of the application.

Health implements the http.Handler interface and can be used to expose the health status of the application via an HTTP endpoint.

func New

func New(components ...Component) *Health

New initializes a new Health instance with the provided components.

Additional components can be registered by calling the Register method on the Health instance.

func (*Health) HandlerFunc

func (h *Health) HandlerFunc() http.HandlerFunc

HandlerFunc returns an http.HandlerFunc for the health endpoint which returns the overall health status of the application along with the status of each component. If the application overall status is Up or Degraded a 200 OK status code is returned. If the application overall status is Down a 503 Service Unavailable status code is returned.

func (*Health) Register

func (h *Health) Register(component Component)

Register adds a component to be monitored and considered in the overall health of the application.

Panics if the component does not have a non-nil check function.

func (*Health) ServeHTTP

func (h *Health) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the HTTP handler for the health endpoint which returns the overall health status of the application along with the status of each component. If the application overall status is Up or Degraded a 200 OK status code is returned. If the application overall status is Down a 503 Service Unavailable status code is returned.

func (*Health) Shutdown added in v0.2.0

func (h *Health) Shutdown()

Shutdown stops monitoring the health of the components but will continue to return the last known status of the components.

func (*Health) Status

func (h *Health) Status(ctx context.Context) Status

Status returns the overall status of the application.

type Status

type Status string

Status represents the status of the application.

const (
	// StatusUp indicates the application is up and functioning as expected.
	StatusUp Status = "UP"
	// StatusDegraded indicates the application is up and functional but is
	// experiencing non-critical issues which is degrading the experience.
	StatusDegraded Status = "DEGRADED"
	// StatusDown indicates the application is not functional and for all intents
	// and purposes the application is down (not usable).
	StatusDown Status = "DOWN"
)

func (Status) HttpStatusCode

func (s Status) HttpStatusCode() int

HttpStatusCode returns the HTTP status code for the given status.

Directories

Path Synopsis
checks module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL