health.go72 lines, 1.8 KB
| 1 | // Package health answers two questions about a process: is it up, and can it |
| 2 | // do its job right now. |
| 3 | package health |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "sync/atomic" |
| 10 | "time" |
| 11 | ) |
| 12 | |
| 13 | // A Check asks one thing this process can't work without, such as its database. |
| 14 | type Check func(ctx context.Context) error |
| 15 | |
| 16 | // Health holds the answers of one process. |
| 17 | type Health struct { |
| 18 | checks []Check |
| 19 | leaving atomic.Bool |
| 20 | } |
| 21 | |
| 22 | func New(checks ...Check) *Health { |
| 23 | return &Health{checks: checks} |
| 24 | } |
| 25 | |
| 26 | // Routes puts both answers on a mux. |
| 27 | func (h *Health) Routes(mux *http.ServeMux) { |
| 28 | mux.HandleFunc("GET /healthz", h.Live) |
| 29 | mux.HandleFunc("GET /readyz", h.Ready) |
| 30 | } |
| 31 | |
| 32 | // Live says the process is up. It asks nobody, so it can't be slow. |
| 33 | func (h *Health) Live(w http.ResponseWriter, r *http.Request) { |
| 34 | fmt.Fprintln(w, "ok") |
| 35 | } |
| 36 | |
| 37 | // Ready says this process can do its job right now. |
| 38 | func (h *Health) Ready(w http.ResponseWriter, r *http.Request) { |
| 39 | if h.leaving.Load() { |
| 40 | http.Error(w, "shutting down", http.StatusServiceUnavailable) |
| 41 | return |
| 42 | } |
| 43 | ctx, cancel := context.WithTimeout(r.Context(), time.Second) |
| 44 | defer cancel() |
| 45 | for _, check := range h.checks { |
| 46 | if err := check(ctx); err != nil { |
| 47 | http.Error(w, err.Error(), http.StatusServiceUnavailable) |
| 48 | return |
| 49 | } |
| 50 | } |
| 51 | fmt.Fprintln(w, "ready") |
| 52 | } |
| 53 | |
| 54 | // Leave is the first step of a shutdown. From here on, Ready says no. |
| 55 | func (h *Health) Leave() { |
| 56 | h.leaving.Store(true) |
| 57 | } |
| 58 | |
| 59 | // Probe asks the process on this machine's private port if it is ready. |
| 60 | // A container without curl checks its own health with it. |
| 61 | func Probe(addr string) error { |
| 62 | client := http.Client{Timeout: 2 * time.Second} |
| 63 | res, err := client.Get("http://localhost" + addr + "/readyz") |
| 64 | if err != nil { |
| 65 | return err |
| 66 | } |
| 67 | defer res.Body.Close() |
| 68 | if res.StatusCode != http.StatusOK { |
| 69 | return fmt.Errorf("not ready: %s", res.Status) |
| 70 | } |
| 71 | return nil |
| 72 | } |