ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m10s
ci / test (pull_request) Successful in 12m19s
ci / build (pull_request) Successful in 18m13s
ci / image (pull_request) Successful in 5m20s
Every console page that shows monitor status (monitors, incidents, monitor details, evidence) went through one loader that read, for all of the organization's monitors: - the newest result per monitor and region, by scanning a day of raw results; - the bars of the selected range, from raw results for ranges up to 24h, though only one page of monitors is shown; - when each monitor first reported, scanning two days of results. With 3000 monitors that took about a second, growing with the number of results. Now: - latest_results keeps the newest result per monitor and region, updated as results are stored (migration 00055 fills it from the last day); - bars are loaded only for the monitors a page shows; - first data is loaded per monitor on its page, and the monitor list asks only for the organization's earliest data, by index; - monitor, region and incident queries name the organization, so their indexes are used instead of row security filtering whole tables. Public status pages also read only their own monitors' latest results and hourly buckets instead of the whole organization's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
343 lines
11 KiB
Go
343 lines
11 KiB
Go
package api
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
"net/http"
|
||
"slices"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
|
||
"github.com/a-h/templ"
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/google/uuid"
|
||
"github.com/redis/go-redis/v9"
|
||
|
||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
|
||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||
)
|
||
|
||
// running:<instance> maps monitor IDs to "<org>|<taken ms>|<timeout ms>"
|
||
// for runs handed out and not yet reported. It shows what a checker is
|
||
// doing; entries of crashed instances are ignored once their checks would
|
||
// have timed out.
|
||
func runningKey(instance uuid.UUID) string { return "running:" + instance.String() }
|
||
|
||
// runningGrace is how long past its timeout a run counts as in progress,
|
||
// covering the report delay.
|
||
const runningGrace = 30 * time.Second
|
||
|
||
func (s *Server) trackRunning(ctx context.Context, instance uuid.UUID, jobs []agentapi.Job, orgs map[uuid.UUID]uuid.UUID) {
|
||
if len(jobs) == 0 {
|
||
return
|
||
}
|
||
now := time.Now().UnixMilli()
|
||
fields := make([]any, 0, 2*len(jobs))
|
||
for _, j := range jobs {
|
||
fields = append(fields, j.MonitorID.String(), fmt.Sprintf("%s|%d|%d", orgs[j.MonitorID], now, j.TimeoutMS))
|
||
}
|
||
key := runningKey(instance)
|
||
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
||
p.HSet(ctx, key, fields...)
|
||
p.Expire(ctx, key, 15*time.Minute)
|
||
return nil
|
||
})
|
||
if err != nil {
|
||
s.log.WarnContext(ctx, "tracking running checks failed", "error", err)
|
||
}
|
||
}
|
||
|
||
func (s *Server) finishRunning(ctx context.Context, instance uuid.UUID, results []agentapi.Result) {
|
||
if len(results) == 0 {
|
||
return
|
||
}
|
||
ids := make([]string, len(results))
|
||
for i, r := range results {
|
||
ids[i] = r.MonitorID.String()
|
||
}
|
||
if err := s.rdb.HDel(ctx, runningKey(instance), ids...).Err(); err != nil {
|
||
s.log.WarnContext(ctx, "clearing running checks failed", "error", err)
|
||
}
|
||
}
|
||
|
||
// runningRun is a check an instance is working on.
|
||
type runningRun struct {
|
||
MonitorID uuid.UUID
|
||
Org uuid.UUID
|
||
Since time.Time
|
||
}
|
||
|
||
func (s *Server) runningOn(ctx context.Context, instance uuid.UUID, now time.Time) ([]runningRun, error) {
|
||
all, err := s.rdb.HGetAll(ctx, runningKey(instance)).Result()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
var out []runningRun
|
||
for id, v := range all {
|
||
parts := strings.Split(v, "|")
|
||
if len(parts) != 3 {
|
||
continue
|
||
}
|
||
m, err1 := uuid.Parse(id)
|
||
org, err2 := uuid.Parse(parts[0])
|
||
at, err3 := strconv.ParseInt(parts[1], 10, 64)
|
||
timeout, err4 := strconv.ParseInt(parts[2], 10, 64)
|
||
if err1 != nil || err2 != nil || err3 != nil || err4 != nil {
|
||
continue
|
||
}
|
||
since := time.UnixMilli(at)
|
||
if now.Sub(since) > time.Duration(timeout)*time.Millisecond+runningGrace {
|
||
continue
|
||
}
|
||
out = append(out, runningRun{MonitorID: m, Org: org, Since: since})
|
||
}
|
||
slices.SortFunc(out, func(a, b runningRun) int { return a.Since.Compare(b.Since) })
|
||
return out, nil
|
||
}
|
||
|
||
// checkerActivity is what the console and API show of a checker instance.
|
||
// Platform checkers work for every organization: only the viewer's own
|
||
// monitors are named, the rest is counted.
|
||
type checkerActivity struct {
|
||
ID uuid.UUID `json:"id"`
|
||
Agent string `json:"agent"`
|
||
Region string `json:"region"`
|
||
Platform bool `json:"platform"`
|
||
Release string `json:"release"`
|
||
StartedAt time.Time `json:"started_at"`
|
||
LastSeenAt time.Time `json:"last_seen_at"`
|
||
Live bool `json:"live"`
|
||
Queued int64 `json:"queued"`
|
||
Running []runningView `json:"running"`
|
||
OtherOrgs int `json:"running_for_others"`
|
||
LastHour checkerHourStats `json:"last_hour"`
|
||
Recent []recentByCheck `json:"recent"`
|
||
// NextCursor and PrevCursor page through Recent, newest first.
|
||
NextCursor string `json:"next_cursor,omitempty"`
|
||
PrevCursor string `json:"prev_cursor,omitempty"`
|
||
Siblings []uuid.UUID `json:"other_instances"`
|
||
regionID string
|
||
monitorName map[uuid.UUID]string
|
||
}
|
||
|
||
type runningView struct {
|
||
MonitorID uuid.UUID `json:"monitor_id"`
|
||
Monitor string `json:"monitor"`
|
||
Since time.Time `json:"since"`
|
||
}
|
||
|
||
type checkerHourStats struct {
|
||
Checks int64 `json:"checks"`
|
||
Failed int64 `json:"failed"`
|
||
AvgLatencyMS float32 `json:"avg_latency_ms"`
|
||
}
|
||
|
||
type recentByCheck struct {
|
||
Time time.Time `json:"time"`
|
||
MonitorID uuid.UUID `json:"monitor_id"`
|
||
Monitor string `json:"monitor"`
|
||
OK bool `json:"ok"`
|
||
LatencyMS *int32 `json:"latency_ms,omitempty"`
|
||
StatusCode *int32 `json:"status_code,omitempty"`
|
||
Error *string `json:"error,omitempty"`
|
||
}
|
||
|
||
var errNoChecker = errors.New("api: checker not found")
|
||
|
||
// loadCheckerActivity gathers the activity of a checker instance visible to
|
||
// p: platform instances and those of p's organization.
|
||
func (s *Server) loadCheckerActivity(ctx context.Context, p *principal, instance uuid.UUID, pg pageReq) (checkerActivity, error) {
|
||
now := time.Now()
|
||
a := checkerActivity{ID: instance, Running: []runningView{}, Recent: []recentByCheck{}, Siblings: []uuid.UUID{}, monitorName: map[uuid.UUID]string{}}
|
||
t, err := s.loadGroupTree(ctx, p.scope())
|
||
if err != nil {
|
||
return a, err
|
||
}
|
||
readable := map[uuid.UUID]bool{}
|
||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||
rows, err := q.AgentInstancesByID(ctx, []uuid.UUID{instance})
|
||
if err != nil {
|
||
return err
|
||
}
|
||
if len(rows) == 0 || rows[0].Kind != "checker" {
|
||
return errNoChecker
|
||
}
|
||
r := rows[0]
|
||
a.Agent, a.Region, a.Platform, a.Release = r.AgentName, r.RegionName, r.OrgID == nil, r.Release
|
||
a.StartedAt, a.LastSeenAt = r.StartedAt, r.LastSeenAt
|
||
if r.RegionID != nil {
|
||
a.regionID = r.RegionID.String()
|
||
}
|
||
siblings, err := q.SiblingInstances(ctx, r.AgentID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
for _, sb := range siblings {
|
||
if sb.ID != instance {
|
||
a.Siblings = append(a.Siblings, sb.ID)
|
||
}
|
||
}
|
||
monitors, err := q.ListMonitors(ctx, p.Org.ID)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
for _, m := range monitors {
|
||
if canInGroup(p, authz.MonitorsRead, t, m.GroupID) {
|
||
readable[m.ID] = true
|
||
a.monitorName[m.ID] = m.Name
|
||
}
|
||
}
|
||
stats, err := q.CheckerStats(ctx, store.CheckerStatsParams{OrgID: p.Org.ID, CheckerID: instance})
|
||
if err != nil {
|
||
return err
|
||
}
|
||
a.LastHour = checkerHourStats{Checks: stats.Total, Failed: stats.Failed, AvgLatencyMS: stats.AvgLatencyMs}
|
||
recent, err := q.ResultsByChecker(ctx, store.ResultsByCheckerParams{
|
||
OrgID: p.Org.ID, CheckerID: instance, AfterT: pg.afterT(), AfterS: pg.afterS(), BeforeT: pg.beforeT(), BeforeS: pg.beforeS(), MaxRows: pg.fetch(),
|
||
})
|
||
// Pages are cut before filtering, so cursors follow every result
|
||
// and a page may show fewer than it read.
|
||
recent, info := paginate(pg, recent, func(r store.ResultsByCheckerRow) cursor {
|
||
return cursor{T: r.Time, S: r.MonitorID.String() + "|" + r.Region}
|
||
})
|
||
a.NextCursor, a.PrevCursor = info.Next, info.Prev
|
||
for _, r := range recent {
|
||
if readable[r.MonitorID] {
|
||
a.Recent = append(a.Recent, recentByCheck{
|
||
Time: r.Time, MonitorID: r.MonitorID, Monitor: a.monitorName[r.MonitorID], OK: r.Ok,
|
||
LatencyMS: r.LatencyMs, StatusCode: r.StatusCode, Error: r.Error,
|
||
})
|
||
}
|
||
}
|
||
return err
|
||
})
|
||
if err != nil {
|
||
return a, err
|
||
}
|
||
if a.regionID != "" {
|
||
if seen, err := s.sched.LastSeen(ctx, a.regionID, instance); err == nil && !seen.IsZero() {
|
||
a.LastSeenAt = seen
|
||
a.Live = now.Sub(seen) < schedule.StaleAfter
|
||
}
|
||
}
|
||
if a.Queued, err = s.sched.QueueLen(ctx, instance); err != nil {
|
||
return a, err
|
||
}
|
||
running, err := s.runningOn(ctx, instance, now)
|
||
if err != nil {
|
||
return a, err
|
||
}
|
||
for _, r := range running {
|
||
if r.Org != p.Org.ID || !readable[r.MonitorID] {
|
||
a.OtherOrgs++
|
||
continue
|
||
}
|
||
a.Running = append(a.Running, runningView{MonitorID: r.MonitorID, Monitor: a.monitorName[r.MonitorID], Since: r.Since})
|
||
}
|
||
return a, nil
|
||
}
|
||
|
||
func (s *Server) getChecker(c *gin.Context) {
|
||
id, err := uuid.Parse(c.Param("id"))
|
||
if err != nil {
|
||
fail(c, http.StatusNotFound, "not_found")
|
||
return
|
||
}
|
||
pg, ok := parsePage(c, apiPageSize)
|
||
if !ok {
|
||
return
|
||
}
|
||
a, err := s.loadCheckerActivity(c.Request.Context(), current(c), id, pg)
|
||
if errors.Is(err, errNoChecker) {
|
||
fail(c, http.StatusNotFound, "not_found")
|
||
return
|
||
}
|
||
if err != nil {
|
||
internalError(c, err)
|
||
return
|
||
}
|
||
c.JSON(http.StatusOK, a)
|
||
}
|
||
|
||
func (s *Server) checkerPage(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) {
|
||
id, err := uuid.Parse(c.Param("id"))
|
||
if err != nil {
|
||
return notFoundPage(c)
|
||
}
|
||
pg, ok := parsePage(c, consolePageSize)
|
||
if !ok {
|
||
return nil, errAborted
|
||
}
|
||
a, err := s.loadCheckerActivity(c.Request.Context(), p, id, pg)
|
||
if errors.Is(err, errNoChecker) {
|
||
return notFoundPage(c)
|
||
}
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
const layout = "2006-01-02 15:04:05"
|
||
v := web.CheckerView{
|
||
ID: a.ID.String(), Agent: a.Agent, Region: a.Region, Platform: a.Platform, Release: a.Release,
|
||
Started: a.StartedAt.Local().Format(layout), LastSeen: a.LastSeenAt.Local().Format(layout), Live: a.Live,
|
||
Queued: int(a.Queued), OtherOrgs: a.OtherOrgs,
|
||
Checks: int(a.LastHour.Checks), Failed: int(a.LastHour.Failed), AvgLatency: fmt.Sprintf("%.0f ms", a.LastHour.AvgLatencyMS),
|
||
}
|
||
now := time.Now()
|
||
for _, r := range a.Running {
|
||
v.Running = append(v.Running, web.CheckerRun{
|
||
MonitorURL: "/monitors/" + r.MonitorID.String(), Monitor: r.Monitor, For: now.Sub(r.Since).Round(time.Second).String(),
|
||
})
|
||
}
|
||
// Live while showing the latest results; paged back, with dates.
|
||
timeLayout := "15:04:05"
|
||
if pg.at() != nil {
|
||
timeLayout = "01-02 15:04:05"
|
||
}
|
||
v.Pager = pager(c, pageInfo{Next: a.NextCursor, Prev: a.PrevCursor})
|
||
for _, r := range a.Recent {
|
||
row := web.CheckerResult{
|
||
Time: r.Time.Local().Format(timeLayout), MonitorURL: "/monitors/" + r.MonitorID.String(), Monitor: r.Monitor,
|
||
OK: r.OK, Latency: "–", Detail: deref(r.Error),
|
||
}
|
||
if r.LatencyMS != nil {
|
||
row.Latency = fmt.Sprintf("%d ms", *r.LatencyMS)
|
||
}
|
||
if row.Detail == "" && r.StatusCode != nil {
|
||
row.Detail = strconv.Itoa(int(*r.StatusCode))
|
||
}
|
||
v.Recent = append(v.Recent, row)
|
||
}
|
||
for _, sb := range a.Siblings {
|
||
v.Siblings = append(v.Siblings, web.CheckerLink{URL: "/checkers/" + sb.String(), Label: shortID(sb)})
|
||
}
|
||
if pg.at() == nil {
|
||
page.RefreshSeconds = 5
|
||
}
|
||
return web.CheckerPage(page, me, v), nil
|
||
}
|
||
|
||
func shortID(id uuid.UUID) string { return id.String()[:8] }
|
||
|
||
// checkerLinks names the checker instances in ids for result lists.
|
||
func (s *Server) checkerLinks(ctx context.Context, p *principal, ids []uuid.UUID) (map[uuid.UUID]web.CheckerLink, error) {
|
||
out := map[uuid.UUID]web.CheckerLink{}
|
||
if len(ids) == 0 {
|
||
return out, nil
|
||
}
|
||
var rows []store.AgentInstancesByIDRow
|
||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||
var err error
|
||
rows, err = q.AgentInstancesByID(ctx, ids)
|
||
return err
|
||
})
|
||
for _, r := range rows {
|
||
out[r.ID] = web.CheckerLink{URL: "/checkers/" + r.ID.String(), Label: r.AgentName + " · " + shortID(r.ID)}
|
||
}
|
||
return out, err
|
||
}
|