health.go99 lines, 3.0 KB
| 1 | // Package health serves a service's probes. Liveness, on /healthz: the process |
| 2 | // is up, and answering. Readiness, on /readyz: it can do its job right now, so |
| 3 | // it should be sent traffic. |
| 4 | package health |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "fmt" |
| 9 | "log/slog" |
| 10 | "maps" |
| 11 | "net" |
| 12 | "net/http" |
| 13 | "slices" |
| 14 | "sync/atomic" |
| 15 | "time" |
| 16 | |
| 17 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 18 | ) |
| 19 | |
| 20 | // A Check reports whether something the service needs is reachable. |
| 21 | type Check func(ctx context.Context) error |
| 22 | |
| 23 | // Probes answers /healthz and /readyz. |
| 24 | type Probes struct { |
| 25 | logger *slog.Logger |
| 26 | checks map[string]Check |
| 27 | draining atomic.Bool |
| 28 | } |
| 29 | |
| 30 | // New returns probes whose readiness runs checks, each under its name. |
| 31 | func New(logger *slog.Logger, checks map[string]Check) *Probes { |
| 32 | return &Probes{logger: logger, checks: checks} |
| 33 | } |
| 34 | |
| 35 | // Register serves both probes on mux. |
| 36 | func (p *Probes) Register(mux *http.ServeMux) { |
| 37 | mux.HandleFunc("GET /healthz", p.live) |
| 38 | mux.HandleFunc("GET /readyz", p.ready) |
| 39 | } |
| 40 | |
| 41 | // live checks nothing else, on purpose. If it checked the database, an outage |
| 42 | // would get every instance restarted, which fixes nothing, and makes it worse. |
| 43 | func (p *Probes) live(w http.ResponseWriter, r *http.Request) { |
| 44 | httpx.WriteJSON(w, r, http.StatusOK, map[string]string{"status": "ok"}) |
| 45 | } |
| 46 | |
| 47 | // ready runs every check, with one deadline for all of them. |
| 48 | func (p *Probes) ready(w http.ResponseWriter, r *http.Request) { |
| 49 | if p.draining.Load() { |
| 50 | httpx.WriteJSON(w, r, http.StatusServiceUnavailable, map[string]string{"status": "draining"}) |
| 51 | return |
| 52 | } |
| 53 | ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) |
| 54 | defer cancel() |
| 55 | var failed []string |
| 56 | for _, name := range slices.Sorted(maps.Keys(p.checks)) { |
| 57 | if err := p.checks[name](ctx); err != nil { |
| 58 | p.logger.WarnContext(ctx, "not ready", "check", name, "err", err) |
| 59 | failed = append(failed, name) |
| 60 | } |
| 61 | } |
| 62 | if len(failed) > 0 { |
| 63 | body := map[string]any{"status": "unavailable", "failed": failed} |
| 64 | httpx.WriteJSON(w, r, http.StatusServiceUnavailable, body) |
| 65 | return |
| 66 | } |
| 67 | httpx.WriteJSON(w, r, http.StatusOK, map[string]string{"status": "ready"}) |
| 68 | } |
| 69 | |
| 70 | // Drain makes readiness fail, and then waits for delay: long enough for load |
| 71 | // balancers to notice, and stop sending new requests, before the server stops |
| 72 | // accepting them. |
| 73 | func (p *Probes) Drain(delay time.Duration) { |
| 74 | p.draining.Store(true) |
| 75 | if delay > 0 { |
| 76 | p.logger.Info("draining: readiness fails from now on", "delay", delay) |
| 77 | time.Sleep(delay) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | // Probe asks the service listening on addr, like :8081, whether it's ready. |
| 82 | // It's a container's health check: our images have no curl, and no shell to |
| 83 | // run one, so the binary checks itself. |
| 84 | func Probe(addr string) error { |
| 85 | _, port, err := net.SplitHostPort(addr) |
| 86 | if err != nil { |
| 87 | return fmt.Errorf("healthcheck: %w", err) |
| 88 | } |
| 89 | client := &http.Client{Timeout: 2 * time.Second} |
| 90 | resp, err := client.Get("http://127.0.0.1:" + port + "/readyz") |
| 91 | if err != nil { |
| 92 | return fmt.Errorf("healthcheck: %w", err) |
| 93 | } |
| 94 | resp.Body.Close() |
| 95 | if resp.StatusCode != http.StatusOK { |
| 96 | return fmt.Errorf("healthcheck: %s", resp.Status) |
| 97 | } |
| 98 | return nil |
| 99 | } |