feat: monitors, checks and random distribution to checker instances (M4) #50

Merged
Sebi merged 6 commits from feat/m4-checker into main 2026-11-22 00:45:07 +00:00
3 changed files with 676 additions and 0 deletions
Showing only changes of commit 56862dce84 - Show all commits

No files matched your search

+177
View File
@@ -0,0 +1,177 @@
// Package agentapi defines the protocol between the API and its agents,
// i.e. checkers and status page servers, and a client for it.
//
// Agents never touch Postgres or Redis. They authenticate with an agent
// token and exchange JSON with the API under /agent/v1, which keeps cloud,
// hybrid and self-hosted deployments on one code path.
package agentapi
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/google/uuid"
)
// Version is the protocol version. The API accepts the current and the
// previous version so agents can be upgraded after the API.
const Version = 1
// Header names sent by agents.
const (
VersionHeader = "X-Agent-Protocol"
InstanceHeader = "X-Agent-Instance"
ReleaseHeader = "X-Agent-Release"
)
// Hello describes the agent the token belongs to.
type Hello struct {
AgentID uuid.UUID `json:"agent_id"`
Name string `json:"name"`
Kind string `json:"kind"`
Region string `json:"region,omitempty"`
Protocol int `json:"protocol"`
}
// JobsRequest asks for up to Max jobs, waiting up to WaitMS if none are
// ready. Polling doubles as the instance's heartbeat; Max may be 0.
type JobsRequest struct {
Max int `json:"max"`
WaitMS int `json:"wait_ms"`
}
// Job is one check to run.
type Job struct {
MonitorID uuid.UUID `json:"monitor_id"`
ScheduledAt time.Time `json:"scheduled_at"`
Type string `json:"type"`
Target string `json:"target"`
TimeoutMS int `json:"timeout_ms"`
Config json.RawMessage `json:"config"`
// AllowPrivate permits targets on private networks.
AllowPrivate bool `json:"allow_private"`
}
// JobsResponse carries jobs for the polling instance.
type JobsResponse struct {
Jobs []Job `json:"jobs"`
}
// Result reports one finished check.
type Result struct {
MonitorID uuid.UUID `json:"monitor_id"`
ScheduledAt time.Time `json:"scheduled_at"`
StartedAt time.Time `json:"started_at"`
OK bool `json:"ok"`
LatencyMS int `json:"latency_ms"`
StatusCode int `json:"status_code,omitempty"`
Error string `json:"error,omitempty"`
}
// ResultsRequest reports finished checks in a batch.
type ResultsRequest struct {
Results []Result `json:"results"`
}
// MaxResults bounds a results batch.
const MaxResults = 500
// ErrUnauthorized means the agent token was rejected.
var ErrUnauthorized = errors.New("agentapi: token rejected")
// Client talks to the agent API on behalf of one agent instance.
type Client struct {
base string
token string
instance uuid.UUID
release string
hc *http.Client
}
// NewClient returns a client for the API at base. instance identifies this
// process among several running with the same token.
func NewClient(base, token string, instance uuid.UUID, release string) *Client {
return &Client{
base: strings.TrimSuffix(base, "/"),
token: token,
instance: instance,
release: release,
hc: &http.Client{Timeout: 60 * time.Second},
}
}
// WithHTTPClient replaces the HTTP client, e.g. to trust a private CA.
func (c *Client) WithHTTPClient(hc *http.Client) *Client {
c.hc = hc
return c
}
// Instance returns the instance ID sent with every request.
func (c *Client) Instance() uuid.UUID { return c.instance }
func (c *Client) do(ctx context.Context, method, path string, in, out any) error {
var body io.Reader
if in != nil {
b, err := json.Marshal(in)
if err != nil {
return err
}
body = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, c.base+"/agent/v1"+path, body)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set(VersionHeader, fmt.Sprint(Version))
req.Header.Set(InstanceHeader, c.instance.String())
req.Header.Set(ReleaseHeader, c.release)
resp, err := c.hc.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
switch {
case resp.StatusCode == http.StatusUnauthorized:
return ErrUnauthorized
case resp.StatusCode >= 300:
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
return fmt.Errorf("agentapi: %s %s: %d %s", method, path, resp.StatusCode, bytes.TrimSpace(msg))
case out == nil:
return nil
}
return json.NewDecoder(resp.Body).Decode(out)
}
// Hello identifies the agent and checks connectivity.
func (c *Client) Hello(ctx context.Context) (Hello, error) {
var h Hello
err := c.do(ctx, http.MethodGet, "/hello", nil, &h)
return h, err
}
// Jobs long-polls for jobs.
func (c *Client) Jobs(ctx context.Context, max int, wait time.Duration) ([]Job, error) {
var resp JobsResponse
err := c.do(ctx, http.MethodPost, "/jobs", JobsRequest{Max: max, WaitMS: int(wait.Milliseconds())}, &resp)
return resp.Jobs, err
}
// Report sends finished checks.
func (c *Client) Report(ctx context.Context, results []Result) error {
return c.do(ctx, http.MethodPost, "/results", ResultsRequest{Results: results}, nil)
}
// Release hands this instance's queued jobs back for other instances and
// deregisters it. Call it during graceful shutdown.
func (c *Client) Release(ctx context.Context) error {
return c.do(ctx, http.MethodPost, "/release", nil, nil)
}
+294
View File
@@ -0,0 +1,294 @@
// Package schedule distributes due checks to checker instances.
//
// It runs inside the API, which is the only component with Redis access.
// Per region, a sorted set holds each monitor's next due time. Dispatch
// moves due monitors into the queue of a randomly chosen live instance of
// that region and schedules their next run in the same atomic step, so any
// number of API replicas can dispatch concurrently without a leader, and a
// lost job never stops a monitor from running again.
//
// Instances announce themselves by polling. One that stops polling is
// considered gone after StaleAfter; its queued jobs return to the region.
package schedule
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
// StaleAfter is how long an instance may stay silent before its queued jobs
// are given to others. Instances poll at least every PollInterval.
const (
PollInterval = 20 * time.Second
StaleAfter = 45 * time.Second
)
const (
keyRegions = "sched:regions"
keyIntervals = "sched:intervals"
jobsPrefix = "sched:jobs:"
// jobsTTL drops queues of instances that vanished together with every
// API replica that could have recovered them.
jobsTTL = 10 * time.Minute
)
func keyDue(region string) string { return "sched:due:" + region }
func keyInstances(region string) string { return "sched:instances:" + region }
// Scheduler is safe for concurrent use.
type Scheduler struct {
rdb redis.UniversalClient
now func() time.Time
}
// New returns a Scheduler on rdb.
func New(rdb redis.UniversalClient) *Scheduler {
return &Scheduler{rdb: rdb, now: time.Now}
}
// Entry is one dispatched run.
type Entry struct {
MonitorID uuid.UUID
ScheduledAt time.Time
}
// Monitor is the schedule-relevant part of a monitor.
type Monitor struct {
ID uuid.UUID
Interval time.Duration
Regions []string
}
// Upsert schedules m in its regions and removes it from others it was in.
// A monitor new to a region runs right away; an existing schedule keeps its
// phase so edits do not cause bursts.
func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []string) error {
now := s.now().UnixMilli()
id := m.ID.String()
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HSet(ctx, keyIntervals, id, int64(m.Interval/time.Millisecond))
keep := map[string]bool{}
for _, r := range m.Regions {
keep[r] = true
p.SAdd(ctx, keyRegions, r)
p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(now), Member: id})
}
for _, r := range previousRegions {
if !keep[r] {
p.ZRem(ctx, keyDue(r), id)
}
}
return nil
})
return err
}
// Remove unschedules a monitor from regions. Runs already queued for an
// instance are dropped at dispatch or job resolution.
func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string) error {
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HDel(ctx, keyIntervals, id.String())
for _, r := range regions {
p.ZRem(ctx, keyDue(r), id.String())
}
return nil
})
return err
}
// Reconcile makes Redis match want, the full set of enabled monitors. It
// repairs drift after a Redis failover or a missed update and is safe to run
// from several replicas.
func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor) error {
byRegion := map[string]map[string]bool{}
for _, m := range want {
if err := s.Upsert(ctx, m, nil); err != nil {
return err
}
for _, r := range m.Regions {
if byRegion[r] == nil {
byRegion[r] = map[string]bool{}
}
byRegion[r][m.ID.String()] = true
}
}
wanted := map[string]bool{}
for _, m := range want {
wanted[m.ID.String()] = true
}
ids, err := s.rdb.HKeys(ctx, keyIntervals).Result()
if err != nil {
return err
}
for _, id := range ids {
if !wanted[id] {
s.rdb.HDel(ctx, keyIntervals, id)
}
}
regions, err := s.rdb.SMembers(ctx, keyRegions).Result()
if err != nil {
return err
}
for _, r := range regions {
members, err := s.rdb.ZRange(ctx, keyDue(r), 0, -1).Result()
if err != nil {
return err
}
for _, id := range members {
if !byRegion[r][id] {
s.rdb.ZRem(ctx, keyDue(r), id)
}
}
}
return nil
}
// Heartbeat records that instance of region is alive.
func (s *Scheduler) Heartbeat(ctx context.Context, region string, instance uuid.UUID) error {
return s.rdb.ZAdd(ctx, keyInstances(region), redis.Z{Score: float64(s.now().UnixMilli()), Member: instance.String()}).Err()
}
// dispatchScript runs per region.
//
// KEYS: due set, instance set, interval hash.
// ARGV: now ms, stale-before ms, batch limit, job queue prefix, queue TTL s.
var dispatchScript = redis.NewScript(`
local now = tonumber(ARGV[1])
for _, inst in ipairs(redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', ARGV[2])) do
local q = ARGV[4] .. inst
for _, job in ipairs(redis.call('LRANGE', q, 0, -1)) do
local m = string.sub(job, 1, string.find(job, '|', 1, true) - 1)
if redis.call('HEXISTS', KEYS[3], m) == 1 then
redis.call('ZADD', KEYS[1], 'LT', now, m)
end
end
redis.call('DEL', q)
redis.call('ZREM', KEYS[2], inst)
end
local live = redis.call('ZRANGE', KEYS[2], 0, -1)
if #live == 0 then return 0 end
local due = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', now, 'WITHSCORES', 'LIMIT', 0, ARGV[3])
local n = 0
for i = 1, #due, 2 do
local m, at = due[i], tonumber(due[i + 1])
local interval = tonumber(redis.call('HGET', KEYS[3], m))
if interval == nil then
redis.call('ZREM', KEYS[1], m)
else
local q = ARGV[4] .. live[math.random(#live)]
redis.call('RPUSH', q, m .. '|' .. string.format('%.0f', at))
redis.call('EXPIRE', q, ARGV[5])
local nxt = at + interval
if nxt <= now then nxt = now + interval end
redis.call('ZADD', KEYS[1], nxt, m)
n = n + 1
end
end
return n
`)
// Dispatch hands due runs of every region to random live instances and
// returns how many it dispatched.
func (s *Scheduler) Dispatch(ctx context.Context) (int, error) {
regions, err := s.rdb.SMembers(ctx, keyRegions).Result()
if err != nil {
return 0, err
}
now := s.now()
total := 0
for _, r := range regions {
n, err := dispatchScript.Run(ctx, s.rdb,
[]string{keyDue(r), keyInstances(r), keyIntervals},
now.UnixMilli(), now.Add(-StaleAfter).UnixMilli(), 1000, jobsPrefix, int(jobsTTL.Seconds()),
).Int()
if err != nil {
return total, fmt.Errorf("schedule: dispatch %s: %w", r, err)
}
total += n
}
return total, nil
}
// Take pops up to max queued runs for instance, waiting up to wait for the
// first one. It returns within about a second once ctx is done, so long polls
// do not hold up shutdown or cancelled requests.
func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, error) {
if max <= 0 {
return nil, nil
}
q := jobsPrefix + instance.String()
raw, err := s.rdb.LPopCount(ctx, q, max).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return nil, err
}
deadline := time.Now().Add(wait)
for len(raw) == 0 && ctx.Err() == nil {
left := time.Until(deadline)
if left <= 0 {
return nil, nil
}
// BLPOP blocks server side and ignores ctx, so wait in slices.
first, err := s.rdb.BLPop(ctx, min(left, time.Second), q).Result()
if errors.Is(err, redis.Nil) {
continue
}
if err != nil {
return nil, err
}
raw = []string{first[1]}
if max > 1 {
more, err := s.rdb.LPopCount(ctx, q, max-1).Result()
if err != nil && !errors.Is(err, redis.Nil) {
return nil, err
}
raw = append(raw, more...)
}
}
out := make([]Entry, 0, len(raw))
for _, r := range raw {
if e, ok := parseEntry(r); ok {
out = append(out, e)
}
}
return out, nil
}
// Release returns instance's queued runs to its region and forgets it.
func (s *Scheduler) Release(ctx context.Context, region string, instance uuid.UUID) error {
// Marking the instance stale lets the dispatch script do the handover,
// which keeps that logic in one place.
if err := s.rdb.ZAdd(ctx, keyInstances(region), redis.Z{Score: 0, Member: instance.String()}).Err(); err != nil {
return err
}
_, err := s.Dispatch(ctx)
return err
}
// Instances returns the live instance count per region.
func (s *Scheduler) Instances(ctx context.Context, region string) (int64, error) {
min := strconv.FormatInt(s.now().Add(-StaleAfter).UnixMilli(), 10)
return s.rdb.ZCount(ctx, keyInstances(region), min, "+inf").Result()
}
func parseEntry(s string) (Entry, bool) {
id, at, ok := strings.Cut(s, "|")
if !ok {
return Entry{}, false
}
mid, err := uuid.Parse(id)
if err != nil {
return Entry{}, false
}
ms, err := strconv.ParseFloat(at, 64)
if err != nil {
return Entry{}, false
}
return Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}, true
}
+205
View File
@@ -0,0 +1,205 @@
package schedule
import (
"context"
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
)
func newTest(t *testing.T) (*Scheduler, *time.Time) {
t.Helper()
url := os.Getenv("UPTIME_TEST_REDIS_URL")
if url == "" {
t.Skip("UPTIME_TEST_REDIS_URL not set")
}
opts, err := redis.ParseURL(url)
if err != nil {
t.Fatal(err)
}
rdb := redis.NewClient(opts)
t.Cleanup(func() { _ = rdb.Close() })
if err := rdb.FlushDB(context.Background()).Err(); err != nil {
t.Fatal(err)
}
now := time.UnixMilli(1_800_000_000_000)
s := New(rdb)
s.now = func() time.Time { return now }
return s, &now
}
func takeAll(t *testing.T, s *Scheduler, inst uuid.UUID) []Entry {
t.Helper()
e, err := s.Take(context.Background(), inst, 1000, 0)
if err != nil {
t.Fatalf("Take() failed: %v", err)
}
return e
}
func mustDispatch(t *testing.T, s *Scheduler) int {
t.Helper()
n, err := s.Dispatch(context.Background())
if err != nil {
t.Fatalf("Dispatch() failed: %v", err)
}
return n
}
// TestDispatchSpreadsRandomly runs many monitors against three instances of
// one region and expects every instance to get a substantial share.
func TestDispatchSpreadsRandomly(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
insts := []uuid.UUID{uuid.New(), uuid.New(), uuid.New()}
for _, in := range insts {
if err := s.Heartbeat(ctx, "eu", in); err != nil {
t.Fatal(err)
}
}
const monitors = 600
for range monitors {
if err := s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil); err != nil {
t.Fatal(err)
}
}
if n := mustDispatch(t, s); n != monitors {
t.Fatalf("Dispatch() = %d, want %d", n, monitors)
}
total := 0
for _, in := range insts {
got := len(takeAll(t, s, in))
total += got
if got < monitors/3-80 || got > monitors/3+80 {
t.Errorf("instance received %d of %d jobs, want about %d", got, monitors, monitors/3)
}
}
if total != monitors {
t.Errorf("instances received %d jobs, want %d", total, monitors)
}
}
func TestDispatchReschedulesAndKeepsRegionsApart(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
eu, us := uuid.New(), uuid.New()
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
m := Monitor{ID: uuid.New(), Interval: 30 * time.Second, Regions: []string{"eu", "us"}}
_ = s.Upsert(ctx, m, nil)
mustDispatch(t, s)
for _, in := range []uuid.UUID{eu, us} {
if got := takeAll(t, s, in); len(got) != 1 || got[0].MonitorID != m.ID || !got[0].ScheduledAt.Equal(*now) {
t.Errorf("instance jobs = %+v, want one run of %v at %v", got, m.ID, *now)
}
}
if n := mustDispatch(t, s); n != 0 {
t.Errorf("Dispatch() before next interval = %d, want 0", n)
}
*now = now.Add(30 * time.Second)
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
if n := mustDispatch(t, s); n != 2 {
t.Errorf("Dispatch() after interval = %d, want 2", n)
}
// Leaving a region stops runs there.
_ = s.Upsert(ctx, Monitor{ID: m.ID, Interval: m.Interval, Regions: []string{"eu"}}, m.Regions)
takeAll(t, s, eu)
takeAll(t, s, us)
*now = now.Add(30 * time.Second)
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
mustDispatch(t, s)
if got := takeAll(t, s, us); len(got) != 0 {
t.Errorf("us instance got %d jobs after region removal, want 0", len(got))
}
}
func TestStaleInstanceJobsMoveToLiveOne(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
dead, alive := uuid.New(), uuid.New()
_ = s.Heartbeat(ctx, "eu", dead)
m := Monitor{ID: uuid.New(), Interval: time.Hour, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
mustDispatch(t, s)
*now = now.Add(StaleAfter + time.Second)
_ = s.Heartbeat(ctx, "eu", alive)
mustDispatch(t, s)
got := takeAll(t, s, alive)
if len(got) != 1 || got[0].MonitorID != m.ID {
t.Errorf("live instance jobs = %+v, want the stale instance's run", got)
}
if n, _ := s.Instances(ctx, "eu"); n != 1 {
t.Errorf("Instances() = %d, want 1", n)
}
}
func TestReleaseHandsJobsOver(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
leaving, staying := uuid.New(), uuid.New()
_ = s.Heartbeat(ctx, "eu", leaving)
m := Monitor{ID: uuid.New(), Interval: time.Hour, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
mustDispatch(t, s)
_ = s.Heartbeat(ctx, "eu", staying)
if err := s.Release(ctx, "eu", leaving); err != nil {
t.Fatal(err)
}
if got := takeAll(t, s, staying); len(got) != 1 {
t.Errorf("staying instance got %d jobs, want 1", len(got))
}
}
func TestRemoveAndReconcile(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
keep := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
gone := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, keep, nil)
_ = s.Upsert(ctx, gone, nil)
if err := s.Reconcile(ctx, []Monitor{keep}); err != nil {
t.Fatal(err)
}
mustDispatch(t, s)
got := takeAll(t, s, in)
if len(got) != 1 || got[0].MonitorID != keep.ID {
t.Errorf("jobs after Reconcile = %+v, want only %v", got, keep.ID)
}
}
func TestTakeWaits(t *testing.T) {
s, _ := newTest(t)
ctx := context.Background()
in := uuid.New()
start := time.Now()
got, err := s.Take(ctx, in, 10, 300*time.Millisecond)
if err != nil || len(got) != 0 {
t.Fatalf("Take() on empty queue = %v, %v", got, err)
}
if waited := time.Since(start); waited < 250*time.Millisecond {
t.Errorf("Take() returned after %v, want it to wait about 300ms", waited)
}
}
func TestTakeReturnsWhenCancelled(t *testing.T) {
s, _ := newTest(t)
ctx, cancel := context.WithCancel(context.Background())
go func() { time.Sleep(100 * time.Millisecond); cancel() }()
start := time.Now()
_, _ = s.Take(ctx, uuid.New(), 10, 20*time.Second)
if took := time.Since(start); took > 2*time.Second {
t.Errorf("Take() returned %v after cancellation, want within about a second", took)
}
}