Files
uptimesebi/internal/checker/checker.go
T
Sebastian UnterschützandClaude Opus 5.5 e776143ee0 fix(checker): take work as soon as a slot frees
With every slot busy, the poll loop paused a fixed second before asking
for work again, so a checker took at most one batch of its slots per
second, whatever its machine could do. Under load, runs piled up in the
checker's queue and started late.

The loop now waits for the first freed slot, at most fullHeartbeat (5s),
so a checker whose slots stay busy still polls as a heartbeat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 14:15:48 +01:00

307 lines
8.5 KiB
Go

// Package checker is the checker agent: it fetches jobs from the API, runs
// them and reports the results. It keeps no state beyond results that are
// waiting to be sent.
package checker
import (
"context"
"encoding/json"
"errors"
"log/slog"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
)
// API is the part of agentapi.Client the runner uses.
type API interface {
Jobs(ctx context.Context, max int, wait time.Duration) ([]agentapi.Job, error)
Report(ctx context.Context, results []agentapi.Result) error
Release(ctx context.Context) error
}
const (
pollWait = 20 * time.Second
// quickPoll is a long poll answered empty faster than any wait would.
quickPoll = 200 * time.Millisecond
flushInterval = 2 * time.Second
// fullHeartbeat is how often a checker with every slot busy still polls,
// so the API keeps it live; well below schedule.StaleAfter.
fullHeartbeat = 5 * time.Second
// maxPending bounds results kept while the API is unreachable.
maxPending = 50_000
)
// Runner executes jobs with bounded concurrency.
type Runner struct {
api API
log *slog.Logger
slots chan struct{}
// freed is signalled when a slot is freed, for a poll waiting for one.
freed chan struct{}
run func(context.Context, check.Spec) check.Outcome
results chan agentapi.Result
lastPoll atomic.Int64
evidenceMu sync.Mutex
evidence map[uuid.UUID]evidenceState
}
// evidenceState remembers what was last sent for a monitor.
type evidenceState struct {
ok bool
sent time.Time
}
// evidenceEvery is how often evidence of healthy checks is sent, so the
// console can show what a working response looks like.
const evidenceEvery = 10 * time.Minute
// shouldSendEvidence decides whether a result carries its evidence: every
// failure, every change between success and failure, and otherwise every
// evidenceEvery. Most results thus stay small.
func (r *Runner) shouldSendEvidence(monitor uuid.UUID, ok bool, now time.Time) bool {
r.evidenceMu.Lock()
defer r.evidenceMu.Unlock()
last, seen := r.evidence[monitor]
send := !ok || !seen || last.ok != ok || now.Sub(last.sent) >= evidenceEvery
if send {
last.sent = now
}
last.ok = ok
r.evidence[monitor] = last
return send
}
// New returns a Runner that runs at most concurrency checks at once.
func New(api API, concurrency int, log *slog.Logger) *Runner {
return &Runner{
api: api,
log: log,
slots: make(chan struct{}, max(concurrency, 1)),
freed: make(chan struct{}, 1),
run: check.Run,
results: make(chan agentapi.Result, 1024),
evidence: map[uuid.UUID]evidenceState{},
}
}
// Healthy reports an error unless the API answered a poll recently.
func (r *Runner) Healthy(context.Context) error {
if time.Since(time.UnixMilli(r.lastPoll.Load())) > 2*pollWait+10*time.Second {
return errors.New("no successful poll recently")
}
return nil
}
// Run polls and executes jobs until ctx is cancelled, then hands queued jobs
// back, lets running checks finish within drain and sends the last results.
// It returns early only if the API rejects the agent token.
func (r *Runner) Run(ctx context.Context, drain time.Duration) error {
var running sync.WaitGroup
reportDone := make(chan struct{})
reportCtx, stopReport := context.WithCancel(context.WithoutCancel(ctx))
go func() {
defer close(reportDone)
r.report(reportCtx)
}()
err := r.poll(ctx, &running)
releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
if rerr := r.api.Release(releaseCtx); rerr != nil {
r.log.Warn("release failed; queued jobs move to other instances once this one is considered gone", "error", rerr)
}
cancel()
waited := make(chan struct{})
go func() { running.Wait(); close(waited) }()
select {
case <-waited:
case <-time.After(drain):
r.log.Warn("checks still running at shutdown", "drain", drain)
}
stopReport()
<-reportDone
return err
}
func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error {
backoff := time.Second
// failing and failures track an outage, so its end is logged too: a log
// whose last line is an error otherwise reads as a checker stuck.
var (
failing time.Time
failures int
)
for ctx.Err() == nil {
free := cap(r.slots) - len(r.slots)
wait := pollWait
if free == 0 {
// Still poll as a heartbeat, but do not take work.
wait = 0
}
asked := time.Now()
jobs, err := r.api.Jobs(ctx, free, wait)
switch {
case errors.Is(err, agentapi.ErrUnauthorized):
return err
case err != nil:
if ctx.Err() != nil {
return nil
}
r.log.Warn("polling for jobs failed", "error", err, "retry_in", backoff)
if failing.IsZero() {
failing = time.Now()
}
failures++
sleep(ctx, backoff)
backoff = min(backoff*2, 30*time.Second)
continue
}
backoff = time.Second
if !failing.IsZero() {
r.log.Info("polling for jobs works again", "failed_for", time.Since(failing).Round(time.Second).String(), "failures", failures)
failing, failures = time.Time{}, 0
}
r.lastPoll.Store(time.Now().UnixMilli())
for _, j := range jobs {
r.slots <- struct{}{}
running.Add(1)
go func() {
defer func() { r.release(); running.Done() }()
r.results <- r.execute(ctx, j)
}()
}
switch {
case free == 0:
// Take work again as soon as a check finishes, not after a
// fixed pause, which would cap throughput at slots per pause.
r.waitForSlot(ctx, fullHeartbeat)
case len(jobs) == 0 && wait > 0 && time.Since(asked) < quickPoll:
// A long poll answered empty at once, as by an instance
// shutting down, is not repeated at once either.
sleep(ctx, time.Second)
}
}
return nil
}
// release frees a slot and wakes a poll waiting for one.
func (r *Runner) release() {
<-r.slots
select {
case r.freed <- struct{}{}:
default:
}
}
// waitForSlot returns once a slot is free, ctx is done or at most after
// d.
func (r *Runner) waitForSlot(ctx context.Context, d time.Duration) {
t := time.NewTimer(d)
defer t.Stop()
for len(r.slots) == cap(r.slots) {
select {
case <-r.freed:
case <-ctx.Done():
return
case <-t.C:
return
}
}
}
func (r *Runner) execute(ctx context.Context, j agentapi.Job) agentapi.Result {
// Checks already started finish even during shutdown; their timeout
// bounds them.
ctx = context.WithoutCancel(ctx)
start := time.Now()
o := r.run(ctx, check.Spec{
Type: check.Type(j.Type), Target: j.Target, Timeout: time.Duration(j.TimeoutMS) * time.Millisecond,
Config: j.Config, AllowPrivate: j.AllowPrivate, Capture: true,
})
res := agentapi.Result{
MonitorID: j.MonitorID, ScheduledAt: j.ScheduledAt, StartedAt: start, OK: o.OK,
LatencyMS: int(o.Latency.Milliseconds()), StatusCode: o.StatusCode, Error: o.Error,
}
if o.Evidence != nil && r.shouldSendEvidence(j.MonitorID, o.OK, start) {
res.Evidence, _ = json.Marshal(o.Evidence)
}
return res
}
// report batches results and sends them. Unsent results are retried with
// the next batch; when ctx ends it makes one last attempt.
func (r *Runner) report(ctx context.Context) {
tick := time.NewTicker(flushInterval)
defer tick.Stop()
var (
pending []agentapi.Result
// failing is when reporting started to fail, zero while it works.
failing time.Time
)
flush := func(ctx context.Context) {
sent := 0
for len(pending) > 0 {
n := min(len(pending), agentapi.MaxResults)
if err := r.api.Report(ctx, pending[:n]); err != nil {
r.log.Warn("reporting results failed", "error", err, "pending", len(pending))
if failing.IsZero() {
failing = time.Now()
}
return
}
pending, sent = pending[n:], sent+n
}
if !failing.IsZero() {
r.log.Info("reporting results works again", "failed_for", time.Since(failing).Round(time.Second).String(), "sent", sent)
failing = time.Time{}
}
}
for {
select {
case res := <-r.results:
pending = append(pending, res)
if len(pending) > maxPending {
dropped := len(pending) - maxPending
pending = pending[dropped:]
r.log.Warn("dropping old results while the API is unreachable", "dropped", dropped)
}
if len(pending) >= agentapi.MaxResults {
flush(ctx)
}
case <-tick.C:
flush(ctx)
case <-ctx.Done():
for {
select {
case res := <-r.results:
pending = append(pending, res)
continue
default:
}
break
}
last, cancel := context.WithTimeout(context.Background(), 5*time.Second)
flush(last)
cancel()
return
}
}
}
func sleep(ctx context.Context, d time.Duration) {
select {
case <-ctx.Done():
case <-time.After(d):
}
}