La référence API provient des commentaires de documentation Go du code source et est rédigée en anglais.
package servicehealth
import "github.com/nsgo-dev/game/pkg/online/servicehealth"Vue d’ensemble
Package servicehealth is experimental: its API and documented formats may change in a minor release. See the API stability policy. serves the deployment endpoints of an online service: GET /healthz for liveness, GET /readyz for readiness (a database ping) and GET /metrics in the Prometheus text format. The game server's gameserver.Health and the accountsd, cloudsaved and leaderboardd daemons serve their endpoints through it.
A Health holds the readiness check and the collectors that write /metrics; Requests counts a handler's requests by route and status and times them. Mount a Health on its own listener, never on the one players reach, with Register or as a handler of its own.
Index
- Constantes
- func CheckAddr(addr string) error
- func FormatFloat(v float64) string
- func Label(name, value string) string
- func Loopback(addr string) bool
- func Serve(w http.ResponseWriter, r *http.Request, ready func(ctx context.Context) bool, metrics func(ctx context.Context, w io.Writer))
- type Collector
- type Dropper
- type Health
- func New(ready func(ctx context.Context) error) *Health
- func (h *Health) AddCollector(c Collector)
- func (h *Health) CheckReady(ctx context.Context) error
- func (h *Health) Register(mux *http.ServeMux)
- func (h *Health) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (h *Health) WriteMetrics(ctx context.Context, w io.Writer)
- type Requests
- type Server
Constantes
const DefaultReadyTimeout = 2 * time.SecondDefaultReadyTimeout bounds one readiness check when Health.ReadyTimeout is 0.
const UnmatchedRoute = "unmatched"UnmatchedRoute is the route label of a request no route pattern matched, such as a 404 or a CORS preflight the handler answered before routing.
Fonctions
func CheckAddr(addr string) errorCheckAddr checks that addr is a TCP listen address with a port, such as "127.0.0.1:9101" or ":9101", the form a service configuration's metrics field takes.
func FormatFloat(v float64) stringFormatFloat renders a sample value the way the Prometheus text format expects: the shortest decimal that reads back as v.
func Label(name, value string) stringLabel returns the label pair name="value", with value escaped for the Prometheus text format.
func Loopback(addr string) boolLoopback reports whether addr, a listen address CheckAddr accepts, binds only the loopback interface: its host is "localhost" or a loopback IP. An empty host, such as ":9101", binds every interface and is not loopback.
func Serve(w http.ResponseWriter, r *http.Request, ready func(ctx context.Context) bool, metrics func(ctx context.Context, w io.Writer))Serve answers one request for /healthz, /readyz or /metrics: ready decides /readyz, and metrics writes the body of /metrics. A nil ready is always ready and a nil metrics writes no series. Other paths get 404 and methods other than GET and HEAD get 405. Health.ServeHTTP and gameserver.Health use it, so every service answers its probes the same way.
Types
type Collector func(ctx context.Context, w io.Writer)Collector writes complete series in the Prometheus text format to w: each series' # HELP and # TYPE lines and its samples. It runs on every scrape of /metrics, from the HTTP handler, so it must be safe to call while the service runs; ctx ends with the scrape.
func AuditCollector(d Dropper) CollectorAuditCollector returns a collector that exports d's dropped records as the counter nsgo_audit_dropped_total. A nil d exports nothing.
func Cached(ttl time.Duration, c Collector) CollectorCached returns a collector that runs c at most once per ttl and writes c's last output to every scrape in between, so a collector that scans a database costs one scan per ttl however often, and however many scrapers, scrape. Scrapes that arrive while c runs wait for it and share its output. A ttl of 0 or less runs c on every scrape, as c itself would.
type Dropper interface {
// Dropped reports how many records never reached their destination.
Dropped() uint64
}Dropper is what AuditCollector reads, such as an *audit.Writer.
type Health struct {
// Ready reports nil when the service can serve requests, such as when its database answers a ping (sql.DB.PingContext); nil is always ready.
Ready func(ctx context.Context) error
// ReadyTimeout bounds one call of Ready; 0 means DefaultReadyTimeout. A check that runs past it reports not ready.
ReadyTimeout time.Duration
// contains filtered or unexported fields
}Health serves a service's deployment endpoints:
GET /healthz 200 while the process is alive GET /readyz 200 when Ready returns nil, else 503 GET /metrics the series every collector writes, in the order they were added
The zero Health is always ready and exports no series. Its methods are safe for concurrent use.
func New(ready func(ctx context.Context) error) *HealthNew returns a Health whose readiness is ready.
func (h *Health) AddCollector(c Collector)AddCollector appends c to /metrics. A nil c is ignored.
func (h *Health) CheckReady(ctx context.Context) errorCheckReady runs Ready under ReadyTimeout and returns its result.
func (h *Health) Register(mux *http.ServeMux)Register mounts the three endpoints on mux at GET /healthz, GET /readyz and GET /metrics (GET patterns also match HEAD), so a listener that serves other routes too, such as an admin listener, can carry them.
func (h *Health) ServeHTTP(w http.ResponseWriter, r *http.Request)ServeHTTP handles GET and HEAD requests for /healthz, /readyz and /metrics, refusing other methods with 405 and other paths with 404.
func (h *Health) WriteMetrics(ctx context.Context, w io.Writer)WriteMetrics runs every collector, in the order they were added.
type Requests struct {
// contains filtered or unexported fields
}Requests counts the requests a handler serves, by route and status, and times them. Its route is the http.ServeMux pattern that matched the request (Request.Pattern, such as "POST /v1/guest"), never the raw path, so the number of series stays bounded; a request no pattern matched counts under UnmatchedRoute. The zero Requests is ready to use and safe for concurrent use.
func (q *Requests) Codes(route string) map[int]uint64Codes returns how many requests of route answered each status code so far.
func (q *Requests) Collect(_ context.Context, w io.Writer)Collect writes nsgo_http_requests_total, labeled route and code, and the nsgo_http_request_duration_seconds histogram, labeled route, in route then code order. It is a Collector.
func (q *Requests) Observe(route string, code int, d time.Duration)Observe records one request of route that answered code after d. An empty route counts as UnmatchedRoute.
func (q *Requests) Wrap(next http.Handler) http.HandlerWrap returns a handler that serves with next and records each request in q. next must route with an http.ServeMux that receives the request Wrap passes, directly or through wrappers that pass the same *http.Request on, since the mux sets the request's Pattern. A request whose handler panics is not recorded.
type Server struct {
// contains filtered or unexported fields
}Server is a listener that serves a Health's endpoints, returned by Listen.
func Listen(ctx context.Context, addr string, h *Health, errorLog *log.Logger) (*Server, error)Listen starts listening on addr for h's endpoints and returns the server to Serve and Shutdown. The server mounts only the three endpoints and sets read, write and idle timeouts, since a scraper never needs long requests; errorLog, when set, receives the server's errors, as http.Server.ErrorLog does.
func (s *Server) Addr() stringAddr returns the address the server listens on, with the port the system chose for ":0".
func (s *Server) Serve() errorServe serves until Shutdown, then returns nil; any other error is the listener's.
func (s *Server) Shutdown(ctx context.Context) errorShutdown stops the server gracefully, as http.Server.Shutdown does.