Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71219d8031 | ||
|
|
e26194d260 |
No files matched your search
+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)
|
||||
}
|
||||
}
|
||||
@@ -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