traefik/cmd/healthcheck/healthcheck.go

75 lines
1.9 KiB
Go
Raw Normal View History

2018-03-01 07:10:04 +00:00
package healthcheck
2017-11-09 16:08:03 +00:00
import (
2017-11-23 15:10:04 +00:00
"errors"
2017-11-09 16:08:03 +00:00
"fmt"
"net/http"
"os"
"time"
"github.com/containous/traefik/pkg/cli"
2019-03-15 08:42:03 +00:00
"github.com/containous/traefik/pkg/config/static"
2017-11-09 16:08:03 +00:00
)
// NewCmd builds a new HealthCheck command.
func NewCmd(traefikConfiguration *static.Configuration, loaders []cli.ResourceLoader) *cli.Command {
return &cli.Command{
Name: "healthcheck",
Description: `Calls Traefik /ping to check the health of Traefik (the API must be enabled).`,
Configuration: traefikConfiguration,
Run: runCmd(traefikConfiguration),
Resources: loaders,
2017-11-09 16:08:03 +00:00
}
}
func runCmd(traefikConfiguration *static.Configuration) func(_ []string) error {
return func(_ []string) error {
traefikConfiguration.SetEffectiveConfiguration()
2017-11-09 16:08:03 +00:00
resp, errPing := Do(*traefikConfiguration)
if resp != nil {
resp.Body.Close()
}
2017-11-09 16:08:03 +00:00
if errPing != nil {
fmt.Printf("Error calling healthcheck: %s\n", errPing)
os.Exit(1)
}
2017-11-09 16:08:03 +00:00
if resp.StatusCode != http.StatusOK {
fmt.Printf("Bad healthcheck status: %s\n", resp.Status)
os.Exit(1)
}
fmt.Printf("OK: %s\n", resp.Request.URL)
os.Exit(0)
return nil
}
}
2017-11-23 15:10:04 +00:00
2018-03-01 07:10:04 +00:00
// Do try to do a healthcheck
func Do(staticConfiguration static.Configuration) (*http.Response, error) {
if staticConfiguration.Ping == nil {
2018-02-13 22:42:03 +00:00
return nil, errors.New("please enable `ping` to use health check")
}
pingEntryPoint, ok := staticConfiguration.EntryPoints[staticConfiguration.Ping.EntryPoint]
2017-11-23 15:10:04 +00:00
if !ok {
2018-02-13 22:42:03 +00:00
return nil, errors.New("missing `ping` entrypoint")
2017-11-23 15:10:04 +00:00
}
client := &http.Client{Timeout: 5 * time.Second}
protocol := "http"
// FIXME Handle TLS on ping etc...
// if pingEntryPoint.TLS != nil {
// protocol = "https"
// tr := &http.Transport{
// TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
// }
// client.Transport = tr
// }
path := "/"
2018-07-31 17:28:03 +00:00
return client.Head(protocol + "://" + pingEntryPoint.Address + path + "ping")
2017-11-23 15:10:04 +00:00
}