Skip to content

Commit

Permalink
Merge pull request #1 from dotse/tmp
Browse files Browse the repository at this point in the history
Initial implementation
  • Loading branch information
biffen authored Oct 25, 2019
2 parents 6d8ddd4 + add5f8f commit 79745d1
Show file tree
Hide file tree
Showing 16 changed files with 1,076 additions and 0 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
%YAML 1.1
---
name: Build

on:
- push

jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v1
with:
go-version: 1.13
id: go

- name: Check out code into the Go module directory
uses: actions/checkout@v1

- name: Build
run: go build -v ./...

- name: Test
run: go test -race -v ./...
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*~
/vendor/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 The Swedish Internet Foundation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
107 changes: 107 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# `go-health`

[![License](https://img.shields.io/github/license/dotse/go-health)](https://opensource.org/licenses/MIT)
[![GoDoc](https://img.shields.io/badge/-Documentation-green?logo=go)](https://godoc.org/github.com/dotse/go-health)
[![Actions](https://github.com/dotse/go-health/workflows/Build/badge.svg?branch=master)](https://github.com/dotse/go-health/actions)
[![Releases](https://img.shields.io/github/v/release/dotse/go-health?sort=semver)](https://github.com/dotse/go-health/releases)
[![Issues](https://img.shields.io/github/issues/dotse/go-health)](https://github.com/dotse/go-health/issues)

`go-health` is a Go library for easily setting up monitoring of anything within
an application. Anything that can have a health status can be registered, and
then, as if by magic 🧙, an HTTP server is running and serving a combined health
status.

It follows the proposed standard [_Health Check Response Format for HTTP APIs_]
(but you don’t even have to know that, `go-health` takes care of that for you).

## Example

ℹ️ The code below is minimal. There’s more to `go-health`, but this is enough to
get something up and running.

### Setting up Health Checks

Let‘s say your application has a database handle, and you want to monitor that
it can actually communicate with the database. Simply implement the `Checker`
interface:

```go
import (
"github.com/dotse/go-health"
)

type MyApplication struct {
db sql.DB

// ...
}

func (app *MyApplication) CheckHealth() []health.Check {
c := health.Check{}
if err := app.db.Ping(); err != nil{
c.Status = health.StatusFail
c.Output = err.Error()
}
return []health.Check{ c }
}
```

Then whenever you create your application register it as a health check:

```go
app := NewMyApplication()
health.Register(true, "my-application", app)
```

Either like the above, e.g. in `main()`, or the application could even register
_itself_ on creation. You can register as many times as you want. The reported
health status will be the ‘worst’ of all the registered checkers.

Then there will be an HTTP server listening on <http://127.0.0.1:9999/> and
serving a fresh health [response] on each request.

### Checking the Health

To then check the health, GET the response and look at its `status` field.

`go-health` has a function for this too:

```go
resp, err := health.CheckHealth(c.config)
if err == nil {
fmt.Printf("Status: %s\n", resp.Status)
} else {
fmt.Printf("ERROR: %v\n", err)
}
```

### Using as a Docker Health Check

An easy way to create a health check for a Docker image is to use the same
binary as your application to do the checking. E.g. if the application is
invoked with the first argument `healthcheck`:

```go
func main() {
if os.Args[1] == "healthcheck" {
health.CheckHealthCommand()
}

// Your other code...
}
```

`CheckHealthCommand()` will GET the current health from the local HTTP server,
parse the response and `os.Exit()` either 0 or 1, depending on the health.

Then in your `Dockerfile` add:

```dockerfile
HEALTHCHECK --interval=10s --timeout=30s CMD ./app healthcheck
```

💁 Voilà! A few lines of code and your Docker image has a built-in health check
for all the things you want monitored.

[_health check response format for http apis_]: https://inadarei.github.io/rfc-healthcheck/
[response]: https://inadarei.github.io/rfc-healthcheck/#rfc.section.3
31 changes: 31 additions & 0 deletions check.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright © 2019 The Swedish Internet Foundation
//
// Distributed under the MIT License. (See accompanying LICENSE file or copy at
// <https://opensource.org/licenses/MIT>.)

package health

import (
"net/url"
"time"
)

// Check represent a single health check point.
type Check struct {
ComponentID string `json:"componentId,omitempty"`
ComponentType string `json:"componentType,omitempty"`
ObservedValue interface{} `json:"observedValue,omitempty"`
ObservedUnit string `json:"observedUnit,omitempty"`
Status Status `json:"status"`
AffectedEndpoints []url.URL `json:"affectedEndpoints,omitempty"`
Time time.Time `json:"time,omitempty"`
Output string `json:"output,omitempty"`
Links []url.URL `json:"links,omitempty"`
}

// SetObservedTime sets the observedValue field to a time duration (and the
// observedUnit field to the correct unit).
func (check *Check) SetObservedTime(duration time.Duration) {
check.ObservedValue = duration.Nanoseconds()
check.ObservedUnit = "ns"
}
201 changes: 201 additions & 0 deletions cmd/healthcheck/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
// Copyright © 2019 The Swedish Internet Foundation
//
// Distributed under the MIT License. (See accompanying LICENSE file or copy at
// <https://opensource.org/licenses/MIT>.)

package main

import (
"bytes"
"context"
"flag"
"fmt"
"log"
"os"
"os/signal"
"strings"
"time"

"github.com/docker/docker/client"
"github.com/tidwall/pretty"
"golang.org/x/crypto/ssh/terminal"

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

const (
errorKey = "error"
)

type cmd struct {
config health.CheckHealthConfig
continuous bool
interval time.Duration
isatty bool
print func(*health.Response)
short bool
stats map[string]uint64
stop bool
}

func newCmd() cmd {
c := cmd{}

var (
docker bool
port int
timeout time.Duration
)

flag.BoolVar(&c.continuous, "c", false, "Run continuously (stop with Ctrl+C).")
flag.BoolVar(&docker, "d", false, "Address is the name of a Docker container.")
flag.DurationVar(&c.interval, "n", 0, "Interval between continuous checks (implies -c) (default: 2s).")
flag.IntVar(&port, "p", 0, "Port.")
flag.BoolVar(&c.short, "s", false, "Short output (just the status).")
flag.DurationVar(&timeout, "t", 0, "HTTP timeout.")

flag.Parse()

// Setting interval implies continuous
c.continuous = c.continuous || c.interval != 0
if c.continuous && c.interval == 0 {
c.interval = 2 * time.Second
}

var host string

if docker {
var err error
if host, err = getContainerAddress(flag.Arg(0)); err != nil {
log.Fatal(err)
}
} else {
host = flag.Arg(0)
}

c.config = health.CheckHealthConfig{
Port: port,
Host: host,
Timeout: timeout,
}

c.isatty = terminal.IsTerminal(int(os.Stdout.Fd()))
c.print = c.makePrint()

return c
}

func (c *cmd) exit() {
if c.continuous && c.isatty {
var str []string

for status, count := range c.stats {
str = append(str, fmt.Sprintf("\033[%dm%d %s\033[0m", map[string]int{
health.StatusPass.String(): 32,
health.StatusWarn.String(): 33,
health.StatusFail.String(): 31,
errorKey: 91,
}[status], count, status))
}

fmt.Printf("\n---\n%s\n", strings.Join(str, ", "))
}

for status, count := range c.stats {
if status == health.StatusPass.String() {
continue
}

if count > 0 {
os.Exit(1)
}
}

os.Exit(0)
}

func (c *cmd) makePrint() func(*health.Response) {
switch {
case c.continuous && c.isatty && c.short:
return func(resp *health.Response) {
fmt.Printf("%s %s\r", time.Now().Format(time.RFC3339), resp.Status)
}

case c.short:
return func(resp *health.Response) {
fmt.Println(resp.Status)
}

case c.isatty:
return func(resp *health.Response) {
var buffer bytes.Buffer
_, _ = resp.Write(&buffer)
fmt.Println(string(pretty.Color(pretty.Pretty(buffer.Bytes()), nil)))
}

default:
return func(resp *health.Response) {
_, _ = resp.Write(os.Stdout)
}
}
}

func (c *cmd) run() {
c.stats = make(map[string]uint64)

go c.wait()

for !c.stop {
resp, err := health.CheckHealth(c.config)
if err == nil {
c.stats[resp.Status.String()]++
c.print(resp)
} else {
c.stats[errorKey]++
log.Println(err)
}

if !c.continuous {
c.exit()
}

time.Sleep(c.interval)
}
}

func (c *cmd) wait() {
channel := make(chan os.Signal, 1)

signal.Notify(channel, os.Interrupt)

<-channel

c.stop = true

c.exit()
}

func getContainerAddress(container string) (string, error) {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
return "", err
}

containerJSON, err := cli.ContainerInspect(context.Background(), container)
if err != nil {
return "", err
}

for _, network := range containerJSON.NetworkSettings.Networks {
if network.IPAddress != "" {
return network.IPAddress, nil
}
}

return "", fmt.Errorf("couldn’t find address of %q", container)
}

func main() {
c := newCmd()
c.run()
}
Loading

0 comments on commit 79745d1

Please sign in to comment.