health

package module
v3.0.4+incompatible Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2020 License: Apache-2.0 Imports: 9 Imported by: 0

README

health-go

Build Status Go Report Card Go Doc

  • Standalone Health Check
  • Customizable Health Check entry
  • Exposes an HTTP handler that retrieves health status of the application
  • Implements some generic checkers for the following services:
    • RabbitMQ
    • PostgreSQL
    • Redis
    • HTTP
    • MongoDB
    • MySQL

Usage

The library exports Execute function to implements a custom health check entry; HealthStandaloneMode function execute the health check and exit the program with right status; Handler and HandlerFunc functions which are fully compatible with net/http.

Custom Health Check entry
import(
"fmt"
"github.com/sensedia/health-go"

)
func main(){
	//Custom func to handle a internal errors and log
	ErrorLogFunc := func(err error, details string, extra ...interface{}) {
		fmt.Println("Errors:\n", err, "\nDetails:\n", details)
	}
	//Custom func to print debug logs
	DebugLogFunc := func(args ...interface{}) {
		fmt.Println(args)
	}
	//Both func can be nil and is optional

	h := health.New(true, ErrorLogFunc, DebugLogFunc)

	// custom health check example (success)
	h.Register(health.Config{
		Name:  "some-custom-check-success",
		Check: func() error { return nil },
	})

	c := customHealthCheckEntry(&h)
	fmt.Println(c)
}

func customHealthCheckEntry(healthCheck *health.Health) health.Check{
	//personalized logic
	return healthCheck.ExecuteCheck()
}
Standalone

This category of health check can be used when the service uses the Cloud Events Specification, where it is not allowed to create endpoints or create another server in the application. The standalone mode is run by Kubernetes' Liveness Probe, running the application itself with the health check flag and verifying the integrity of the service's external dependencies.

package main

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

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

func main() {
	//Custom func to handle a internal errors and log
	ErrorLogFunc := func(err error, details string, extra ...interface{}) {
		fmt.Println("Errors:\n", err, "\nDetails:\n", details)
	}
	//Custom func to print debug logs
	DebugLogFunc := func(args ...interface{}) {
		fmt.Println(args)
	}
	//Both func can be nil

	healthCheck := health.New(true, ErrorLogFunc, DebugLogFunc)

	// custom health check example (success)
	healthCheck.Register(health.Config{
		Name:  "some-custom-check-success",
		Check: func() error { return nil },
	})

 	//if the flag hc is true, health check will be executed and exit te program
	healthCheck.HealthCheckStandaloneMode("hc")

	http.Handle("/status", healthCheck.Handler())
	http.ListenAndServe(":3000", nil)
}

Handler
package main

import (
  "net/http"
  "time"

  "github.com/sensedia/health-go"
  healthMysql "github.com/sensedia/health-go/checks/mysql"
)

func main() {
  health.Register(health.Config{
    Name: "rabbitmq",
    Timeout: time.Second*5,
    SkipOnErr: true,
    Check: func() error {
      // rabbitmq health check implementation goes here
    },
  })

  health.Register(health.Config{
    Name: "mongodb",
    Check: func() error {
      // mongo_db health check implementation goes here
    },
  })
  
  health.Register(health.Config{
    Name:      "mysql",
    Timeout:   time.Second * 2,
    SkipOnErr: false,
    Check: healthMysql.New(healthMysql.Config{
      DSN: "test:test@tcp(0.0.0.0:31726)/test?charset=utf8",
    },
  })

  http.Handle("/status", health.Handler())
  http.ListenAndServe(":3000", nil)
}
HandlerFunc
package main

import (
  "net/http"
  "time"

  "github.com/go-chi/chi"
  "github.com/sensedia/health-go"
  healthMysql "github.com/sensedia/health-go/checks/mysql"
)

func main() {
  health.Register(health.Config{
    Name: "rabbitmq",
    Timeout: time.Second*5,
    SkipOnErr: true,
    Check: func() error {
      // rabbitmq health check implementation goes here
    }),
  })

  health.Register(health.Config{
    Name: "mongodb",
    Check: func() error {
      // mongo_db health check implementation goes here
    },
  })
  
  health.Register(health.Config{
    Name:      "mysql",
    Timeout:   time.Second * 2,
    SkipOnErr: false,
    Check: healthMysql.New(healthMysql.Config{
      DSN:               "test:test@tcp(0.0.0.0:31726)/test?charset=utf8",
    },
  })

  r := chi.NewRouter()
  r.Get("/status", health.HandlerFunc)
  http.ListenAndServe(":3000", nil)
}

For more examples please check here

API Documentation

GET /status

Get the health of the application.

  • Method: GET
  • Endpoint: /status
  • Request:
curl localhost:3000/status
  • Response:

HTTP/1.1 200 OK

{
  "status": "OK",
  "timestamp": "2017-01-01T00:00:00.413567856+033:00",
  "system": {
    "version": "go1.8",
    "goroutines_count": 4,
    "total_alloc_bytes": 21321,
    "heap_objects_count": 21323,
    "alloc_bytes": 234523
  }
}

HTTP/1.1 200 OK

{
  "status": "Partially Available",
  "timestamp": "2017-01-01T00:00:00.413567856+033:00",
  "failures": {
    "rabbitmq": "Failed during rabbitmq health check"
  },
  "system": {
    "version": "go1.8",
    "goroutines_count": 4,
    "total_alloc_bytes": 21321,
    "heap_objects_count": 21323,
    "alloc_bytes": 234523
  }
}

HTTP/1.1 503 Service Unavailable

{
  "status": "Unavailable",
  "timestamp": "2017-01-01T00:00:00.413567856+033:00",
  "failures": {
    "mongodb": "Failed during mongodb health check"
  },
  "system": {
    "version": "go1.8",
    "goroutines_count": 4,
    "total_alloc_bytes": 21321,
    "heap_objects_count": 21323,
    "alloc_bytes": 234523
  }
}

Contributing

  • Fork it
  • Create your feature branch (git checkout -b my-new-feature)
  • Commit your changes (git commit -am 'Add some feature')
  • Push to the branch (git push origin my-new-feature)
  • Create new Pull Request
Note

This project is a fork of hellofresh health-go, the original content is available in GitHub @hellofresh


GitHub @sensedia  · 

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Check

type Check struct {
	// Status is the check status.
	Status string `json:"status"`
	// Timestamp is the time in which the check occurred.
	Timestamp time.Time `json:"timestamp"`
	// Failures holds the failed checks along with their messages.
	Failures map[string]string `json:"failures,omitempty"`
	// System holds information of the go process.
	System `json:"system"`
}

Check represents the health check response.

type CheckFunc

type CheckFunc func() error

CheckFunc is the func which executes the check.

type Config

type Config struct {
	// Name is the name of the resource to be checked.
	Name string
	// Timeout is the timeout defined for every check.
	Timeout time.Duration
	// SkipOnErr if set to true, it will retrieve StatusOK providing the error message from the failed resource.
	SkipOnErr bool
	// Check is the func which executes the check.
	Check CheckFunc
}

Config carries the parameters to run the check.

type Health

type Health struct {

	//WithSysMetrics is the conditional to process system metrics
	//If it true log and response system metrics
	WithSysMetrics bool
	// ErrorLogFunc is the callback function for errors logging during check.
	// If not set logging is skipped.
	ErrorLogFunc func(err error, details string, extra ...interface{})
	// DebugLogFunc is the callback function for debug logging during check.
	// If not set logging is skipped.
	DebugLogFunc func(...interface{})
	// contains filtered or unexported fields
}

func New

func New(WithSysMetrics bool, ErrorLogFunc func(err error, details string, extra ...interface{}), DebugLogFunc func(...interface{})) Health

func (*Health) BulkRegister

func (h *Health) BulkRegister(c ...Config) (err error)

Register allot of checks

func (*Health) ExecuteCheck

func (h *Health) ExecuteCheck() Check

Execute health check base on config map

func (*Health) ExecuteStandalone

func (h *Health) ExecuteStandalone()

Execute health check in standalone which if it is not ok return code 1 to system

func (*Health) Handler

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

Handler returns an HTTP handler (http.HandlerFunc).

func (*Health) HandlerFunc

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

HandlerFunc is the HTTP handler function.

func (*Health) HealthCheckStandaloneMode

func (h *Health) HealthCheckStandaloneMode(flagName string)

Execute a health check standalone if the flag chosen is true

func (*Health) Register

func (h *Health) Register(c Config) error

Register registers a check config to be performed.

func (*Health) Reset

func (h *Health) Reset()

Reset unregisters all previously set check configs

type System

type System struct {
	// Version is the go version.
	Version string `json:"version"`
	// GoroutinesCount is the number of the current goroutines.
	GoroutinesCount int `json:"goroutines_count"`
	// TotalAllocBytes is the total bytes allocated.
	TotalAllocBytes int `json:"total_alloc_bytes"`
	// HeapObjectsCount is the number of objects in the go heap.
	HeapObjectsCount int `json:"heap_objects_count"`
	// TotalAllocBytes is the bytes allocated and not yet freed.
	AllocBytes int `json:"alloc_bytes"`
}

System runtime variables about the go process.

Directories

Path Synopsis
checks

Jump to

Keyboard shortcuts

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