2018-03-01 08:10:04 +01:00
package healthcheck
2017-11-09 17:08:03 +01:00
import (
2017-11-23 16:10:04 +01:00
"errors"
2017-11-09 17:08:03 +01:00
"fmt"
"net/http"
"os"
"time"
2020-08-17 18:04:03 +02:00
"github.com/traefik/paerser/cli"
2020-09-16 15:46:04 +02:00
"github.com/traefik/traefik/v2/pkg/config/static"
2017-11-09 17:08:03 +01:00
)
2019-06-17 11:48:05 +02:00
// NewCmd builds a new HealthCheck command.
func NewCmd ( traefikConfiguration * static . Configuration , loaders [ ] cli . ResourceLoader ) * cli . Command {
return & cli . Command {
Name : "healthcheck" ,
2019-10-07 15:12:05 +02:00
Description : ` Calls Traefik /ping endpoint (disabled by default) to check the health of Traefik. ` ,
2019-06-17 11:48:05 +02:00
Configuration : traefikConfiguration ,
Run : runCmd ( traefikConfiguration ) ,
Resources : loaders ,
2017-11-09 17:08:03 +01:00
}
}
2019-06-17 11:48:05 +02:00
func runCmd ( traefikConfiguration * static . Configuration ) func ( _ [ ] string ) error {
return func ( _ [ ] string ) error {
2019-07-15 10:22:03 +02:00
traefikConfiguration . SetEffectiveConfiguration ( )
2017-11-09 17:08:03 +01:00
2019-06-17 11:48:05 +02:00
resp , errPing := Do ( * traefikConfiguration )
if resp != nil {
resp . Body . Close ( )
}
2017-11-09 17:08:03 +01:00
if errPing != nil {
fmt . Printf ( "Error calling healthcheck: %s\n" , errPing )
os . Exit ( 1 )
}
2019-06-17 11:48:05 +02:00
2017-11-09 17:08:03 +01: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 16:10:04 +01:00
2020-05-11 12:06:07 +02:00
// Do try to do a healthcheck.
2018-11-27 17:42:04 +01:00
func Do ( staticConfiguration static . Configuration ) ( * http . Response , error ) {
if staticConfiguration . Ping == nil {
2018-02-13 23:42:03 +01:00
return nil , errors . New ( "please enable `ping` to use health check" )
}
2019-06-17 11:48:05 +02:00
2019-11-20 18:34:05 +01:00
ep := staticConfiguration . Ping . EntryPoint
if ep == "" {
ep = "traefik"
}
pingEntryPoint , ok := staticConfiguration . EntryPoints [ ep ]
2017-11-23 16:10:04 +01:00
if ! ok {
2019-11-20 18:34:05 +01:00
return nil , fmt . Errorf ( "ping: missing %s entry point" , ep )
2017-11-23 16:10:04 +01:00
}
client := & http . Client { Timeout : 5 * time . Second }
protocol := "http"
2018-11-27 17:42:04 +01:00
2022-08-31 08:24:08 +02:00
// TODO Handle TLS on ping etc...
2019-03-14 09:30:04 +01:00
// if pingEntryPoint.TLS != nil {
// protocol = "https"
// tr := &http.Transport{
// TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
// }
// client.Transport = tr
// }
2018-11-27 17:42:04 +01:00
2017-12-06 11:20:03 +01:00
path := "/"
2018-07-31 19:28:03 +02:00
2020-02-11 01:26:04 +01:00
return client . Head ( protocol + "://" + pingEntryPoint . GetAddress ( ) + path + "ping" )
2017-11-23 16:10:04 +01:00
}