Go microservices, part 6 - health checks.

22 March 2017 // Erik Lupander

As our microservices and the landscape they operate in grows more complex, it also becomes increasingly important for our services to provide a mechanism for Docker Swarm to know if they’re feeling healthy or not. Therefore, we’ll take a look at how to add health checks in this sixth part of the blog series.

For example, our “accountservice” microservice isn’t very useful if it cannot:

  • Serve HTTP
  • Connect to its database
    The idiomatic way to handle this in a microservice is to provide an healthcheck endpoint (good article from Azure Docs) that in our case - since we’re HTTP based - should map to /health and respond with a HTTP 200 if things are OK, possibly together with some machine-parsable message explaining what’s OK. If there is a problem, a non HTTP 200 should be returned, possibly stating what’s not OK. Do note that some argue that failed checks should return 200 OK with errors specified in the response payload. I can agree with that too, but for the case of simplicity we’ll stick with non-200 for this blog post. So let’s add such an endpoint to our “account” microservice.

Source code

As always, feel free to checkout the appropriate branch from git to get all changes of this part up front:

  1. git checkout P6

Add check for accessing the BoltDB

Our service won’t be of much use if it cannot access its underlying database. Therefore, we’ll add a new function to the IBoltClient interface, Check():

  1. type IBoltClient interface {
  2. OpenBoltDb()
  3. QueryAccount(accountId string) (model.Account, error)
  4. Seed()
  5. Check() bool // NEW!
  6. }

The Check method is perhaps a bit naive, but will serve its purpose for the sake of this blog. It specifies that either true or false will be returned depending on whether the BoltDB was accessible or not.

Our implementation of Check() in boltclient.go is not very realistic either, but it should explain the concept well enough:

  1. // Naive healthcheck, just makes sure the DB connection has been initialized.
  2. func (bc *BoltClient) Check() bool {
  3. return bc.boltDB != nil
  4. }

The mocked implementation in mockclient.go follows our standard stretchr/testify pattern:

  1. func (m *MockBoltClient) Check() bool {
  2. args := m.Mock.Called()
  3. return args.Get(0).(bool)
  4. }

Adding the /health endpoint

This is very straightforward. We’ll start by adding a new /health route to our /accountservice/service/routes.go file below the existing route to /accounts/{accountId}:

  1. Route{
  2. "HealthCheck",
  3. "GET",
  4. "/health",
  5. HealthCheck,
  6. },

We declared that the route shall be handled by a function named HealthCheck that we now will add to the /accountservice/service/handlers.go file:

  1. func HealthCheck(w http.ResponseWriter, r *http.Request) {
  2. // Since we're here, we already know that HTTP service is up. Let's just check the state of the boltdb connection
  3. dbUp := DBClient.Check()
  4. if dbUp {
  5. data, _ := json.Marshal(healthCheckResponse{Status: "UP"})
  6. writeJsonResponse(w, http.StatusOK, data)
  7. } else {
  8. data, _ := json.Marshal(healthCheckResponse{Status: "Database unaccessible"})
  9. writeJsonResponse(w, http.StatusServiceUnavailable, data)
  10. }
  11. }
  12. func writeJsonResponse(w http.ResponseWriter, status int, data []byte) {
  13. w.Header().Set("Content-Type", "application/json")
  14. w.Header().Set("Content-Length", strconv.Itoa(len(data)))
  15. w.WriteHeader(status)
  16. w.Write(data)
  17. }
  18. type healthCheckResponse struct {
  19. Status string `json:"status"`
  20. }

The HealthCheck function delegates the check of the DB state to the Check() function we added to the DBClient. If OK, we create an instance of the healthCheckResponse struct. Note the lower-case first character? That’s how we scope this struct to only be accessible within the service package. We also extracted the “write a http response” code into a utility method to keep ourselves DRY.

Running

From the /goblog/accountservice folder, build and run:

  1. > go run *.go
  2. Starting accountservice
  3. Seeded 100 fake accounts...
  4. 2017/03/03 21:00:31 Starting HTTP service at 6767

Open a new console window and curl the /health endpoint:

  1. > curl localhost:6767/health
  2. {"status":"UP"}

It works!

The Docker Healthcheck

docker healthcheck

Next, we’ll use the Docker HEALTHCHECK mechanism to let Docker Swarm check our service for liveness. This is done by adding a line in the Dockerfile:

  1. HEALTHCHECK --interval=5s --timeout=5s CMD ["./healthchecker-linux-amd64", "-port=6767"] || exit 1

What’s this “healthchecker-linux-amd64” thing? We need to help Docker a bit with these health checks as Docker itself doesn’t provide us with an HTTP client or similar to actually execute the health checks. Instead, the HEALTHCHECK directive in a Dockerfile specifies a command (CMD) that should perform the call to /health endpoint. Depending on the exit code of the program that was run, Docker will determine whether the service is healthy or not. If too many subsequent health checks fail, Docker Swarm will kill the container and start a new instance.

The most common way to do the actual healthcheck seems to be curl. However, this requires our base docker image to actually have curl (and any underlying dependencies) installed and at this moment we don’t really want to deal with that. Instead, we’ll use Go to brew our own little healthchecker program.

Creating the healthchecker program

Time to create a new sub-project under the /src/github.com/callistaenterprise/goblog path:

  1. mkdir healthchecker

Then, create main.go inside the /healthchecker folder:

  1. package main
  2. import (
  3. "flag"
  4. "net/http"
  5. "os"
  6. )
  7. func main() {
  8. port := flag.String("port", "80", "port on localhost to check")
  9. flag.Parse()
  10. resp, err := http.Get("http://127.0.0.1:" + *port + "/health") // Note pointer dereference using *
  11. // If there is an error or non-200 status, exit with 1 signaling unsuccessful check.
  12. if err != nil || resp.StatusCode != 200 {
  13. os.Exit(1)
  14. }
  15. os.Exit(0)
  16. }

Not an overwhelming amount of code. What it does:

  • Uses the flags support in golang to read a -port=NNNN command line argument. If not specified, fall back to port 80 as default.
  • Perform a HTTP GET to 127.0.0.1:[port]/health
  • If an error occurred or the HTTP status returned wasn’t 200 OK, exit with a non-zero exit code. 0 == Success, > 0 == fail.
    Let’s try this. If you’ve stopped the “accountservice”, start it again either by go run *.go or by building it in a new console tab by going into the “/goblog/accountservice” directory and build/start it:
  1. go build
  2. ./accountservice

Reminder: If you’re getting strange compile errors, check so the GOPATH still is set to the root folder of your Go workspace, e.g. the parent folder of /src/github.com/callistaenterprise/goblog

Then switch back to your normal console window (where you have GOPATH set as well) and run the healthchecker:

  1. > cd $GOPATH/src/github.com/callistaenterprise/goblog/healtchecker
  2. > go run *.go
  3. exit status 1

Ooops! We forgot to specify the port number so it defaulted to port 80. Let’s try it again:

  1. > go run *.go -port=6767
  2. >

No output at all means we were successful. Good. Now, let’s build a linux/amd64 binary and add it to the “accountservice” by including the healthchecker binary in the Dockerfile. We’ll continue using the copyall.sh script to automate things a bit:

  1. #!/bin/bash
  2. export GOOS=linux
  3. export CGO_ENABLED=0
  4. cd accountservice;go get;go build -o accountservice-linux-amd64;echo built `pwd`;cd ..
  5. // NEW, builds the healthchecker binary
  6. cd healthchecker;go get;go build -o healthchecker-linux-amd64;echo built `pwd`;cd ..
  7. export GOOS=darwin
  8. // NEW, copies the healthchecker binary into the accountservice/ folder
  9. cp healthchecker/healthchecker-linux-amd64 accountservice/
  10. docker build -t someprefix/accountservice accountservice/

One last thing, we need to update the “accountservice” Dockerfile. It’s full content looks like this now:

  1. FROM iron/base
  2. EXPOSE 6767
  3. ADD accountservice-linux-amd64 /
  4. # NEW!!
  5. ADD healthchecker-linux-amd64 /
  6. HEALTHCHECK --interval=3s --timeout=3s CMD ["./healthchecker-linux-amd64", "-port=6767"] || exit 1
  7. ENTRYPOINT ["./accountservice-linux-amd64"]

Additions:

  • We added an ADD statement which makes sure the healthchecker binary is included in the image.
  • The HEALTHCHECK statement specifies our binary as well as some parameters that tells Docker to execute the healthcheck every 3 seconds and to accept a timeout of 3 seconds.

Deploying with healthcheck

Now we’re ready to deploy our updated “accountservice” with healthchecking. To automate things even further, add these two lines to the bottom of the copyall.sh script that will remove and re-create the accountservice inside Docker Swarm every time we run it:

  1. docker service rm accountservice
  2. docker service create --name=accountservice --replicas=1 --network=my_network -p=6767:6767 someprefix/accountservice

Now, run ./copyall.sh and wait a few seconds while everything builds and updates. Let’s check the state of our containers using docker ps that lists all running containers:

  1. > docker ps
  2. CONTAINER ID IMAGE COMMAND CREATED STATUS
  3. 1d9ec8122961 someprefix/accountservice:latest "./accountservice-lin" 8 seconds ago Up 6 seconds (healthy)
  4. 107dc2f5e3fc manomarks/visualizer "npm start" 7 days ago Up 7 days

The thing we’re looking for here is the “(healthy)” text under the STATUS header. Services without a healthcheck configured doesn’t have a health indication at all.

Making things fail on purpose

To make things a bit more interesting, let’s add a testability API that lets us make the endpoint act unhealthy on purpose. In routes.go, declare a new endpoint:

  1. Route{
  2. "Testability",
  3. "GET",
  4. "/testability/healthy/{state}",
  5. SetHealthyState,
  6. },

This route (which you never should have in a production service!) provides us with a REST-ish endpoint for failing healthchecks on purpose. The SetHealthyState function goes into goblog/accountservice/handlers.go and looks like this:

  1. var isHealthy = true // NEW
  2. func SetHealthyState(w http.ResponseWriter, r *http.Request) {
  3. // Read the 'state' path parameter from the mux map and convert to a bool
  4. var state, err = strconv.ParseBool(mux.Vars(r)["state"])
  5. // If we couldn't parse the state param, return a HTTP 400
  6. if err != nil {
  7. fmt.Println("Invalid request to SetHealthyState, allowed values are true or false")
  8. w.WriteHeader(http.StatusBadRequest)
  9. return
  10. }
  11. // Otherwise, mutate the package scoped "isHealthy" variable.
  12. isHealthy = state
  13. w.WriteHeader(http.StatusOK)
  14. }

Finally, add the isHealthy bool as a condition to the HealthCheck function:

  1. func HealthCheck(w http.ResponseWriter, r *http.Request) {
  2. // Since we're here, we already know that HTTP service is up. Let's just check the state of the boltdb connection
  3. dbUp := DBClient.Check()
  4. if dbUp && isHealthy { // NEW condition here!
  5. data, _ := json.Marshal(
  6. ...
  7. ...
  8. }

Restart the accountservice:

  1. > cd $GOPATH/src/github.com/callistaenterprise/goblog/accountservice
  2. > go run *.go
  3. Starting accountservice
  4. Seeded 100 fake accounts...
  5. 2017/03/03 21:19:24 Starting HTTP service at 6767

Make a new healthcheck call from the other window:

  1. > cd $GOPATH/src/github.com/callistaenterprise/goblog/healthchecker
  2. > go run *.go -port=6767
  3. >

First attempt successful. Now change the state of the accountservice using a curl request to the testability endpoint:

  1. > curl localhost:6767/testability/healthy/false
  2. > go run *.go -port=6767
  3. exit status 1

It’s working! Let’s try this running inside Docker Swarm. Rebuild and redeploy the “accountservice” using copyall.sh:

  1. > cd $GOPATH/src/github.com/callistaenterprise/goblog
  2. > ./copyall.sh

As always, wait a bit while Docker Swarm redeploys the “accountservice” service using the latest build of the “accountservice” container image. Then, run docker ps to see if we’re up and running with a healthy service:

  1. > docker ps
  2. CONTAINER ID IMAGE COMMAND CREATED STATUS
  3. 8640f41f9939 someprefix/accountservice:latest "./accountservice-lin" 19 seconds ago Up 18 seconds (healthy)

Note CONTAINER ID and the CREATED. Call the testability API on your docker swarm IP (mine is 192.168.99.100):

  1. > curl $ManagerIP:6767/testability/healthy/false
  2. >

Now, run docker ps again within a few seconds.

  1. > docker ps
  2. CONTAINER ID IMAGE COMMAND CREATED STATUS NAMES
  3. 0a6dc695fc2d someprefix/accountservice:latest "./accountservice-lin" 3 seconds ago Up 2 seconds (healthy)

See - a brand new CONTAINER ID and new timestamps on CREATED and STATUS. What actually happened was that Docker Swarm detected three (default values for –retries) consecutive failed healthchecks and immediately decided the service had become unhealthy and need to be replaced with a fresh instance which is exactly what happened without any administrator intervention.

Summary

In this part we added health checks using a simple /health endpoint and a little healthchecker go program in conjunction with the Docker HEALTHCHECK mechanism, showing how that mechanism allows Docker Swarm to handle unhealthy services automatically for us.

In the next part, we’ll dive deeper into Docker Swarm mechanics as we’ll be focusing on two key areas of microservice architecture - Service Discovery and Load-balancing.