Files
uptimesebi/internal/checker/checker.go
T
Sebastian UnterschützandClaude Opus 5.5 a6bc50b39d fix(checker): log when the API works again after failures
A checker logged only failures, so after an outage of the API, as during a
rollout, its log ended on an error and read as stuck although it had
recovered. Polling and reporting now log once when they work again, with
how long they failed and how many results the backlog delivered. A long
poll answered empty at once is not repeated at once either.

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

271 lines
7.6 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
// 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
// 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.slots; running.Done() }()
r.results <- r.execute(ctx, j)
}()
}
// A long poll answered empty at once, as by an instance shutting
// down, is not repeated at once either.
if free == 0 || (len(jobs) == 0 && wait > 0 && time.Since(asked) < quickPoll) {
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
// 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):
}
}