Files
uptimesebi/internal/checker/checker.go
T

240 lines
6.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
flushInterval = 2 * 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{}
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)),
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
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
}
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)
sleep(ctx, backoff)
backoff = min(backoff*2, 30*time.Second)
continue
}
backoff = time.Second
r.lastPoll.Store(time.Now().UnixMilli())
for _, j := range jobs {
r.slots <- struct{}{}
running.Add(1)
go func() {
defer func() { <-r.slots; running.Done() }()
r.results <- r.execute(ctx, j)
}()
}
if free == 0 {
sleep(ctx, time.Second)
}
}
return nil
}
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
flush := func(ctx context.Context) {
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))
return
}
pending = pending[n:]
}
}
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):
}
}