From a6bc50b39d72decd4b3bf21c793ea641af9eb3fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Thu, 26 Nov 2026 00:00:11 +0100 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/checker/checker.go | 39 +++++++++-- internal/checker/recovery_test.go | 106 ++++++++++++++++++++++++++++++ 2 files changed, 141 insertions(+), 4 deletions(-) create mode 100644 internal/checker/recovery_test.go diff --git a/internal/checker/checker.go b/internal/checker/checker.go index 8005f02..0380a7b 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -26,7 +26,9 @@ type API interface { } const ( - pollWait = 20 * time.Second + 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 @@ -127,6 +129,12 @@ func (r *Runner) Run(ctx context.Context, drain time.Duration) error { 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 @@ -134,6 +142,7 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error { // 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): @@ -143,11 +152,19 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error { 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{}{} @@ -157,7 +174,9 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error { r.results <- r.execute(ctx, j) }() } - if free == 0 { + // 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) } } @@ -188,15 +207,27 @@ func (r *Runner) execute(ctx context.Context, j agentapi.Job) agentapi.Result { func (r *Runner) report(ctx context.Context) { tick := time.NewTicker(flushInterval) defer tick.Stop() - var pending []agentapi.Result + 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 = pending[n:] + 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 { diff --git a/internal/checker/recovery_test.go b/internal/checker/recovery_test.go new file mode 100644 index 0000000..fa56b8d --- /dev/null +++ b/internal/checker/recovery_test.go @@ -0,0 +1,106 @@ +package checker + +import ( + "bytes" + "context" + "errors" + "log/slog" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/check" +) + +// flakyAPI fails its first calls, like an API being rolled out. +type flakyAPI struct { + mu sync.Mutex + jobFails int + reportFails int + gave bool + reported int +} + +func (f *flakyAPI) Jobs(ctx context.Context, _ int, wait time.Duration) ([]agentapi.Job, error) { + f.mu.Lock() + if f.jobFails > 0 { + f.jobFails-- + f.mu.Unlock() + return nil, errors.New("504 Gateway Timeout") + } + if !f.gave { + f.gave = true + f.mu.Unlock() + return []agentapi.Job{{MonitorID: uuid.New(), Type: "tcp", Target: "x:1"}}, nil + } + f.mu.Unlock() + select { + case <-time.After(min(wait, 50*time.Millisecond)): + case <-ctx.Done(): + } + return nil, nil +} + +func (f *flakyAPI) Report(_ context.Context, rs []agentapi.Result) error { + f.mu.Lock() + defer f.mu.Unlock() + if f.reportFails > 0 { + f.reportFails-- + return errors.New("context deadline exceeded") + } + f.reported += len(rs) + return nil +} + +func (f *flakyAPI) Release(context.Context) error { return nil } + +type syncBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuffer) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.Write(p) +} + +func (s *syncBuffer) String() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.b.String() +} + +func TestRecoveryIsLogged(t *testing.T) { + api := &flakyAPI{jobFails: 1, reportFails: 1} + var logs syncBuffer + r := New(api, 2, slog.New(slog.NewJSONHandler(&logs, nil))) + r.run = func(context.Context, check.Spec) check.Outcome { return check.Outcome{OK: true} } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- r.Run(ctx, time.Second) }() + + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + out := logs.String() + if strings.Contains(out, "polling for jobs works again") && strings.Contains(out, "reporting results works again") { + break + } + time.Sleep(50 * time.Millisecond) + } + cancel() + <-done + out := logs.String() + for _, want := range []string{`"msg":"polling for jobs works again"`, `"failures":1`, `"msg":"reporting results works again"`, `"sent":1`} { + if !strings.Contains(out, want) { + t.Errorf("log lacks %s:\n%s", want, out) + } + } + if n := strings.Count(out, "works again"); n != 2 { + t.Errorf("recovery logged %d times, want once each", n) + } +}