ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m57s
ci / test (pull_request) Successful in 13m1s
ci / build (pull_request) Successful in 19m25s
ci / image (pull_request) In progress
uptimesebi_checks_overdue counted only runs not dispatched yet. Dispatch hands due runs to an instance's queue and schedules the next run at once, so a checker too busy to take its work left the metric at 0. It now also counts queued runs due more than 10 seconds ago. The chart adds an optional PrometheusRule (api.metrics.prometheusRule): UptimeSebiRegionBehind fires when a region's checks stay overdue, and UptimeSebiPlatformMetricsFailing when the platform metrics cannot be read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
375 lines
12 KiB
Go
375 lines
12 KiB
Go
// 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"
|
|
// keyTouched records when each monitor was last upserted, so a
|
|
// reconciliation based on an older database read leaves it alone.
|
|
keyTouched = "sched:touched"
|
|
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))
|
|
p.HSet(ctx, keyTouched, id, now)
|
|
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())
|
|
p.HDel(ctx, keyTouched, 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 as read
|
|
// from the database at asOf. It repairs drift after a Redis failover or a
|
|
// missed update and is safe to run from several replicas. Monitors upserted
|
|
// after asOf are kept even if want lacks them: they were created while the
|
|
// database was being read.
|
|
func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Time) 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
|
|
}
|
|
asOfMS := asOf.UnixMilli()
|
|
ids, err := s.rdb.HKeys(ctx, keyIntervals).Result()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, id := range ids {
|
|
if wanted[id] {
|
|
continue
|
|
}
|
|
if err := pruneScript.Run(ctx, s.rdb, []string{keyIntervals, keyTouched}, id, asOfMS).Err(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
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] {
|
|
continue
|
|
}
|
|
if err := pruneScript.Run(ctx, s.rdb, []string{keyDue(r), keyTouched}, id, asOfMS).Err(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// pruneScript removes a monitor from a hash or sorted set unless it was
|
|
// upserted at or after asOf. Checking and removing in one step closes the
|
|
// window in which a concurrent upsert would be undone.
|
|
//
|
|
// KEYS: hash or sorted set to prune, touched hash. ARGV: monitor id, asOf ms.
|
|
var pruneScript = redis.NewScript(`
|
|
local touched = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '0')
|
|
if touched >= tonumber(ARGV[2]) then return 0 end
|
|
if redis.call('TYPE', KEYS[1]).ok == 'zset' then
|
|
redis.call('ZREM', KEYS[1], ARGV[1])
|
|
else
|
|
redis.call('HDEL', KEYS[1], ARGV[1])
|
|
redis.call('HDEL', KEYS[2], ARGV[1])
|
|
end
|
|
return 1
|
|
`)
|
|
|
|
// 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
|
|
}
|
|
|
|
// QueueLen returns how many runs wait for instance.
|
|
func (s *Scheduler) QueueLen(ctx context.Context, instance uuid.UUID) (int64, error) {
|
|
return s.rdb.LLen(ctx, jobsPrefix+instance.String()).Result()
|
|
}
|
|
|
|
// LastSeen returns when instance last polled in region, or zero if it is
|
|
// not registered.
|
|
func (s *Scheduler) LastSeen(ctx context.Context, region string, instance uuid.UUID) (time.Time, error) {
|
|
score, err := s.rdb.ZScore(ctx, keyInstances(region), instance.String()).Result()
|
|
if errors.Is(err, redis.Nil) || score == 0 {
|
|
return time.Time{}, nil
|
|
}
|
|
return time.UnixMilli(int64(score)), err
|
|
}
|
|
|
|
// 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.blpop(ctx, min(left, time.Second), q)
|
|
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
|
|
}
|
|
|
|
// blpop is BLPOP with a timeout below a second, which go-redis would round
|
|
// up to one (Redis takes fractions of seconds since 6.0).
|
|
func (s *Scheduler) blpop(ctx context.Context, timeout time.Duration, key string) ([]string, error) {
|
|
if timeout >= time.Second {
|
|
return s.rdb.BLPop(ctx, timeout, key).Result()
|
|
}
|
|
return s.rdb.Do(ctx, "BLPOP", key, strconv.FormatFloat(timeout.Seconds(), 'f', 3, 64)).StringSlice()
|
|
}
|
|
|
|
// 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()
|
|
}
|
|
|
|
// overdueScript counts the runs of a region due before a cutoff: those not
|
|
// dispatched yet and those waiting in an instance's queue.
|
|
//
|
|
// KEYS: due set, instance set.
|
|
// ARGV: cutoff ms, job queue prefix.
|
|
var overdueScript = redis.NewScript(`
|
|
local cutoff = tonumber(ARGV[1])
|
|
local n = redis.call('ZCOUNT', KEYS[1], '-inf', cutoff)
|
|
for _, inst in ipairs(redis.call('ZRANGE', KEYS[2], 0, -1)) do
|
|
for _, job in ipairs(redis.call('LRANGE', ARGV[2] .. inst, 0, -1)) do
|
|
local at = tonumber(string.sub(job, string.find(job, '|', 1, true) + 1))
|
|
if at ~= nil and at <= cutoff then n = n + 1 end
|
|
end
|
|
end
|
|
return n
|
|
`)
|
|
|
|
// Overdue returns how many runs of region were due more than late ago and
|
|
// have not started: runs not dispatched, as when the region has no live
|
|
// instance, and runs left in the queue of an instance too busy to take them.
|
|
func (s *Scheduler) Overdue(ctx context.Context, region string, late time.Duration) (int64, error) {
|
|
return overdueScript.Run(ctx, s.rdb, []string{keyDue(region), keyInstances(region)},
|
|
s.now().Add(-late).UnixMilli(), jobsPrefix).Int64()
|
|
}
|
|
|
|
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
|
|
}
|