healthz

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2023 License: Apache-2.0 Imports: 11 Imported by: 0

README

go-healthz

CircleCI

This package provides an HTTP handler that returns information about the health status of the application. If the application is healthy and all the registered check pass, it returns a 200 OK HTTP status, otherwise, it fails with a 503 Service Unavailable. All responses contain a JSON encoded payload with information about the runtime system, current checks statuses and some configurable metadata.

This is a fork of github.com/MEDIGO/go-healthz with breaking changes. Changes include:

  • Added the ability to return warnings from checkers that are not considered service failures.
  • Renamed Set and Delete to SetMeta and DeleteMeta (this is a breaking change)
  • Added Set to statically set a check status without callbacks with optional timeout. This is useful if you already have an event loop.
  • Several locking fixes.
Usage
package main

import (
	"errors"
	"net/http"
	"time"

	"github.com/wojas/go-healthz"
)

const version = "1.0.0"

func main() {
	healthz.SetMeta("version", version)

	healthz.Register("important_check", time.Second*5, func() error {
		return errors.New("fail fail fail")
	})

	healthz.Register("some_warning", time.Second*5, func() error {
		return healthz.Warn("some warning")
	})

	healthz.Set("other_warning", healthz.Warn("static value"), time.Hour)

	http.Handle("/healthz", healthz.Handler())
	http.ListenAndServe(":8000", nil)
}
$ http GET localhost:8000/healthz
HTTP/1.1 503 Service Unavailable
Content-Length: 317
Content-Type: application/json
Date: Fri, 23 Sep 2016 08:55:16 GMT

{
    "ok": false,
    "has_warnings": true,
    "status": "Unavailable",
    "time": "2016-09-23T10:55:16.781538256+02:00",
    "since": "2016-09-23T10:55:14.268149643+02:00",
    "metadata": {
        "version": "1.0.0"
    },
    "failures": {
        "important_check": "fail fail fail"
    },
    "warnings": {
        "some_warning": "some warning",
        "other_warning": "static value"
    },
    "runtime": {
        "alloc_bytes": 314048,
        "arch": "amd64",
        "goroutines_count": 4,
        "heap_objects_count": 4575,
        "os": "darwin",
        "total_alloc_bytes": 314048,
        "version": "go1.19"
    }
}

Copyright © 2016 MEDIGO GmbH. Copyright © 2022-present other contributors, see git history.

go-healthz is licensed under the Apache License, Version 2.0. See LICENSE for the full license text.

Documentation

Overview

Package healthz provides an HTTP handler that returns information about the health status of the application.

Index

Constants

View Source
const (
	// DefaultRuntimeTTL is the default TTL of the collected runtime stats.
	DefaultRuntimeTTL = 15 * time.Second

	// DefaultCheckPeriod is the default check period if 0 is passed to Register
	DefaultCheckPeriod = time.Second
)
View Source
const (
	// StatusOK is returned when all the registered checks pass.
	StatusOK = "OK"
	// StatusUnavailable is returned when any of the registered checks fail.
	StatusUnavailable = "Unavailable"
	// StatusWarning is returned when one or more registered check returns
	// a warning and none returns a fatal error.
	StatusWarning = "Warning"
)
View Source
const (
	// RemoteDefaultTimeout is the default timeout for fetching a remote
	// healthz in RegisterRemote.
	RemoteDefaultTimeout = 10 * time.Second
)

Variables

View Source
var (
	// DefaultChecker is the default global checker referenced by the shortcut
	// functions in this package. Change this variable with caution, because
	// you will lose any checkers that have already been registered to the
	// old one.
	DefaultChecker = NewChecker(&Config{DefaultRuntimeTTL})
)

Functions

func AddBuildInfo

func AddBuildInfo()

AddBuildInfo adds some build info like VCS from debug.ReadBuildInfo to the metadata.

func DeleteMeta

func DeleteMeta(name string)

DeleteMeta is a shortcut for DefaultChecker.DeleteMeta. See there for more information.

func Deregister

func Deregister(name string)

Deregister is a shortcut for DefaultChecker.Deregister. See there for more information.

func Handler

func Handler() http.Handler

Handler is a shortcut for DefaultChecker.Handler. See there for more information.

func IsScopedMultiError

func IsScopedMultiError(err error) bool

IsScopedMultiError returns true if the error is a ScopedMultiError. It will NOT attempt to unwrap the error.

func IsWarning

func IsWarning(err error) bool

IsWarning returns true if the error is a Warning instead of a failure. It will recursively unwrap the error to look for a Warning.

func Register

func Register(name string, period time.Duration, fn CheckFunc)

Register is a shortcut for DefaultChecker.Register. See there for more information.

func RegisterRemote

func RegisterRemote(name string, period time.Duration, url string, opt *RemoteOptions) error

RegisterRemote registers a remote /healthz endpoint that needs to be monitored. See Checker.RegisterRemote for details.

func Set

func Set(name string, err error, timeout time.Duration)

Set is a shortcut for DefaultChecker.Set. See there for more information.

func SetMeta

func SetMeta(name string, value interface{})

SetMeta is a shortcut for DefaultChecker.SetMeta. See there for more information.

func Warn

func Warn(msg string) error

Warn returns a Warning with given message

func Warnf

func Warnf(format string, args ...interface{}) error

Warnf formats a Warning

Types

type CheckFunc

type CheckFunc func() error

CheckFunc is an application health check function.

type Checker

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

Checker is a health status checker responsible for evaluating the registered checks as well as of collecting useful runtime information about the Go Process. It provides an HTTP handler that returns the current health status.

func NewChecker

func NewChecker(config *Config) *Checker

NewChecker creates a new Checker. Using a custom Checker instead of the global DefaultChecker is not recommended.

func (*Checker) AddBuildInfo

func (c *Checker) AddBuildInfo()

AddBuildInfo will add build information like the Go version and VCS to the exposed metadata.

func (*Checker) Close

func (c *Checker) Close()

Close removes all existing checks

func (*Checker) DeleteMeta

func (c *Checker) DeleteMeta(name string)

DeleteMeta deletes a named entry from the configured metadata.

func (*Checker) Deregister

func (c *Checker) Deregister(name string)

Deregister deregisters a check.

func (*Checker) Handler

func (c *Checker) Handler() http.Handler

Handler returns an HTTP handler to be used as a health check endpoint. If the application is healthy and all the registered check pass, it returns a `200 OK` HTTP status code, otherwise, it fails with a `503 Service Unavailable` code. All responses contain a JSON encoded payload with information about the runtime system, current checks statuses and some configurable metadata.

func (*Checker) Register

func (c *Checker) Register(name string, period time.Duration, fn CheckFunc)

Register registers a check to be evaluated each given period.

func (*Checker) RegisterRemote

func (c *Checker) RegisterRemote(name string, period time.Duration, url string, opt *RemoteOptions) error

RegisterRemote registers a remote /healthz endpoint that needs to be monitored. The period parameter determines the poll interval. The url must contain the full url to the healthz endpoint.

If the remote endpoint uses the same JSON structure as this instance does, the name is used to prefix all remote failures and warnings, separated by a slash ('/'). E.g. if the name is "foo", a remote "bar" error will end up as "foo/bar" in the status reported by this instance. It the remote endpoint is not served by this library and no compatible failures and warnings keys could be found, this check returns a single error for this endpoint with the requested name.

func (*Checker) Set

func (c *Checker) Set(name string, err error, expiry time.Duration)

Set sets a static status value without a periodic checker function. This can be useful if your application has an event loop that can directly update the status for real-time information, instead of relying on a checker function to run periodically. If the expiry duration is not 0, the status will be reset to Expired after this duration, if no new value is set in the meantime.

func (*Checker) SetMeta

func (c *Checker) SetMeta(name string, value interface{})

SetMeta sets a name value pair as a metadata entry to be returned with each response. This can be used to store useful debug information like version numbers or git commit hashes.

func (*Checker) Status

func (c *Checker) Status() Status

Status returns the current service status.

type Config

type Config struct {
	// RuntimeTTL is the time between checking runtime stats like memory usage.
	// It defaults to DefaultRuntimeTTL.
	RuntimeTTL time.Duration
}

Config parameterizes a Checker.

type Expired

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

Expired is the error status set after a status set by SetMeta has expired.

func (Expired) Error

func (e Expired) Error() string

type RemoteOptions

type RemoteOptions struct {
	// Client allows you to override the default http.Client
	Client *http.Client // optional client override

	// Timeout allows you to override the default timeout of RemoteDefaultTimeout
	// used by RegisterRemote. If the Client is overridden, this does nothing.
	Timeout time.Duration // optional timeout, if the default is not OK

	// AsWarnings instructs RegisterRemote to downgrade any remote errors to
	// warnings for this check.
	AsWarnings bool

	// Warn404 make a remote 404 a warning instead of an error. This is useful
	// if you are not sure if the target url has a healthz endpoint.
	Warn404 bool
}

RemoteOptions are options passed to RegisterRemote

type Runtime

type Runtime struct {
	CollectedAt      time.Time `json:"-"`
	Arch             string    `json:"arch"`
	OS               string    `json:"os"`
	Version          string    `json:"version"`
	GoroutinesCount  int       `json:"goroutines_count"`
	HeapObjectsCount int       `json:"heap_objects_count"`
	AllocBytes       int       `json:"alloc_bytes"`
	TotalAllocBytes  int       `json:"total_alloc_bytes"`
}

Runtime contains statistics about the Go's process.

type ScopedMultiError

type ScopedMultiError map[string]error

ScopedMultiError contains multiple errors keyed by a unique name

func (ScopedMultiError) Error

func (e ScopedMultiError) Error() string

type Status

type Status struct {
	OK          bool                   `json:"ok"` // May have warnings
	HasWarnings bool                   `json:"has_warnings"`
	Status      string                 `json:"status"`
	Time        time.Time              `json:"time"`
	Since       time.Time              `json:"since"`
	Runtime     Runtime                `json:"runtime"`
	Failures    map[string]string      `json:"failures"`
	Warnings    map[string]string      `json:"warnings"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

Status represents the service health status.

type Warning

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

Warning is a type of error that is considered a warning instead of a failure. It will not cause the health check to fail, but the warning will appear in the JSON.

func (Warning) Error

func (w Warning) Error() string

Jump to

Keyboard shortcuts

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