• Stars
    star
    130
  • Rank 270,103 (Top 6 %)
  • Language
    Go
  • License
    Other
  • Created over 7 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A go implementation of the Health Checks API used for microservice exploration, documentation and monitoring.

go healthchecks

Introduction

A go implementation of the Health Checks API used for microservice exploration, documentation and monitoring.

How to Use It

Using the healthchecks framework in your service is easy.

  • Define a StatusEndpoint for each dependency in your service.
  • Register the healthchecks framework to respond to all /status/... requests passing a slice of all your StatusEndpoints.
  • That's it! As long as you have defined your StatusEndpoints correctly, the framework will take care of the rest.

Example:

// Define a StatusEndpoint at '/status/db' for a database dependency
db := healthchecks.StatusEndpoint{
  Name: "The DB",
  Slug: "db",
  Type: "internal",
  IsTraversable: false,
  StatusCheck: sqlsc.SQLDBStatusChecker{
    DB: myDB
  },
  TraverseCheck: nil,
}

// Define a StatusEndpoint at '/status/service-organization' for the Organization service
org := healthchecks.StatusEndpoint{
  Name: "Organization Service",
  Slug: "service-organization",
  Type: "http",
  IsTraversable: true,
  StatusCheck: httpsc.HttpStatusChecker{
    BaseUrl: "[Read value from config]",
  },
  TraverseCheck: httpsc.HttpStatusChecker{
    BaseUrl: "[Read value from config]",
  },
}

// Define the list of StatusEndpoints for your service
statusEndpoints := []healthchecks.StatusEndpoint{ db, org }

// Set the path for the about and version files
aboutFilePath := "conf/about.json"
versionFilePath := "conf/version.txt"

// Set up any service injected customData for /status/about response.
// Values can be any valid JSON conversion and will override values set in about.json.
customData := make(map[string]interface{})
// Examples:
//
// String value
// customData["a-string"] = "some-value"
//
// Number value
// customData["a-number"] = 123
//
// Boolean value
// customData["a-bool"] = true
//
// Array
// customData["an-array"] = []string{"val1", "val2"}
//
// Custom object
// customObject := make(map[string]interface{})
// customObject["key1"] = 1
// customObject["key2"] = "some-value"
// customData["an-object"] = customObject

// Register all the "/status/..." requests to use our health checking framework
http.Handle("/status/", healthchecks.Handler(statusEndpoints, aboutFilePath, versionFilePath, customData))

Writing a StatusCheck

A StatusCheck is a struct which implements the function func CheckStatus(name string) StatusList. A StatusCheck is defined or used in a service but executed by the healthchecks framework. The key to a successful StatusCheck is to handle all errors on the dependency you are checking. Below is an example of a StatusCheck that checks the connection of Redis using the gopkg.in/redis.v4 driver.

type RedisStatusChecker struct {
	client RedisClient
}

func (r RedisStatusChecker) CheckStatus(name string) healthchecks.StatusList {
	pong, err := r.client.Ping()

	// Set a default response
	s := healthchecks.Status{
		Description:  name,
		Result: healthchecks.OK,
		Details: "",
	}

	// Handle any errors that Ping() function returned
	if err != nil {
		s = healthchecks.Status{
			Description:  name,
			Result: healthchecks.CRITICAL,
			Details: err.Error(),
		}
	}

	// Make sure the pong response is what we expected
	if pong != "PONG" {
		s = healthchecks.Status{
			Description:  name,
			Result: healthchecks.CRITICAL,
			Details: fmt.Sprintf("Expecting `PONG` response, got `%s`", pong),
		}
	}

	// Return our response
	return healthchecks.StatusList{ StatusList: []healthchecks.Status{ s }}
}

Writing a TraverseCheck

A TraverseCheck is a struct which implements the function func Traverse(traversalPath []string, action string) (string, error). A TraverseCheck is defined or used in a service but executed by the healthchecks framework. The key to a successful TraverseCheck is to build and execute the /status/traverse?action=[action]&dependencies=[dependencies] request to the service you are trying to traverse to and returning the response or error you got. Below is an example of a TraverseCheck for an HTTP service.

type HttpStatusChecker struct {
	BaseUrl string
	Name    string
}

func (h HttpStatusChecker) Traverse(traversalPath []string, action string) (string, error) {
	dependencies := ""
	if len(traversalPath) > 0 {
		dependencies = fmt.Sprintf("&dependencies=%s", strings.Join(traversalPath, ","))
	}

	// Build our HTTP request
	url := fmt.Sprintf("%s/status/traverse?action=%s%s", h.BaseUrl, action, dependencies)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Printf("Error creating request: %s \n", err.Error())
		return "", err
	}

	// Execute HTTP request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Error executing request: %s \n", err.Error())
		return "", err
	}

	// Defer the closing of the body
	defer resp.Body.Close()

	// Read our response
	responseBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Error reading response body: %s", err.Error())
		return "", err
	}

	// Return our response
	return string(responseBody), nil
}

How To Contribute

Contribute by submitting a PR and a bug report in GitHub.

License

healthchecks is released under the Apache License, Version 2.0. See LICENSE for details.

Maintainers

More Repositories

1

grid

Drag and drop library for two-dimensional, resizable and responsive lists
JavaScript
3,574
star
2

atlantis

Atlantis is now being maintained at https://github.com/runatlantis/atlantis
Go
615
star
3

nachos

Material Chips for Android
Java
451
star
4

pre-commit-php

Pre-commit scripts appropriate for any PHP project. These hooks are made as custom plugins under the pre-commit git hook framework.
Shell
175
star
5

akka-persistence-redis

Akka Persistence that uses Redis as backend
Scala
117
star
6

health-checks-api

Standardize the way services and applications expose their status in a distributed application
API Blueprint
93
star
7

microservice-graph-explorer

Navigate and explore all of the microservices in your application in real time using the real application connections.
JavaScript
74
star
8

sens8

Kubernetes controller for Sensu checks
Go
41
star
9

token-ui

Text input components that allows to add 'tokens' rendered as pills.
Swift
40
star
10

hermes

Kotlin ktor application which bridges Github and Slack. Use it to automate common workflows involving those platforms
Kotlin
35
star
11

scala-circuit-breaker

A circuit breaker for Scala applications and services
Scala
34
star
12

sbt-swagger

SBT plugin for extracting Swagger & JAX-RS (jsr311) annotations from compiled classes into Swagger API models, which are then serialized to JSON for consumption with swagger-ui.
Scala
27
star
13

wordpress-multisite-vagrant

JavaScript
27
star
14

vault-ctrl-tool

Simple tool for managing authentication, secrets, and leases for services.
Go
25
star
15

backup53

AWS Route53 backup tool
Python
23
star
16

hootsuite-app-express

Sample Hootsuite app directory app using Express and Node.js
JavaScript
16
star
17

statsd-client

A lightweight library for generating statsd events from in Scala applications.
Scala
13
star
18

apis-101

Beginners-friendly introduction to APIs starter code.
JavaScript
10
star
19

maintenance-calendar-for-aws

Go
9
star
20

OwlBanners

Swift
7
star
21

emit

Simple signals library for Swift
Swift
6
star
22

udp-logger

UDP logging to logstash for logback and log4j.
Scala
6
star
23

microservice-graph-explorer-test

Runs services that implement the Health Checks API to be used when testing the Microservice Graph Explorer
Go
5
star
24

atlantis-example

A simple terraform project to use along with atlantis bootstrap mode
3
star
25

dropbox-media-library-sample

Media Library Sample App with Auth
JavaScript
1
star
26

atlantis-tests

A set of terraform projects that atlantis e2e tests run on.
HCL
1
star