health

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2023 License: Apache-2.0 Imports: 6 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

health

Package health is a framework for running health tests. Test functions are run in parallel and results can be reported via a web handler.

To get started, initialize the Tests map with named tests:

tester = health.Tester{
	Tests: health.TestFuncs{
		"myTest": func(ctx context.Context) error {
			// ctx.Done() is a channel that will report if the timeout was exceeded
			// or if processing should be cancelled
			// do some test
			if err != nil {
				return err
			}
			return nil
		},
	},
}

You can manually invoke tests using Run:

var results health.Results = tester.Run()

Or, use the HTTP handler and have a load balancer periodically run and check the results:

http.Handle("/health", tester)

If all the tests succeed, an HTTP 200 is returned. Otherwise, and HTTP 500 is returned. Both cases return JSON:

{
  "database": {
    "healthy": true
  },
  "memcached": {
    "healthy": true
  },
  "logic": {
    "healthy": false,
    "message": "OH. MY. GOD.",
    "error": "goroutine 23 [running]:\nsomepackage/somepackage/oops.func·001()..."
  }
}

Note that all tests are run in parallel, and the system includes code to trap calls to panic(). Tests should respect the timeout by checking ctx.Done(), however the system will not break if they don't check.

Tests can also be run periodically in the background using the Ticker type. The difference is that a thread is started to periodically run the tests, and a mechanism is provided to get the results.

Start by defining some tests:

bgtester = .Ticker{
	Tester: health.Tester{
		Tests: health.TestFuncs{
			"myTest": func(ctx context.Context) error {
				// ctx.Done() is a channel that will report if the timeout was exceeded
				// or if processing should be cancelled
				// do some test
				if err != nil {
					return err
				}
				return nil
			},
		},
	},
}

Then start the background testing (and provide a means for it to stop running at some point, usually the end of the program):

bg.Start()
defer bg.Stop()

You can manually check the results using GetResults:

var results health.Results = bg.GetResults()

Or, use the HTTP handler and have a load balancer periodically check the results:

http.Handle("/health", &bg)

If all the tests succeed, an HTTP 200 is returned. Otherwise, and HTTP 500 is returned. Both cases return JSON.

Documentation

Overview

Package health is a framework for running health tests. Test functions are run in parallel and results can be reported via a web handler.

To get started, initialize the Tests map with named tests:

tester = health.Tester{
	Tests: health.TestFuncs{
		"myTest": func(ctx context.Context) error {
			// ctx.Done() is a channel that will report if the timeout was exceeded
			// or if processing should be cancelled
			// do some test
			if err != nil {
				return err
			}
			return nil
		},
	},
}

You can manually invoke tests using Run:

var results health.Results = tester.Run()

Or, use the HTTP handler and have a load balancer periodically run and check the results:

http.Handle("/health", tester)

If all the tests succeed, an HTTP 200 is returned. Otherwise, and HTTP 500 is returned. Both cases return JSON:

{
  "database": {
    "healthy": true
  },
  "memcached": {
    "healthy": true
  },
  "logic": {
    "healthy": false,
    "message": "OH. MY. GOD.",
    "error": "goroutine 23 [running]:\nsomepackage/somepackage.git/oops.func·001()..."
  }
}

Note that all tests are run in parallel, and the system includes code to trap calls to panic(). Tests should respect the timeout by checking ctx.Done(), however the system will not break if they don't check.

Tests can also be run periodically in the background using the Ticker type. The difference is that a thread is started to periodically run the tests, and a mechanism is provided to get the results.

Start by defining some tests:

bgtester = .Ticker{
	Tester: health.Tester{
		Tests: health.TestFuncs{
			"myTest": func(ctx context.Context) error {
				// ctx.Done() is a channel that will report if the timeout was exceeded
				// or if processing should be cancelled
				// do some test
				if err != nil {
					return err
				}
				return nil
			},
		},
	},
}

Then start the background testing (and provide a means for it to stop running at some point, usually the end of the program):

bg.Start()
defer bg.Stop()

You can manually check the results using GetResults:

var results health.Results = bg.GetResults()

Or, use the HTTP handler and have a load balancer periodically check the results:

http.Handle("/health", &bg)

If all the tests succeed, an HTTP 200 is returned. Otherwise, and HTTP 500 is returned. Both cases return JSON.

Index

Constants

View Source
const (
	// DefaultFrequency is how often background tests will run when not specified.
	DefaultFrequency = 1 * time.Minute
)
View Source
const (
	// DefaultTimeout is how long tests can take when a timeout is not specified.
	DefaultTimeout = 2 * time.Second
)

Variables

This section is empty.

Functions

This section is empty.

Types

type LoggerFunc

type LoggerFunc func(testName, messageText, errorText string)

LoggerFunc defines a function used to log messages when tests fail.

type Result

type Result struct {
	Healthy bool   `json:"healthy"`           // Whether this part of the service is healthy.
	Message string `json:"message,omitempty"` // A message indicating what went wrong.
	Error   string `json:"error,omitempty"`   // Error or stack trace information, if available.
}

A Result holds the results of a single test.

type Results

type Results map[string]Result

Results maps test names to their results.

func (Results) Failed

func (r Results) Failed() bool

Failed returns true if any of the tests have failed.

type TestFunc

type TestFunc func(context.Context) error

TestFunc defines the type of a test function. Test functions receive a Context which has a timeout. Test functions can (and should) check the context's Done() channel, and stop their test if the deadline is reached.

type TestFuncs

type TestFuncs map[string]TestFunc

TestFuncs maps test names to their test functions.

type Tester

type Tester struct {
	Timeout time.Duration   // The time that all the tests can take
	Context context.Context // The default context passed to the test functions; defaults to context.Background()
	Tests   TestFuncs       // The slice for storing the test methods to invoke
	Log     LoggerFunc      // If not nil, will be used to log messages when tests fail
}

Tester is used to invoke test functions, gather results, and provide HTTP access. Only the Tests member must be initialized.

func (Tester) Run

func (t Tester) Run() Results

Run runs all of the tests in parallel and collects the results. Run provides a timeout and will return when the timeout is reached, even if some of the test functions are not complete. Test functions should check the context's Done() channel and stop if the test should be aborted. Run will handle panic() calls and errors from the test functions. You should not add tests while Run is active.

func (Tester) ServeHTTP

func (t Tester) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves requests by running all the tests and returning a JSON block with the results. If all the tests succeed, a 200 HTTP status is returned. Otherwise, a 500 HTTP status is returned.

type Ticker

type Ticker struct {
	Tester
	Frequency time.Duration // How often to run the tests
	// contains filtered or unexported fields
}

Ticker defines information for background tests.

func (*Ticker) GetResults

func (tick *Ticker) GetResults() Results

GetResults returns the current results

func (*Ticker) ServeHTTP

func (tick *Ticker) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves requests by running all the tests and returning a JSON block with the results. If all the tests succeed, a 200 HTTP status is returned. Otherwise, a 500 HTTP status is returned.

func (*Ticker) Start

func (tick *Ticker) Start()

Start starts the background health check.

func (*Ticker) Stop

func (tick *Ticker) Stop()

Stop stops the background health check.

Jump to

Keyboard shortcuts

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