| 1 | package hostedctl |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "maps" |
| 9 | "net/http" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | // Metrics counts what the API and the alerter did since the process |
| 17 | // started, and renders those counts with the controller's current state as |
| 18 | // Prometheus text on a listener of its own. It is safe for concurrent use; |
| 19 | // a nil *Metrics counts nothing. |
| 20 | type Metrics struct { |
| 21 | mu sync.Mutex |
| 22 | launches map[string]uint64 // the launched job's state, or the refusal's code |
| 23 | errs map[[2]string]uint64 // route, code |
| 24 | alerts map[[2]string]uint64 // kind, "sent" or "failed" |
| 25 | } |
| 26 | |
| 27 | // NewMetrics returns empty counts. |
| 28 | func NewMetrics() *Metrics { |
| 29 | return &Metrics{launches: map[string]uint64{}, errs: map[[2]string]uint64{}, alerts: map[[2]string]uint64{}} |
| 30 | } |
| 31 | |
| 32 | func (m *Metrics) launch(result string) { |
| 33 | if m == nil { |
| 34 | return |
| 35 | } |
| 36 | m.mu.Lock() |
| 37 | defer m.mu.Unlock() |
| 38 | m.launches[result]++ |
| 39 | } |
| 40 | |
| 41 | func (m *Metrics) apiError(route, code string) { |
| 42 | if m == nil { |
| 43 | return |
| 44 | } |
| 45 | m.mu.Lock() |
| 46 | defer m.mu.Unlock() |
| 47 | m.errs[[2]string{route, code}]++ |
| 48 | } |
| 49 | |
| 50 | // CountAlerts wraps next so each alert it is given is counted by kind, as |
| 51 | // sent or failed. |
| 52 | func (m *Metrics) CountAlerts(next Alerter) Alerter { |
| 53 | return countingAlerter{m: m, next: next} |
| 54 | } |
| 55 | |
| 56 | type countingAlerter struct { |
| 57 | m *Metrics |
| 58 | next Alerter |
| 59 | } |
| 60 | |
| 61 | func (a countingAlerter) Alert(ctx context.Context, al Alert) error { |
| 62 | err := a.next.Alert(ctx, al) |
| 63 | if a.m != nil { |
| 64 | result := "sent" |
| 65 | if err != nil { |
| 66 | result = "failed" |
| 67 | } |
| 68 | a.m.mu.Lock() |
| 69 | a.m.alerts[[2]string{al.Kind, result}]++ |
| 70 | a.m.mu.Unlock() |
| 71 | } |
| 72 | return err |
| 73 | } |
| 74 | |
| 75 | // knownStates are the job states always reported, as 0 when no job is in |
| 76 | // them, once the store has been read. |
| 77 | var knownStates = []string{JobWaiting, JobStarting, JobRunning, JobDraining, JobSuspending, JobSuspended, |
| 78 | JobResuming, JobStopping, JobStopped, JobAbandoned} |
| 79 | |
| 80 | // Handler serves GET /metrics for c. A value the controller cannot read now |
| 81 | // is left out rather than shown as zero: the job counts when the store read |
| 82 | // fails, the audit status before any audit has run, and the reaper's results |
| 83 | // before its first pass. |
| 84 | func (m *Metrics) Handler(c *Controller) http.Handler { |
| 85 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 86 | if r.URL.Path != "/metrics" { |
| 87 | http.NotFound(w, r) |
| 88 | return |
| 89 | } |
| 90 | if r.Method != http.MethodGet { |
| 91 | w.WriteHeader(http.StatusMethodNotAllowed) |
| 92 | return |
| 93 | } |
| 94 | w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8") |
| 95 | m.write(r.Context(), w, c) |
| 96 | }) |
| 97 | } |
| 98 | |
| 99 | func (m *Metrics) write(ctx context.Context, w io.Writer, c *Controller) { |
| 100 | p := promWriter{w: w} |
| 101 | |
| 102 | counts, err := c.jobsByState(ctx) |
| 103 | p.head("equipo_hosted_store_readable", "gauge", "1 when the metrics read of the job table worked, else 0.") |
| 104 | p.sample("equipo_hosted_store_readable", nil, boolValue(err == nil)) |
| 105 | p.head("equipo_hosted_jobs", "gauge", "Jobs by state. Absent when the store could not be read.") |
| 106 | if err == nil { |
| 107 | states := slices.Clone(knownStates) |
| 108 | for s := range counts { |
| 109 | if !slices.Contains(states, s) { |
| 110 | states = append(states, s) |
| 111 | } |
| 112 | } |
| 113 | for _, s := range states { |
| 114 | p.sample("equipo_hosted_jobs", []string{"state", s}, float64(counts[s])) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | now := c.store.Clock().Now() |
| 119 | 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.") |
| 120 | if passing, ran := c.audit.status(now); ran { |
| 121 | p.sample("equipo_hosted_network_audit_passing", nil, boolValue(passing)) |
| 122 | } |
| 123 | |
| 124 | last, ran := c.LastReap() |
| 125 | for _, g := range []struct { |
| 126 | name, help string |
| 127 | v float64 |
| 128 | }{ |
| 129 | {"equipo_hosted_reap_last_error", "1 when the last reaper pass returned an error, else 0.", boolValue(last.Err != nil)}, |
| 130 | {"equipo_hosted_reap_last_orphans_stopped", "Orphan VMs the last reaper pass asked the provider to stop.", float64(last.Report.OrphansStopped)}, |
| 131 | {"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)}, |
| 132 | {"equipo_hosted_reap_last_age_seconds", "Controller time since the last reaper pass finished.", time.Duration(now - last.At).Seconds()}, |
| 133 | } { |
| 134 | p.head(g.name, "gauge", g.help+" Absent before the first pass.") |
| 135 | if ran { |
| 136 | p.sample(g.name, nil, g.v) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | m.mu.Lock() |
| 141 | launches, errs, alerts := maps.Clone(m.launches), maps.Clone(m.errs), maps.Clone(m.alerts) |
| 142 | m.mu.Unlock() |
| 143 | p.head("equipo_hosted_launches_total", "counter", "Launch requests answered, by the job state returned or the refusal's code.") |
| 144 | for _, k := range slices.Sorted(maps.Keys(launches)) { |
| 145 | p.sample("equipo_hosted_launches_total", []string{"result", k}, float64(launches[k])) |
| 146 | } |
| 147 | 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.") |
| 148 | for _, k := range slices.SortedFunc(maps.Keys(errs), comparePair) { |
| 149 | p.sample("equipo_hosted_errors_total", []string{"route", k[0], "code", k[1]}, float64(errs[k])) |
| 150 | } |
| 151 | p.head("equipo_hosted_alerts_total", "counter", "Operator alerts by kind, sent or failed.") |
| 152 | for _, k := range slices.SortedFunc(maps.Keys(alerts), comparePair) { |
| 153 | p.sample("equipo_hosted_alerts_total", []string{"kind", k[0], "result", k[1]}, float64(alerts[k])) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | func comparePair(a, b [2]string) int { |
| 158 | if c := strings.Compare(a[0], b[0]); c != 0 { |
| 159 | return c |
| 160 | } |
| 161 | return strings.Compare(a[1], b[1]) |
| 162 | } |
| 163 | |
| 164 | func boolValue(b bool) float64 { |
| 165 | if b { |
| 166 | return 1 |
| 167 | } |
| 168 | return 0 |
| 169 | } |
| 170 | |
| 171 | // jobsByState counts the job table by state. |
| 172 | func (c *Controller) jobsByState(ctx context.Context) (map[string]int64, error) { |
| 173 | out := map[string]int64{} |
| 174 | err := c.store.Tx(ctx, func(tx *sql.Tx) error { |
| 175 | rows, err := tx.QueryContext(ctx, `SELECT state, count(*) FROM jobs GROUP BY state`) |
| 176 | if err != nil { |
| 177 | return err |
| 178 | } |
| 179 | defer rows.Close() |
| 180 | for rows.Next() { |
| 181 | var s string |
| 182 | var n int64 |
| 183 | if err := rows.Scan(&s, &n); err != nil { |
| 184 | return err |
| 185 | } |
| 186 | out[s] = n |
| 187 | } |
| 188 | return rows.Err() |
| 189 | }) |
| 190 | if err != nil { |
| 191 | return nil, fmt.Errorf("hostedctl: count jobs by state: %w", err) |
| 192 | } |
| 193 | return out, nil |
| 194 | } |
| 195 | |
| 196 | // status reports whether the last audit passes the launch gate at now, and |
| 197 | // whether any audit has run. |
| 198 | func (s *auditState) status(now T) (passing, ran bool) { |
| 199 | s.mu.Lock() |
| 200 | ran = s.ran |
| 201 | s.mu.Unlock() |
| 202 | return s.check(now) == nil, ran |
| 203 | } |
| 204 | |
| 205 | // promWriter writes the Prometheus text format. |
| 206 | type promWriter struct{ w io.Writer } |
| 207 | |
| 208 | func (p promWriter) head(name, typ, help string) { |
| 209 | fmt.Fprintf(p.w, "# HELP %s %s\n# TYPE %s %s\n", name, help, name, typ) |
| 210 | } |
| 211 | |
| 212 | // sample writes one line; labels alternate names and values. |
| 213 | func (p promWriter) sample(name string, labels []string, v float64) { |
| 214 | var b strings.Builder |
| 215 | b.WriteString(name) |
| 216 | if len(labels) > 0 { |
| 217 | b.WriteByte('{') |
| 218 | for i := 0; i+1 < len(labels); i += 2 { |
| 219 | if i > 0 { |
| 220 | b.WriteByte(',') |
| 221 | } |
| 222 | fmt.Fprintf(&b, "%s=\"%s\"", labels[i], labelEscaper.Replace(labels[i+1])) |
| 223 | } |
| 224 | b.WriteByte('}') |
| 225 | } |
| 226 | fmt.Fprintf(&b, " %v\n", v) |
| 227 | _, _ = io.WriteString(p.w, b.String()) |
| 228 | } |
| 229 | |
| 230 | var labelEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`) |
| 231 | |