2016-09-25 08:39:20 +01:00
|
|
|
// Package health implements an HTTP handler that responds to health checks.
|
2016-04-06 09:21:46 +01:00
|
|
|
package health
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"io"
|
2016-04-29 07:28:35 +01:00
|
|
|
"net"
|
2016-04-06 09:21:46 +01:00
|
|
|
"net/http"
|
2018-01-18 10:40:09 +00:00
|
|
|
"time"
|
2018-04-19 07:41:56 +01:00
|
|
|
|
2018-04-22 21:40:33 +01:00
|
|
|
clog "github.com/coredns/coredns/plugin/pkg/log"
|
2019-11-20 20:14:37 +08:00
|
|
|
"github.com/coredns/coredns/plugin/pkg/reuseport"
|
2016-04-06 09:21:46 +01:00
|
|
|
)
|
|
|
|
|
|
2018-04-22 21:40:33 +01:00
|
|
|
var log = clog.NewWithPlugin("health")
|
|
|
|
|
|
2019-05-04 21:06:04 +01:00
|
|
|
// Health implements healthchecks by exporting a HTTP endpoint.
|
2016-09-23 09:14:12 +01:00
|
|
|
type health struct {
|
2018-01-18 10:40:09 +00:00
|
|
|
Addr string
|
|
|
|
|
lameduck time.Duration
|
2016-08-19 17:14:17 -07:00
|
|
|
|
2018-04-21 17:43:02 +01:00
|
|
|
ln net.Listener
|
|
|
|
|
nlSetup bool
|
|
|
|
|
mux *http.ServeMux
|
2017-08-27 21:33:38 +01:00
|
|
|
|
2019-03-07 22:13:47 +00:00
|
|
|
stop chan bool
|
2018-01-18 10:40:09 +00:00
|
|
|
}
|
|
|
|
|
|
2018-01-10 11:41:22 +00:00
|
|
|
func (h *health) OnStartup() error {
|
2016-04-06 09:21:46 +01:00
|
|
|
if h.Addr == "" {
|
2019-05-04 21:06:04 +01:00
|
|
|
h.Addr = ":8080"
|
2016-04-06 09:21:46 +01:00
|
|
|
}
|
2019-05-04 21:06:25 +01:00
|
|
|
h.stop = make(chan bool)
|
2019-11-20 20:14:37 +08:00
|
|
|
ln, err := reuseport.Listen("tcp", h.Addr)
|
2018-03-02 21:40:14 -08:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
h.ln = ln
|
|
|
|
|
h.mux = http.NewServeMux()
|
2018-04-21 17:43:02 +01:00
|
|
|
h.nlSetup = true
|
2018-03-02 21:40:14 -08:00
|
|
|
|
2019-05-04 21:06:04 +01:00
|
|
|
h.mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
2019-03-07 22:13:47 +00:00
|
|
|
// We're always healthy.
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
2019-08-26 18:31:24 +08:00
|
|
|
io.WriteString(w, http.StatusText(http.StatusOK))
|
2016-04-06 09:21:46 +01:00
|
|
|
})
|
2018-03-02 21:40:14 -08:00
|
|
|
|
|
|
|
|
go func() { http.Serve(h.ln, h.mux) }()
|
|
|
|
|
go func() { h.overloaded() }()
|
|
|
|
|
|
2016-04-06 09:21:46 +01:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2018-04-21 17:43:02 +01:00
|
|
|
func (h *health) OnFinalShutdown() error {
|
|
|
|
|
if !h.nlSetup {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2018-01-18 10:40:09 +00:00
|
|
|
if h.lameduck > 0 {
|
2018-04-19 07:41:56 +01:00
|
|
|
log.Infof("Going into lameduck mode for %s", h.lameduck)
|
2018-01-18 10:40:09 +00:00
|
|
|
time.Sleep(h.lameduck)
|
|
|
|
|
}
|
|
|
|
|
|
2018-04-21 17:43:02 +01:00
|
|
|
h.ln.Close()
|
2018-01-10 11:41:22 +00:00
|
|
|
|
2018-04-21 17:43:02 +01:00
|
|
|
h.nlSetup = false
|
2019-03-07 22:13:47 +00:00
|
|
|
close(h.stop)
|
2016-04-29 07:28:35 +01:00
|
|
|
return nil
|
|
|
|
|
}
|