Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3bc927a5f7 | ||
|
|
94c529a97e | ||
|
|
71219d8031 | ||
|
|
e26194d260 | ||
|
|
61a50ee6f0 | ||
|
|
4246e37384 |
No files matched your search
+26
-4
@@ -222,12 +222,31 @@ func (s *Server) agentJobs(c *gin.Context) {
|
||||
}
|
||||
}()
|
||||
}
|
||||
entries, err := s.sched.Take(pollCtx, instance, min(req.Max, maxJobBatch), wait)
|
||||
entries, stale, err := s.sched.Take(pollCtx, instance, min(req.Max, maxJobBatch), wait)
|
||||
s.metrics.Stale(stale)
|
||||
if err != nil && pollCtx.Err() == nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
jobs, orgs, err := s.resolveJobs(ctx, agentOf(c), entries)
|
||||
agent := agentOf(c)
|
||||
if len(entries) > 0 {
|
||||
// The long poll may have waited for a while: settings such as
|
||||
// allow_private apply to the jobs as they are now.
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
agent, err = q.GetAgentByHash(ctx, HashToken(bearerToken(c)))
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusUnauthorized, "unauthenticated")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
jobs, orgs, err := s.resolveJobs(ctx, agent, entries)
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -394,8 +413,11 @@ func truncateValid(s string, n int) string {
|
||||
}
|
||||
|
||||
// resultClaimTTL covers the retries of a checker that lost the answer to a
|
||||
// report, which happen within minutes.
|
||||
const resultClaimTTL = 2 * time.Hour
|
||||
// report: the next report, seconds later, or the first after the API is
|
||||
// back. A claim is one Redis key per result, so the TTL sets how much of
|
||||
// Redis they take: at 500 results a second, 10 minutes are 300,000 keys,
|
||||
// about 70 MiB.
|
||||
const resultClaimTTL = 10 * time.Minute
|
||||
|
||||
// claimResults drops results already received. A checker that does not get
|
||||
// the answer to a report, say because the connection broke while the API was
|
||||
|
||||
@@ -85,7 +85,9 @@ func TestCheckerNetwork(t *testing.T) {
|
||||
}
|
||||
waitResult := func(id string, ok bool, what string) {
|
||||
t.Helper()
|
||||
waitFor(t, 20*time.Second, what, func() bool {
|
||||
// Two runs at most: the one already handed out, then the next on
|
||||
// the monitor's phase, up to one and a half intervals later.
|
||||
waitFor(t, 30*time.Second, what, func() bool {
|
||||
got, msg, seen := latestOf(owner, id)
|
||||
return seen && got == ok && (ok || strings.Contains(msg, "non-public"))
|
||||
})
|
||||
|
||||
+75
-28
@@ -37,9 +37,15 @@ const (
|
||||
|
||||
// storeEvidence keeps the evidence of accepted results: per monitor and
|
||||
// region the latest success, and failures unless an identical one was kept
|
||||
// within failureEvidenceEvery. Evidence is an aid; failures are logged and
|
||||
// never fail the report.
|
||||
// within failureEvidenceEvery. All of a report's evidence is written in one
|
||||
// transaction, so a report full of it stays quick and the checker can go
|
||||
// on. Evidence is an aid; failures are logged and never fail the report.
|
||||
func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.UUID, results []agentapi.Result, monitors map[uuid.UUID]store.MonitorsForResultsRow) {
|
||||
var (
|
||||
successes = map[uuid.UUID]agentapi.Result{}
|
||||
failures []agentapi.Result
|
||||
failed []uuid.UUID
|
||||
)
|
||||
for _, r := range results {
|
||||
m, ok := monitors[r.MonitorID]
|
||||
if len(r.Evidence) == 0 || !ok {
|
||||
@@ -49,34 +55,75 @@ func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.
|
||||
s.log.WarnContext(ctx, "dropping malformed evidence", "monitor", m.ID, "bytes", len(r.Evidence))
|
||||
continue
|
||||
}
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if r.OK {
|
||||
if err := q.DeleteSuccessEvidence(ctx, store.DeleteSuccessEvidenceParams{MonitorID: m.ID, Region: region}); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
last, err := q.LastFailureEvidence(ctx, store.LastFailureEvidenceParams{MonitorID: m.ID, Region: region})
|
||||
if err == nil && last.Error == r.Error && r.StartedAt.Sub(last.Time) < failureEvidenceEvery {
|
||||
return nil
|
||||
}
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if r.OK {
|
||||
// Only the latest success is kept anyway.
|
||||
if prev, seen := successes[r.MonitorID]; !seen || r.StartedAt.After(prev.StartedAt) {
|
||||
successes[r.MonitorID] = r
|
||||
}
|
||||
row := store.InsertEvidenceParams{
|
||||
OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence,
|
||||
}
|
||||
if r.StatusCode > 0 {
|
||||
row.StatusCode = ptr(int32(r.StatusCode))
|
||||
}
|
||||
if r.Error != "" {
|
||||
row.Error = ptr(truncateValid(r.Error, 500))
|
||||
}
|
||||
return q.InsertEvidence(ctx, row)
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "storing evidence failed", "monitor", m.ID, "error", err)
|
||||
continue
|
||||
}
|
||||
failures = append(failures, r)
|
||||
if !slices.Contains(failed, r.MonitorID) {
|
||||
failed = append(failed, r.MonitorID)
|
||||
}
|
||||
}
|
||||
if len(successes) == 0 && len(failures) == 0 {
|
||||
return
|
||||
}
|
||||
slices.SortFunc(failures, func(a, b agentapi.Result) int { return a.StartedAt.Compare(b.StartedAt) })
|
||||
insert := func(q *store.Queries, r agentapi.Result) error {
|
||||
m := monitors[r.MonitorID]
|
||||
row := store.InsertEvidenceParams{
|
||||
OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence,
|
||||
}
|
||||
if r.StatusCode > 0 {
|
||||
row.StatusCode = ptr(int32(r.StatusCode))
|
||||
}
|
||||
if r.Error != "" {
|
||||
row.Error = ptr(truncateValid(r.Error, 500))
|
||||
}
|
||||
return q.InsertEvidence(ctx, row)
|
||||
}
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if len(successes) > 0 {
|
||||
ids := make([]uuid.UUID, 0, len(successes))
|
||||
for id := range successes {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if err := q.DeleteSuccessEvidence(ctx, store.DeleteSuccessEvidenceParams{Region: region, MonitorIds: ids}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range successes {
|
||||
if err := insert(q, r); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows, err := q.LastFailureEvidence(ctx, store.LastFailureEvidenceParams{Region: region, MonitorIds: failed})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
last := make(map[uuid.UUID]store.LastFailureEvidenceRow, len(rows))
|
||||
for _, l := range rows {
|
||||
last[l.MonitorID] = l
|
||||
}
|
||||
for _, r := range failures {
|
||||
kept := truncateValid(r.Error, 500)
|
||||
if l, ok := last[r.MonitorID]; ok && l.Error == kept && r.StartedAt.Sub(l.Time) < failureEvidenceEvery {
|
||||
continue
|
||||
}
|
||||
if err := insert(q, r); err != nil {
|
||||
return err
|
||||
}
|
||||
last[r.MonitorID] = store.LastFailureEvidenceRow{MonitorID: r.MonitorID, Time: r.StartedAt, Error: kept}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "storing evidence failed", "results", len(successes)+len(failures), "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,12 +2,17 @@ package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
)
|
||||
|
||||
func TestEvidence(t *testing.T) {
|
||||
@@ -103,3 +108,62 @@ func TestEvidence(t *testing.T) {
|
||||
t.Error("the monitor page links evidence for a viewer")
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvidenceBatch stores a report with evidence of several monitors and
|
||||
// runs at once, as a checker sends after a backlog.
|
||||
func TestEvidenceBatch(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
tok, region := e.platformChecker(t, uniq("ev-batch-"))
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("evb")+".test", uniq("evb-"))
|
||||
monitor := func() uuid.UUID {
|
||||
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
|
||||
})
|
||||
return uuid.MustParse(m["id"].(string))
|
||||
}
|
||||
up, down := monitor(), monitor()
|
||||
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
|
||||
ev := json.RawMessage(`{"steps":[]}`)
|
||||
at := time.Now().Add(-time.Minute).Truncate(time.Millisecond)
|
||||
run := func(m uuid.UUID, after time.Duration, ok bool, msg string) agentapi.Result {
|
||||
return agentapi.Result{MonitorID: m, ScheduledAt: at.Add(after), StartedAt: at.Add(after), OK: ok, Error: msg, Evidence: ev}
|
||||
}
|
||||
if err := client.Report(context.Background(), []agentapi.Result{
|
||||
run(up, 0, true, ""),
|
||||
run(up, time.Second, true, ""),
|
||||
run(down, 0, false, "boom"),
|
||||
run(down, time.Second, false, "boom"),
|
||||
run(down, 2*time.Second, false, "other"),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The latest success only; failures unless the same one was just kept.
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok AND time = $2`, up, at.Add(time.Second)); n != 1 {
|
||||
t.Errorf("success evidence of the latest run = %d rows, want 1", n)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1`, up); n != 1 {
|
||||
t.Errorf("success evidence rows = %d, want 1", n)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, down); n != 2 {
|
||||
t.Errorf("failure evidence rows = %d, want 2: boom once, then other", n)
|
||||
}
|
||||
|
||||
// The next report replaces the success and thins out the failure
|
||||
// already kept.
|
||||
if err := client.Report(context.Background(), []agentapi.Result{
|
||||
run(up, 5*time.Second, true, ""),
|
||||
run(down, 10*time.Second, false, "other"),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok AND time = $2`, up, at.Add(5*time.Second)); n != 1 {
|
||||
t.Errorf("success evidence after the next report: latest run kept %d times, want 1", n)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1`, up); n != 1 {
|
||||
t.Errorf("success evidence rows after the next report = %d, want 1", n)
|
||||
}
|
||||
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, down); n != 2 {
|
||||
t.Errorf("failure evidence rows after the next report = %d, want still 2", n)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"math/rand/v2"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -51,6 +52,8 @@ type Runner struct {
|
||||
|
||||
evidenceMu sync.Mutex
|
||||
evidence map[uuid.UUID]evidenceState
|
||||
// jitter returns a random duration in [0, d), replaced in tests.
|
||||
jitter func(d time.Duration) time.Duration
|
||||
}
|
||||
|
||||
// evidenceState remembers what was last sent for a monitor.
|
||||
@@ -66,13 +69,23 @@ 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.
|
||||
//
|
||||
// Evidence sent for another reason than the period, like the first result
|
||||
// after a start, puts the next periodic one at a random point of the
|
||||
// period. Otherwise every monitor would send its evidence in the same
|
||||
// minute every period after a restart, and the API would have to store all
|
||||
// of it at once.
|
||||
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 {
|
||||
periodic := seen && last.ok == ok && now.Sub(last.sent) >= evidenceEvery
|
||||
send := !ok || !seen || last.ok != ok || periodic
|
||||
switch {
|
||||
case periodic:
|
||||
last.sent = now
|
||||
case send:
|
||||
last.sent = now.Add(-r.jitter(evidenceEvery))
|
||||
}
|
||||
last.ok = ok
|
||||
r.evidence[monitor] = last
|
||||
@@ -90,6 +103,7 @@ func New(api API, concurrency int, log *slog.Logger) *Runner {
|
||||
results: make(chan agentapi.Result, 1024),
|
||||
|
||||
evidence: map[uuid.UUID]evidenceState{},
|
||||
jitter: rand.N[time.Duration],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
|
||||
func TestEvidencePolicy(t *testing.T) {
|
||||
r := New(nil, 1, slog.New(slog.DiscardHandler))
|
||||
r.jitter = func(time.Duration) time.Duration { return 0 }
|
||||
m := uuid.New()
|
||||
now := time.Now()
|
||||
steps := []struct {
|
||||
@@ -31,3 +32,39 @@ func TestEvidencePolicy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestEvidenceSpreadsAfterStart starts with many healthy monitors at once:
|
||||
// their periodic evidence must not all fall into the same minute again.
|
||||
func TestEvidenceSpreadsAfterStart(t *testing.T) {
|
||||
r := New(nil, 1, slog.New(slog.DiscardHandler))
|
||||
start := time.Now()
|
||||
const monitors = 600
|
||||
ids := make([]uuid.UUID, monitors)
|
||||
for i := range ids {
|
||||
ids[i] = uuid.New()
|
||||
if !r.shouldSendEvidence(ids[i], true, start) {
|
||||
t.Fatal("first result sent no evidence")
|
||||
}
|
||||
}
|
||||
// One result per monitor and minute over the next period.
|
||||
perMinute := map[int]int{}
|
||||
for minute := 1; minute <= int(evidenceEvery/time.Minute); minute++ {
|
||||
for _, id := range ids {
|
||||
if r.shouldSendEvidence(id, true, start.Add(time.Duration(minute)*time.Minute)) {
|
||||
perMinute[minute]++
|
||||
}
|
||||
}
|
||||
}
|
||||
total, peak := 0, 0
|
||||
for _, n := range perMinute {
|
||||
total += n
|
||||
peak = max(peak, n)
|
||||
}
|
||||
if total != monitors {
|
||||
t.Errorf("periodic evidence in the first period = %d, want one per monitor, %d", total, monitors)
|
||||
}
|
||||
// 60 a minute on average; all 600 in one minute without the jitter.
|
||||
if peak > 150 {
|
||||
t.Errorf("busiest minute sent %d evidence, want them spread at about %d a minute", peak, monitors/10)
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ type Metrics struct {
|
||||
duration *prometheus.HistogramVec
|
||||
inFlight prometheus.Gauge
|
||||
dispatched prometheus.Counter
|
||||
stale prometheus.Counter
|
||||
results *prometheus.CounterVec
|
||||
rejected *prometheus.CounterVec
|
||||
resultDelay prometheus.Histogram
|
||||
@@ -62,6 +63,10 @@ func New(edition string) *Metrics {
|
||||
Namespace: namespace, Name: "checks_dispatched_total",
|
||||
Help: "Checks this instance moved from the schedule to the checkers' queues.",
|
||||
}),
|
||||
stale: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "checks_stale_total",
|
||||
Help: "Queued checks dropped because they waited longer than two intervals; a newer run of the monitor was queued by then.",
|
||||
}),
|
||||
results: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: namespace, Name: "check_results_total",
|
||||
Help: "Check results stored, by region (\"own\" for organizations' own checkers) and outcome.",
|
||||
@@ -116,7 +121,7 @@ func New(edition string) *Metrics {
|
||||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
build,
|
||||
m.requests, m.duration, m.inFlight,
|
||||
m.dispatched, m.results, m.rejected, m.resultDelay,
|
||||
m.dispatched, m.stale, m.results, m.rejected, m.resultDelay,
|
||||
m.notifications, m.notifyDuration, m.subscriberMail,
|
||||
m.incidents,
|
||||
m.jobRuns, m.jobDuration, m.jobSuccess,
|
||||
@@ -162,6 +167,13 @@ func (m *Metrics) HTTP(streaming ...string) gin.HandlerFunc {
|
||||
// Dispatched counts checks moved to the checkers' queues.
|
||||
func (m *Metrics) Dispatched(n int) { m.dispatched.Add(float64(n)) }
|
||||
|
||||
// Stale counts n queued checks dropped as out of date.
|
||||
func (m *Metrics) Stale(n int) {
|
||||
if n > 0 {
|
||||
m.stale.Add(float64(n))
|
||||
}
|
||||
}
|
||||
|
||||
// Result counts a stored check result and how long it took to arrive.
|
||||
func (m *Metrics) Result(region string, ok bool, delay time.Duration) {
|
||||
m.results.WithLabelValues(region, strconv.FormatBool(ok)).Inc()
|
||||
|
||||
@@ -66,6 +66,8 @@ func TestJobRecordsOutcome(t *testing.T) {
|
||||
func TestCountersAndHandler(t *testing.T) {
|
||||
m := New("cloud")
|
||||
m.Dispatched(3)
|
||||
m.Stale(2)
|
||||
m.Stale(0)
|
||||
m.Result("fsn", true, 2*time.Second)
|
||||
m.Result("fsn", false, -time.Second)
|
||||
m.Rejected("duplicate", 2)
|
||||
@@ -79,6 +81,7 @@ func TestCountersAndHandler(t *testing.T) {
|
||||
got, want float64
|
||||
}{
|
||||
"dispatched": {testutil.ToFloat64(m.dispatched), 3},
|
||||
"stale": {testutil.ToFloat64(m.stale), 2},
|
||||
"ok results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "true")), 1},
|
||||
"failed results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "false")), 1},
|
||||
"duplicates": {testutil.ToFloat64(m.rejected.WithLabelValues("duplicate")), 2},
|
||||
|
||||
+100
-35
@@ -68,6 +68,9 @@ func New(rdb redis.UniversalClient) *Scheduler {
|
||||
type Entry struct {
|
||||
MonitorID uuid.UUID
|
||||
ScheduledAt time.Time
|
||||
// DispatchedAt is when the run was queued; zero for runs queued before
|
||||
// dispatch times were recorded.
|
||||
DispatchedAt time.Time
|
||||
}
|
||||
|
||||
// Monitor is the schedule-relevant part of a monitor.
|
||||
@@ -267,7 +270,7 @@ for i = 1, #due, 2 do
|
||||
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('RPUSH', q, m .. '|' .. string.format('%.0f', at) .. '|' .. string.format('%.0f', now))
|
||||
redis.call('EXPIRE', q, ARGV[5])
|
||||
local nxt
|
||||
local phase = tonumber(redis.call('HGET', KEYS[4], m) or '')
|
||||
@@ -324,48 +327,100 @@ func (s *Scheduler) LastSeen(ctx context.Context, region string, instance uuid.U
|
||||
return time.UnixMilli(int64(score)), err
|
||||
}
|
||||
|
||||
// staleAfter is how many intervals a queued run may wait before Take drops
|
||||
// it. By then a newer run of the monitor has been dispatched, since the next
|
||||
// run is due at most one and a half intervals after the last dispatch, so
|
||||
// a checker that fell behind catches up instead of working off runs that
|
||||
// are out of date.
|
||||
const staleAfter = 2
|
||||
|
||||
// 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) {
|
||||
// do not hold up shutdown or cancelled requests. Runs queued for longer than
|
||||
// staleAfter intervals are dropped; Take returns how many.
|
||||
func (s *Scheduler) Take(ctx context.Context, instance uuid.UUID, max int, wait time.Duration) ([]Entry, int, error) {
|
||||
if max <= 0 {
|
||||
return nil, nil
|
||||
return nil, 0, 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
|
||||
stale := 0
|
||||
for ctx.Err() == nil {
|
||||
raw, err := s.rdb.LPopCount(ctx, q, max).Result()
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
return nil, stale, err
|
||||
}
|
||||
// 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
|
||||
if len(raw) == 0 {
|
||||
left := time.Until(deadline)
|
||||
if left <= 0 {
|
||||
return nil, stale, nil
|
||||
}
|
||||
raw = append(raw, more...)
|
||||
// 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, stale, 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, stale, err
|
||||
}
|
||||
raw = append(raw, more...)
|
||||
}
|
||||
}
|
||||
out, n, err := s.fresh(ctx, raw)
|
||||
if err != nil {
|
||||
return nil, stale, err
|
||||
}
|
||||
stale += n
|
||||
if len(out) > 0 {
|
||||
return out, stale, nil
|
||||
}
|
||||
}
|
||||
out := make([]Entry, 0, len(raw))
|
||||
return nil, stale, nil
|
||||
}
|
||||
|
||||
// fresh parses popped runs and drops those queued for longer than
|
||||
// staleAfter intervals. It returns the rest and how many it dropped.
|
||||
func (s *Scheduler) fresh(ctx context.Context, raw []string) ([]Entry, int, error) {
|
||||
entries := make([]Entry, 0, len(raw))
|
||||
var ids []string
|
||||
for _, r := range raw {
|
||||
if e, ok := parseEntry(r); ok {
|
||||
out = append(out, e)
|
||||
entries = append(entries, e)
|
||||
if !e.DispatchedAt.IsZero() {
|
||||
ids = append(ids, e.MonitorID.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
if len(ids) == 0 {
|
||||
return entries, 0, nil
|
||||
}
|
||||
vals, err := s.rdb.HMGet(ctx, keyIntervals, ids...).Result()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
interval := make(map[uuid.UUID]time.Duration, len(ids))
|
||||
for i, v := range vals {
|
||||
str, _ := v.(string)
|
||||
if ms, err := strconv.ParseInt(str, 10, 64); err == nil {
|
||||
interval[uuid.MustParse(ids[i])] = time.Duration(ms) * time.Millisecond
|
||||
}
|
||||
}
|
||||
now := s.now()
|
||||
out := entries[:0]
|
||||
for _, e := range entries {
|
||||
// Removed monitors are left to the caller, which drops them.
|
||||
if iv, ok := interval[e.MonitorID]; ok && !e.DispatchedAt.IsZero() && now.Sub(e.DispatchedAt) > staleAfter*iv {
|
||||
continue
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, len(entries) - len(out), nil
|
||||
}
|
||||
|
||||
// blpop is BLPOP with a timeout below a second, which go-redis would round
|
||||
@@ -404,7 +459,7 @@ 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))
|
||||
local at = tonumber(string.match(job, '^[^|]*|([^|]*)'))
|
||||
if at ~= nil and at <= cutoff then n = n + 1 end
|
||||
end
|
||||
end
|
||||
@@ -419,18 +474,28 @@ func (s *Scheduler) Overdue(ctx context.Context, region string, late time.Durati
|
||||
s.now().Add(-late).UnixMilli(), jobsPrefix).Int64()
|
||||
}
|
||||
|
||||
// parseEntry parses a queued run: "monitor|scheduled ms|dispatched ms",
|
||||
// or without the dispatch time as queued by older releases.
|
||||
func parseEntry(s string) (Entry, bool) {
|
||||
id, at, ok := strings.Cut(s, "|")
|
||||
if !ok {
|
||||
parts := strings.Split(s, "|")
|
||||
if len(parts) < 2 || len(parts) > 3 {
|
||||
return Entry{}, false
|
||||
}
|
||||
mid, err := uuid.Parse(id)
|
||||
mid, err := uuid.Parse(parts[0])
|
||||
if err != nil {
|
||||
return Entry{}, false
|
||||
}
|
||||
ms, err := strconv.ParseFloat(at, 64)
|
||||
ms, err := strconv.ParseFloat(parts[1], 64)
|
||||
if err != nil {
|
||||
return Entry{}, false
|
||||
}
|
||||
return Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}, true
|
||||
e := Entry{MonitorID: mid, ScheduledAt: time.UnixMilli(int64(ms))}
|
||||
if len(parts) == 3 {
|
||||
d, err := strconv.ParseFloat(parts[2], 64)
|
||||
if err != nil {
|
||||
return Entry{}, false
|
||||
}
|
||||
e.DispatchedAt = time.UnixMilli(int64(d))
|
||||
}
|
||||
return e, true
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func newTest(t *testing.T) (*Scheduler, *time.Time) {
|
||||
|
||||
func takeAll(t *testing.T, s *Scheduler, inst uuid.UUID) []Entry {
|
||||
t.Helper()
|
||||
e, err := s.Take(context.Background(), inst, 1000, 0)
|
||||
e, _, err := s.Take(context.Background(), inst, 1000, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("Take() failed: %v", err)
|
||||
}
|
||||
@@ -196,7 +196,7 @@ func TestTakeWaits(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
in := uuid.New()
|
||||
start := time.Now()
|
||||
got, err := s.Take(ctx, in, 10, 300*time.Millisecond)
|
||||
got, _, err := s.Take(ctx, in, 10, 300*time.Millisecond)
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatalf("Take() on empty queue = %v, %v", got, err)
|
||||
}
|
||||
@@ -214,7 +214,7 @@ func TestTakeGetsAJobDuringAShortWait(t *testing.T) {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
s.rdb.RPush(ctx, jobsPrefix+in.String(), monitor.String()+"|1800000000000")
|
||||
}()
|
||||
got, err := s.Take(ctx, in, 10, 600*time.Millisecond)
|
||||
got, _, err := s.Take(ctx, in, 10, 600*time.Millisecond)
|
||||
if err != nil || len(got) != 1 || got[0].MonitorID != monitor {
|
||||
t.Fatalf("Take() = %v, %v; want the job pushed while waiting", got, err)
|
||||
}
|
||||
@@ -225,7 +225,7 @@ func TestTakeReturnsWhenCancelled(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go func() { time.Sleep(100 * time.Millisecond); cancel() }()
|
||||
start := time.Now()
|
||||
_, _ = s.Take(ctx, uuid.New(), 10, 20*time.Second)
|
||||
_, _, _ = s.Take(ctx, uuid.New(), 10, 20*time.Second)
|
||||
if took := time.Since(start); took > 2*time.Second {
|
||||
t.Errorf("Take() returned %v after cancellation, want within about a second", took)
|
||||
}
|
||||
@@ -282,7 +282,7 @@ func TestOverdueCountsRunsLeftBehind(t *testing.T) {
|
||||
if n := overdue(); n != 2 {
|
||||
t.Errorf("Overdue() with the runs left in a queue = %d, want 2", n)
|
||||
}
|
||||
if _, err := s.Take(ctx, busy, 10, 0); err != nil {
|
||||
if _, _, err := s.Take(ctx, busy, 10, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n := overdue(); n != 0 {
|
||||
@@ -421,3 +421,91 @@ func TestNextSlot(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTakeDropsStaleRuns lets a busy instance fall behind: the runs it left
|
||||
// in its queue for more than two intervals are dropped, the newer ones of
|
||||
// the same monitors are handed out.
|
||||
func TestTakeDropsStaleRuns(t *testing.T) {
|
||||
s, now := newTest(t)
|
||||
ctx := context.Background()
|
||||
busy := uuid.New()
|
||||
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
|
||||
_ = s.Upsert(ctx, m, nil)
|
||||
_ = s.Heartbeat(ctx, "eu", busy)
|
||||
mustDispatch(t, s)
|
||||
|
||||
// Within two intervals the run is still handed out.
|
||||
*now = now.Add(2 * time.Minute)
|
||||
if got, stale, err := s.Take(ctx, busy, 10, 0); err != nil || len(got) != 1 || stale != 0 {
|
||||
t.Fatalf("Take() after two intervals = %v, %d stale, %v; want the run", got, stale, err)
|
||||
}
|
||||
|
||||
// Left waiting longer, it is dropped in favour of the newer run.
|
||||
_ = s.Heartbeat(ctx, "eu", busy)
|
||||
mustDispatch(t, s)
|
||||
*now = now.Add(2*time.Minute + time.Second)
|
||||
_ = s.Heartbeat(ctx, "eu", busy)
|
||||
if n := mustDispatch(t, s); n != 1 {
|
||||
t.Fatalf("Dispatch() of the newer run = %d, want 1", n)
|
||||
}
|
||||
got, stale, err := s.Take(ctx, busy, 10, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stale != 1 || len(got) != 1 || !got[0].DispatchedAt.Equal(*now) {
|
||||
t.Errorf("Take() = %+v with %d stale, want only the run dispatched now and 1 stale", got, stale)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTakeSkipsAllStaleRuns does not return empty-handed while fresh runs
|
||||
// wait behind a batch of stale ones.
|
||||
func TestTakeSkipsAllStaleRuns(t *testing.T) {
|
||||
s, now := newTest(t)
|
||||
ctx := context.Background()
|
||||
in := uuid.New()
|
||||
for range 5 {
|
||||
_ = s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil)
|
||||
}
|
||||
_ = s.Heartbeat(ctx, "eu", in)
|
||||
mustDispatch(t, s)
|
||||
*now = now.Add(3 * time.Minute)
|
||||
fresh := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
|
||||
_ = s.Upsert(ctx, fresh, nil)
|
||||
_ = s.Heartbeat(ctx, "eu", in)
|
||||
mustDispatch(t, s)
|
||||
// The first pop of 5 holds only stale runs.
|
||||
got, stale, err := s.Take(ctx, in, 5, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stale != 5 {
|
||||
t.Errorf("stale runs = %d, want 5", stale)
|
||||
}
|
||||
// It pops on and hands out the next runs, all dispatched now.
|
||||
if len(got) != 5 {
|
||||
t.Fatalf("Take() = %d runs, want 5", len(got))
|
||||
}
|
||||
for _, e := range got {
|
||||
if !e.DispatchedAt.Equal(*now) {
|
||||
t.Errorf("Take() handed out %+v, want only runs dispatched now", e)
|
||||
}
|
||||
}
|
||||
if rest := takeAll(t, s, in); len(rest) != 1 || rest[0].MonitorID != fresh.ID {
|
||||
t.Errorf("remaining runs = %+v, want the new monitor's", rest)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseEntry(t *testing.T) {
|
||||
id := uuid.New()
|
||||
if e, ok := parseEntry(id.String() + "|1800000000000"); !ok || !e.DispatchedAt.IsZero() || e.ScheduledAt.UnixMilli() != 1_800_000_000_000 {
|
||||
t.Errorf("entry without dispatch time = %+v, %v", e, ok)
|
||||
}
|
||||
if e, ok := parseEntry(id.String() + "|1800000000000|1800000005000"); !ok || e.DispatchedAt.UnixMilli() != 1_800_000_005_000 {
|
||||
t.Errorf("entry with dispatch time = %+v, %v", e, ok)
|
||||
}
|
||||
for _, bad := range []string{"x|1", id.String(), id.String() + "|1|2|3", id.String() + "|1|x"} {
|
||||
if _, ok := parseEntry(bad); ok {
|
||||
t.Errorf("parseEntry(%q) accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,17 +13,18 @@ import (
|
||||
)
|
||||
|
||||
const deleteSuccessEvidence = `-- name: DeleteSuccessEvidence :exec
|
||||
DELETE FROM check_evidence WHERE monitor_id = $1 AND region = $2 AND ok
|
||||
DELETE FROM check_evidence
|
||||
WHERE region = $1 AND ok AND monitor_id = ANY($2::uuid[])
|
||||
`
|
||||
|
||||
type DeleteSuccessEvidenceParams struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
Region string
|
||||
MonitorIds []uuid.UUID
|
||||
}
|
||||
|
||||
// Only the latest success per monitor and region is kept.
|
||||
func (q *Queries) DeleteSuccessEvidence(ctx context.Context, arg DeleteSuccessEvidenceParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteSuccessEvidence, arg.MonitorID, arg.Region)
|
||||
_, err := q.db.Exec(ctx, deleteSuccessEvidence, arg.Region, arg.MonitorIds)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -124,27 +125,43 @@ func (q *Queries) InsertEvidence(ctx context.Context, arg InsertEvidenceParams)
|
||||
return err
|
||||
}
|
||||
|
||||
const lastFailureEvidence = `-- name: LastFailureEvidence :one
|
||||
SELECT time, coalesce(error, '')::text AS error FROM check_evidence
|
||||
WHERE monitor_id = $1 AND region = $2 AND NOT ok
|
||||
ORDER BY time DESC LIMIT 1
|
||||
const lastFailureEvidence = `-- name: LastFailureEvidence :many
|
||||
SELECT DISTINCT ON (monitor_id) monitor_id, time, coalesce(error, '')::text AS error
|
||||
FROM check_evidence
|
||||
WHERE region = $1 AND NOT ok AND monitor_id = ANY($2::uuid[])
|
||||
ORDER BY monitor_id, time DESC
|
||||
`
|
||||
|
||||
type LastFailureEvidenceParams struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
Region string
|
||||
MonitorIds []uuid.UUID
|
||||
}
|
||||
|
||||
type LastFailureEvidenceRow struct {
|
||||
Time time.Time
|
||||
Error string
|
||||
MonitorID uuid.UUID
|
||||
Time time.Time
|
||||
Error string
|
||||
}
|
||||
|
||||
func (q *Queries) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error) {
|
||||
row := q.db.QueryRow(ctx, lastFailureEvidence, arg.MonitorID, arg.Region)
|
||||
var i LastFailureEvidenceRow
|
||||
err := row.Scan(&i.Time, &i.Error)
|
||||
return i, err
|
||||
// The newest failure per monitor in region.
|
||||
func (q *Queries) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) ([]LastFailureEvidenceRow, error) {
|
||||
rows, err := q.db.Query(ctx, lastFailureEvidence, arg.Region, arg.MonitorIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []LastFailureEvidenceRow{}
|
||||
for rows.Next() {
|
||||
var i LastFailureEvidenceRow
|
||||
if err := rows.Scan(&i.MonitorID, &i.Time, &i.Error); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listEvidence = `-- name: ListEvidence :many
|
||||
|
||||
@@ -217,7 +217,8 @@ type Querier interface {
|
||||
InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error)
|
||||
InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, error)
|
||||
IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
|
||||
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error)
|
||||
// The newest failure per monitor in region.
|
||||
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) ([]LastFailureEvidenceRow, error)
|
||||
// latest_results holds the newest check result per monitor and region
|
||||
// (see migration 00055) and has row-level security.
|
||||
// Whether the newest result of each region of the monitors ids succeeded.
|
||||
|
||||
@@ -4,12 +4,15 @@ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
|
||||
|
||||
-- name: DeleteSuccessEvidence :exec
|
||||
-- Only the latest success per monitor and region is kept.
|
||||
DELETE FROM check_evidence WHERE monitor_id = $1 AND region = $2 AND ok;
|
||||
DELETE FROM check_evidence
|
||||
WHERE region = sqlc.arg(region) AND ok AND monitor_id = ANY(sqlc.arg(monitor_ids)::uuid[]);
|
||||
|
||||
-- name: LastFailureEvidence :one
|
||||
SELECT time, coalesce(error, '')::text AS error FROM check_evidence
|
||||
WHERE monitor_id = $1 AND region = $2 AND NOT ok
|
||||
ORDER BY time DESC LIMIT 1;
|
||||
-- name: LastFailureEvidence :many
|
||||
-- The newest failure per monitor in region.
|
||||
SELECT DISTINCT ON (monitor_id) monitor_id, time, coalesce(error, '')::text AS error
|
||||
FROM check_evidence
|
||||
WHERE region = sqlc.arg(region) AND NOT ok AND monitor_id = ANY(sqlc.arg(monitor_ids)::uuid[])
|
||||
ORDER BY monitor_id, time DESC;
|
||||
|
||||
-- name: ListEvidence :many
|
||||
-- Newest first, a page from a keyset cursor (see paging.go).
|
||||
|
||||
Reference in new issue
Block a user