package hostedctl import ( "context" "database/sql" "fmt" "io" "maps" "net/http" "slices" "strings" "sync" "time" ) // Metrics counts what the API and the alerter did since the process // started, and renders those counts with the controller's current state as // Prometheus text on a listener of its own. It is safe for concurrent use; // a nil *Metrics counts nothing. type Metrics struct { mu sync.Mutex launches map[string]uint64 // the launched job's state, or the refusal's code errs map[[2]string]uint64 // route, code alerts map[[2]string]uint64 // kind, "sent" or "failed" } // NewMetrics returns empty counts. func NewMetrics() *Metrics { return &Metrics{launches: map[string]uint64{}, errs: map[[2]string]uint64{}, alerts: map[[2]string]uint64{}} } func (m *Metrics) launch(result string) { if m == nil { return } m.mu.Lock() defer m.mu.Unlock() m.launches[result]++ } func (m *Metrics) apiError(route, code string) { if m == nil { return } m.mu.Lock() defer m.mu.Unlock() m.errs[[2]string{route, code}]++ } // CountAlerts wraps next so each alert it is given is counted by kind, as // sent or failed. func (m *Metrics) CountAlerts(next Alerter) Alerter { return countingAlerter{m: m, next: next} } type countingAlerter struct { m *Metrics next Alerter } func (a countingAlerter) Alert(ctx context.Context, al Alert) error { err := a.next.Alert(ctx, al) if a.m != nil { result := "sent" if err != nil { result = "failed" } a.m.mu.Lock() a.m.alerts[[2]string{al.Kind, result}]++ a.m.mu.Unlock() } return err } // knownStates are the job states always reported, as 0 when no job is in // them, once the store has been read. var knownStates = []string{JobWaiting, JobStarting, JobRunning, JobDraining, JobSuspending, JobSuspended, JobResuming, JobStopping, JobStopped, JobAbandoned} // Handler serves GET /metrics for c. A value the controller cannot read now // is left out rather than shown as zero: the job counts when the store read // fails, the audit status before any audit has run, and the reaper's results // before its first pass. func (m *Metrics) Handler(c *Controller) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/metrics" { http.NotFound(w, r) return } if r.Method != http.MethodGet { w.WriteHeader(http.StatusMethodNotAllowed) return } w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8") m.write(r.Context(), w, c) }) } func (m *Metrics) write(ctx context.Context, w io.Writer, c *Controller) { p := promWriter{w: w} counts, err := c.jobsByState(ctx) p.head("equipo_hosted_store_readable", "gauge", "1 when the metrics read of the job table worked, else 0.") p.sample("equipo_hosted_store_readable", nil, boolValue(err == nil)) p.head("equipo_hosted_jobs", "gauge", "Jobs by state. Absent when the store could not be read.") if err == nil { states := slices.Clone(knownStates) for s := range counts { if !slices.Contains(states, s) { states = append(states, s) } } for _, s := range states { p.sample("equipo_hosted_jobs", []string{"state", s}, float64(counts[s])) } } now := c.store.Clock().Now() p.head("equipo_hosted_network_audit_passing", "gauge", "1 when the last network audit passed and is fresh enough for launches, else 0. Absent before the first audit.") if passing, ran := c.audit.status(now); ran { p.sample("equipo_hosted_network_audit_passing", nil, boolValue(passing)) } last, ran := c.LastReap() for _, g := range []struct { name, help string v float64 }{ {"equipo_hosted_reap_last_error", "1 when the last reaper pass returned an error, else 0.", boolValue(last.Err != nil)}, {"equipo_hosted_reap_last_orphans_stopped", "Orphan VMs the last reaper pass asked the provider to stop.", float64(last.Report.OrphansStopped)}, {"equipo_hosted_reap_last_orphans_deferred", "Orphan VMs past their grace the last reaper pass left running for a waiting intent.", float64(last.Report.OrphansDeferred)}, {"equipo_hosted_reap_last_age_seconds", "Controller time since the last reaper pass finished.", time.Duration(now - last.At).Seconds()}, } { p.head(g.name, "gauge", g.help+" Absent before the first pass.") if ran { p.sample(g.name, nil, g.v) } } m.mu.Lock() launches, errs, alerts := maps.Clone(m.launches), maps.Clone(m.errs), maps.Clone(m.alerts) m.mu.Unlock() p.head("equipo_hosted_launches_total", "counter", "Launch requests answered, by the job state returned or the refusal's code.") for _, k := range slices.Sorted(maps.Keys(launches)) { p.sample("equipo_hosted_launches_total", []string{"result", k}, float64(launches[k])) } p.head("equipo_hosted_errors_total", "counter", "API requests answered from the error table, by route and code (stop_pending, a 202, included). Route unverified is a request that failed its signature check.") for _, k := range slices.SortedFunc(maps.Keys(errs), comparePair) { p.sample("equipo_hosted_errors_total", []string{"route", k[0], "code", k[1]}, float64(errs[k])) } p.head("equipo_hosted_alerts_total", "counter", "Operator alerts by kind, sent or failed.") for _, k := range slices.SortedFunc(maps.Keys(alerts), comparePair) { p.sample("equipo_hosted_alerts_total", []string{"kind", k[0], "result", k[1]}, float64(alerts[k])) } } func comparePair(a, b [2]string) int { if c := strings.Compare(a[0], b[0]); c != 0 { return c } return strings.Compare(a[1], b[1]) } func boolValue(b bool) float64 { if b { return 1 } return 0 } // jobsByState counts the job table by state. func (c *Controller) jobsByState(ctx context.Context) (map[string]int64, error) { out := map[string]int64{} err := c.store.Tx(ctx, func(tx *sql.Tx) error { rows, err := tx.QueryContext(ctx, `SELECT state, count(*) FROM jobs GROUP BY state`) if err != nil { return err } defer rows.Close() for rows.Next() { var s string var n int64 if err := rows.Scan(&s, &n); err != nil { return err } out[s] = n } return rows.Err() }) if err != nil { return nil, fmt.Errorf("hostedctl: count jobs by state: %w", err) } return out, nil } // status reports whether the last audit passes the launch gate at now, and // whether any audit has run. func (s *auditState) status(now T) (passing, ran bool) { s.mu.Lock() ran = s.ran s.mu.Unlock() return s.check(now) == nil, ran } // promWriter writes the Prometheus text format. type promWriter struct{ w io.Writer } func (p promWriter) head(name, typ, help string) { fmt.Fprintf(p.w, "# HELP %s %s\n# TYPE %s %s\n", name, help, name, typ) } // sample writes one line; labels alternate names and values. func (p promWriter) sample(name string, labels []string, v float64) { var b strings.Builder b.WriteString(name) if len(labels) > 0 { b.WriteByte('{') for i := 0; i+1 < len(labels); i += 2 { if i > 0 { b.WriteByte(',') } fmt.Fprintf(&b, "%s=\"%s\"", labels[i], labelEscaper.Replace(labels[i+1])) } b.WriteByte('}') } fmt.Fprintf(&b, " %v\n", v) _, _ = io.WriteString(p.w, b.String()) } var labelEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`)