Skip to content

Commit

Permalink
Merge pull request gruntwork-io#1 from gruntwork-io/v0.0.1
Browse files Browse the repository at this point in the history
Initial release
  • Loading branch information
josh-padnick authored Dec 15, 2017
2 parents 59a3563 + 4e0c8a5 commit 1b4c7ba
Show file tree
Hide file tree
Showing 11 changed files with 482 additions and 1 deletion.
95 changes: 95 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
defaults: &defaults
working_directory: /go/src/github.com/gruntwork-io/health-checker
docker:
- image: 087285199408.dkr.ecr.us-east-1.amazonaws.com/circle-ci-test-image-base:latest

version: 2
jobs:
install_dependencies:
<<: *defaults
steps:
- checkout
- attach_workspace:
at: /go/src/github.com/gruntwork-io/health-checker
- restore_cache:
keys:
- dep-{{ checksum "Gopkg.lock" }}
- run: (dep ensure)
- save_cache:
key: dep-{{ checksum "Gopkg.lock" }}
paths:
- /go/src/github.com/gruntwork-io/health-checker/vendor
- persist_to_workspace:
root: .
paths:
- vendor

test:
<<: *defaults
steps:
- checkout
- attach_workspace:
at: /go/src/github.com/gruntwork-io/health-checker
- run: run-go-tests --circle-ci-2 --path test

build:
<<: *defaults
steps:
- checkout
- attach_workspace:
at: /go/src/github.com/gruntwork-io/health-checker
- run: build-go-binaries --circle-ci-2 --src-path . --app-name health-checker --dest-path bin --ld-flags "-X main.VERSION=$CIRCLE_TAG"
- persist_to_workspace:
root: .
paths: bin

deploy:
<<: *defaults
steps:
- checkout
- attach_workspace:
at: /go/src/github.com/gruntwork-io/health-checker
- run: upload-github-release-assets bin/*

workflows:
version: 2
build-and-test:
jobs:
- install_dependencies:
filters:
tags:
only: /^v.*/
- test:
requires:
- install_dependencies
filters:
tags:
only: /^v.*/
- build:
requires:
- test
filters:
tags:
only: /^v.*/
- deploy:
requires:
- build
filters:
tags:
only: /^v.*/
branches:
ignore: /.*/


nightly:
triggers:
- schedule:
cron: "0 8 * * *"
filters:
branches:
only: master
jobs:
- install_dependencies
- test:
requires:
- install_dependencies
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea
vendor
tmp
45 changes: 45 additions & 0 deletions Gopkg.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions Gopkg.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@

# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "git hub.com/x/y"
# version = "2.4.0"

[[constraint]]
name = "github.com/gruntwork-io/gruntwork-cli"
version = "0.1.1"

[[constraint]]
name = "github.com/urfave/cli"
version = "1.20.0"
56 changes: 55 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,56 @@
# health-checker
A simple HTTP server that will return 200 OK if the given set of TCP ports are all accepting connections.

A simple HTTP server that will return `200 OK` if the given TCP ports are all successfully accepting connections.

## Motivation

We were setting up an AWS [Auto Scaling Group](http://docs.aws.amazon.com/autoscaling/latest/userguide/AutoScalingGroup.html)
(ASG) fronted by a [Load Balancer](https://aws.amazon.com/documentation/elastic-load-balancing/) that used a
[Health Check](http://docs.aws.amazon.com/elasticloadbalancing/latest/network/target-group-health-checks.html#) to
determine if the server is healthy. Each server in the ASG runs two services, which means that a server is "healthy" if
the TCP Listeners of both services are successfully accepting connections. But the Load Balancer Health Check is limited to
a single TCP port, or an HTTP(S) endpoint. As a result, our use case just isn't supported natively by AWS.

We wrote health-checker so that we could run a daemon on the server that reports the true health of the server by
attempting to open a TCP connection to more than one port when it receives an inbound HTTP request on the given listener.

## How It Works

When health-checker is started, it will listen for inbound HTTP requests for any URL on the IP address and port specified
by `--listener`. When it receives a request, it will attempt to open TCP connections to each of the ports specified by
an instance of `--port`. If all TCP connections succeed, it will return `HTTP 200 OK`. If any TCP connection fails, it
will return `HTTP 504 Gateway Not Found`.

Configure your AWS Health Check to only pass the Health Check on `HTTP 200 OK`. Now when an HTTP Health Check request
comes in, all desired TCP ports will be checked.

For stability, we recommend running health-checker under a process supervisor such as [supervisord](http://supervisord.org/)
or [systemd](https://www.freedesktop.org/wiki/Software/systemd/) to automatically restart health-checker in the unlikely
case that it fails.

## Usage

```
health-checker [options]
```

#### Options

| Option | Description | Default
| ------ | ----------- | -------
| `--port` | The port number on which a TCP connection will be attempted. Specify one or more times. | |
| `--listener` | The IP address and port on which inbound HTTP connections will be accepted. | `0.0.0.0:5000`
| `--log-level` | Set the log level to LEVEL. Must be one of: `panic`, `fatal`, `error,` `warning`, `info`, or `debug` | `info`
| `--help` | Show the help screen | |
| `--version` | Show the program's version | |

#### Example

Run a listener on port 6000 that accepts all inbound HTTP connections for any URL. When the request is received,
attempt to open TCP connections to port 5432 and 3306. If both succeed, return `HTTP 200 OK`. If any fails, return `HTTP
504 Gateway Not Found`.

```
health-checker --listener "0.0.0.0:6000" --port 5432 --port 3306
```

63 changes: 63 additions & 0 deletions commands/cli.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package commands

import (
"github.com/gruntwork-io/gruntwork-cli/errors"
"github.com/gruntwork-io/health-checker/server"
"github.com/urfave/cli"
)

// Create the CLI app with all commands (in this case a single one!), flags, and usage text configured.
func CreateCli(version string) *cli.App {
app := cli.NewApp()

app.CustomAppHelpTemplate = ` NAME:
{{.Name}} - {{.Usage}}
USAGE:
{{.HelpName}} {{if .Flags}}[options]{{end}}
{{if .Commands}}
OPTIONS:
{{range .Flags}}{{.}}
{{end}}{{end}}{{if .Copyright }}
COPYRIGHT:
{{.Copyright}}
{{end}}{{if .Version}}
VERSION:
{{.Version}}
{{end}}{{if len .Authors}}
AUTHOR(S):
{{range .Authors}}{{ . }}{{end}}
{{end}}
`

app.Name = "health-checker"
app.HelpName = app.Name
app.Author = "Gruntwork, Inc. <www.gruntwork.io> | https://github.com/gruntwork-io/health-checker"
app.Version = version
app.Usage = "A simple HTTP server that returns a 200 OK when all given TCP ports accept inbound connections."
app.Commands = nil
app.Flags = defaultFlags
app.Action = runHealthChecker

return app
}

func runHealthChecker(cliContext *cli.Context) error {
if allCliOptionsEmpty(cliContext) {
cli.ShowAppHelpAndExit(cliContext, 0)
}

opts, err := parseOptions(cliContext)
if isSimpleError(err) {
return err
}
if err != nil {
return errors.WithStackTrace(err)
}

opts.Logger.Infof("The Health Check will attempt to connect to the following ports via TCP: %v", opts.Ports)
opts.Logger.Infof("Listening on Port %s...", opts.Listener)
server.StartHttpServer(opts)

return nil
}
88 changes: 88 additions & 0 deletions commands/flags.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package commands

import (
"fmt"
"github.com/gruntwork-io/health-checker/options"
"github.com/gruntwork-io/gruntwork-cli/logging"
"github.com/urfave/cli"
"github.com/sirupsen/logrus"
)

const DEFAULT_LISTENER_IP_ADDRESS = "0.0.0.0"
const DEFAULT_LISTENER_PORT = 5500

var portFlag = cli.IntSliceFlag{
Name: "port",
Usage: fmt.Sprintf("[Required] The port number on which a TCP connection will be attempted. Specify one or more times. Example: 8000"),
}

var listenerFlag = cli.StringFlag{
Name: "listener",
Usage: fmt.Sprintf("[Optional] The IP address and port on which inbound HTTP connections will be accepted."),
Value: fmt.Sprintf("%s:%d", DEFAULT_LISTENER_IP_ADDRESS, DEFAULT_LISTENER_PORT),
}

var logLevelFlag = cli.StringFlag{
Name: "log-level",
Usage: fmt.Sprintf("[Optional] Set the log level to `LEVEL`. Must be one of: %v", logrus.AllLevels),
Value: logrus.InfoLevel.String(),
}

var defaultFlags = []cli.Flag{
portFlag,
listenerFlag,
logLevelFlag,
}

// Return true if all no options at all were passed to the CLI
func allCliOptionsEmpty(cliContext *cli.Context) bool {
return cliContext.NumFlags() == 0
}

// Parse and validate all CLI options
func parseOptions(cliContext *cli.Context) (*options.Options, error) {
logger := logging.GetLogger("health-checker")

logLevel := cliContext.String(logLevelFlag.Name)
level, err := logrus.ParseLevel(logLevel)
if err != nil {
return nil, InvalidLogLevel(logLevel)
}
logger.SetLevel(level)

ports := cliContext.IntSlice("port")
if len(ports) == 0 {
return nil, MissingParam(portFlag.Name)
}

listener := cliContext.String("listener")

return &options.Options{
Ports: ports,
Listener: listener,
Logger: logger,
}, nil
}

// Some error types are simple enough that we'd rather just show the error message directly instead vomiting out a
// whole stack trace in log output
func isSimpleError(err error) bool {
_, isInvalidLogLevelErr := err.(InvalidLogLevel)
_, isMissingParam := err.(MissingParam)

return isInvalidLogLevelErr || isMissingParam
}

// Custom error types

type InvalidLogLevel string

func (invalidLogLevel InvalidLogLevel) Error() string {
return fmt.Sprintf("The log-level value \"%s\" is invalid", string(invalidLogLevel))
}

type MissingParam string

func (paramName MissingParam) Error() string {
return fmt.Sprintf("Missing required parameter --%s", string(paramName))
}
Loading

0 comments on commit 1b4c7ba

Please sign in to comment.