feat: show unchecked monitors and tell about regions without checkers
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m17s
ci / test (pull_request) Successful in 12m7s
ci / build (pull_request) Successful in 19m34s
ci / image (pull_request) Successful in 3m15s
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m17s
ci / test (pull_request) Successful in 12m7s
ci / build (pull_request) Successful in 19m34s
ci / image (pull_request) Successful in 3m15s
A region whose checkers had all gone left its monitors looking up: the console and status pages took the last result, however old, and nobody was told. - A region's last result counts only while it is younger than the evaluator's staleness (3 intervals, at least 2 minutes); older ones show as "no data since …" in the console and leave status page components unknown instead of operational. - A monitor no region has reported for recently is marked "not being checked", counted on the dashboard with an explanation, and noted on its page. - A region watch on every API replica emails the platform's admins (platform regions) or the organization's owners (own regions) once a region with checkers and enabled monitors has had no live checker for UPTIME_REGION_ALERT_AFTER (default 5m), and again when one is back. The dashboard names such regions at once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
f3d0a4c844
commit
dc2e21f964
18 files changed
+3272
-2652
No files matched your search
+29
-1
@@ -21,6 +21,7 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
@@ -91,7 +92,14 @@ func (s *Server) dashboard(c *gin.Context) {
|
||||
v.Ranges = rangeOptions(c, data.rng, earliest, data.now)
|
||||
for _, m := range data.rows {
|
||||
v.Counts[m.Status]++
|
||||
if m.Unchecked {
|
||||
v.Unchecked++
|
||||
}
|
||||
}
|
||||
for id, since := range s.regionsWithoutChecker(c.Request.Context(), data.usedRegions) {
|
||||
v.DeadRegions = append(v.DeadRegions, web.DeadRegion{Name: data.regionOf[id].Name, Since: since.Local().Format("2006-01-02 15:04")})
|
||||
}
|
||||
slices.SortFunc(v.DeadRegions, func(a, b web.DeadRegion) int { return strings.Compare(a.Name, b.Name) })
|
||||
}
|
||||
web.Render(c, http.StatusOK, web.Dashboard(s.pageFor(c, "console.monitors.title"), me, v))
|
||||
}
|
||||
@@ -214,6 +222,8 @@ type monitorData struct {
|
||||
firstRegion map[uuid.UUID]map[string]time.Time
|
||||
// statuses are the organization's own incident statuses.
|
||||
statuses customStatuses
|
||||
// usedRegions are the regions the enabled monitors are checked from.
|
||||
usedRegions []uuid.UUID
|
||||
}
|
||||
|
||||
// loadFirstData finds when monitors and their regions first reported. The
|
||||
@@ -366,6 +376,13 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
for _, a := range assigned {
|
||||
regionsOf[a.MonitorID] = append(regionsOf[a.MonitorID], a.RegionID)
|
||||
}
|
||||
for _, m := range monitors {
|
||||
if m.Enabled {
|
||||
d.usedRegions = append(d.usedRegions, regionsOf[m.ID]...)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(d.usedRegions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
||||
d.usedRegions = slices.Compact(d.usedRegions)
|
||||
latestOf := map[uuid.UUID]map[string]store.LatestResultsRow{}
|
||||
for _, l := range latest {
|
||||
if latestOf[l.MonitorID] == nil {
|
||||
@@ -393,9 +410,18 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
}
|
||||
var latencies []int32
|
||||
failing, reported := 0, 0
|
||||
// A region that has not reported for longer than the evaluator
|
||||
// waits is unknown, whatever its last result said; passive monitors
|
||||
// judge their own lateness.
|
||||
staleBefore := now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
|
||||
for _, key := range keys {
|
||||
rs := web.RegionStatus{Name: d.regionNameString(key), Status: web.StatusUnknown, Detail: "–"}
|
||||
if l, ok := latestOf[m.ID][key]; ok {
|
||||
l, ok := latestOf[m.ID][key]
|
||||
if ok && !check.Passive(check.Type(m.Type)) && l.Time.Before(staleBefore) {
|
||||
rs.Detail = i18n.T(ctx, "monitors.no_data_since", "Time", l.Time.Format("15:04"))
|
||||
ok = false
|
||||
}
|
||||
if ok {
|
||||
reported++
|
||||
rs.Detail = l.Time.Format("15:04:05")
|
||||
if l.Ok {
|
||||
@@ -421,6 +447,8 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
|
||||
row.Status = web.StatusDown
|
||||
case reported == 0:
|
||||
row.Status = web.StatusUnknown
|
||||
// Nobody is checking it, unless it is too new to have results.
|
||||
row.Unchecked = !check.Passive(check.Type(m.Type)) && m.CreatedAt.Before(staleBefore)
|
||||
case failing > 0:
|
||||
row.Status = web.StatusDegraded
|
||||
default:
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// LookupTXT lets tests replace DNS lookups for domain verification.
|
||||
var LookupTXT = &lookupTXT
|
||||
|
||||
@@ -17,3 +24,9 @@ func DocumentedRoutes() []string {
|
||||
|
||||
// OpenAPI builds the OpenAPI document.
|
||||
func OpenAPI() map[string]any { return buildOpenAPI("https://uptime.example") }
|
||||
|
||||
// WatchRegionsOf runs the region watch for the regions given only, so
|
||||
// tests are not slowed down by the regions other tests left behind.
|
||||
func (s *Server) WatchRegionsOf(ctx context.Context, now time.Time, ids ...uuid.UUID) error {
|
||||
return s.watchRegions(ctx, now, ids)
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
)
|
||||
|
||||
// A region whose checkers have all gone leaves its monitors unchecked:
|
||||
// they neither go down nor alert. The region watch tells those who run the
|
||||
// region, the platform's admins for platform regions and the owners for an
|
||||
// organization's own, once it has had no live checker for
|
||||
// UPTIME_REGION_ALERT_AFTER, and again when one is back. Every replica runs
|
||||
// it; Redis decides which one sends.
|
||||
|
||||
const (
|
||||
regionWatchEvery = 30 * time.Second
|
||||
// regionWatchTTL bounds the state of a region; one dead for longer is
|
||||
// announced again.
|
||||
regionWatchTTL = 30 * 24 * time.Hour
|
||||
)
|
||||
|
||||
func keyRegionDeadSince(id uuid.UUID) string { return "regionwatch:since:" + id.String() }
|
||||
func keyRegionAlerted(id uuid.UUID) string { return "regionwatch:alerted:" + id.String() }
|
||||
|
||||
// RunRegionWatch watches the regions until ctx ends.
|
||||
func (s *Server) RunRegionWatch(ctx context.Context) {
|
||||
if s.cfg.RegionAlertAfter <= 0 {
|
||||
return
|
||||
}
|
||||
tick := time.NewTicker(regionWatchEvery)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.WatchRegions(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "watching regions failed", "error", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// WatchRegions checks every region with checkers and enabled monitors once.
|
||||
func (s *Server) WatchRegions(ctx context.Context, now time.Time) error {
|
||||
return s.watchRegions(ctx, now, nil)
|
||||
}
|
||||
|
||||
// watchRegions is WatchRegions limited to only, unless only is nil.
|
||||
func (s *Server) watchRegions(ctx context.Context, now time.Time, only []uuid.UUID) error {
|
||||
var regions []store.RegionsToWatchRow
|
||||
if err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
regions, err = q.RegionsToWatch(ctx)
|
||||
return err
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, r := range regions {
|
||||
if only != nil && !slices.Contains(only, r.ID) {
|
||||
continue
|
||||
}
|
||||
live, err := s.sched.Instances(ctx, r.ID.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if live > 0 {
|
||||
since, _ := s.rdb.GetDel(ctx, keyRegionDeadSince(r.ID)).Time()
|
||||
// Only the replica that clears the alert announces the return.
|
||||
if n, err := s.rdb.Del(ctx, keyRegionAlerted(r.ID)).Result(); err == nil && n > 0 {
|
||||
s.mailRegion(ctx, r, since, now, false)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := s.rdb.SetNX(ctx, keyRegionDeadSince(r.ID), now, regionWatchTTL).Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
since, err := s.rdb.Get(ctx, keyRegionDeadSince(r.ID)).Time()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if now.Sub(since) < s.cfg.RegionAlertAfter {
|
||||
continue
|
||||
}
|
||||
if first, err := s.rdb.SetNX(ctx, keyRegionAlerted(r.ID), 1, regionWatchTTL).Result(); err == nil && first {
|
||||
if !s.mailRegion(ctx, r, since, now, true) {
|
||||
// Tried again on the next round.
|
||||
s.rdb.Del(ctx, keyRegionAlerted(r.ID))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// regionsWithoutChecker returns since when each of ids has had no live
|
||||
// checker, for those the watch found without one.
|
||||
func (s *Server) regionsWithoutChecker(ctx context.Context, ids []uuid.UUID) map[uuid.UUID]time.Time {
|
||||
out := map[uuid.UUID]time.Time{}
|
||||
for _, id := range ids {
|
||||
since, err := s.rdb.Get(ctx, keyRegionDeadSince(id)).Time()
|
||||
if err == nil {
|
||||
out[id] = since
|
||||
} else if !errors.Is(err, redis.Nil) {
|
||||
s.log.WarnContext(ctx, "reading region watch failed", "region", id, "error", err)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// mailRegion tells the admins or the owners that r has no live checker
|
||||
// since since, or, when down is false, that it has one again. It reports
|
||||
// false if the mail could not be sent and should be tried again.
|
||||
func (s *Server) mailRegion(ctx context.Context, r store.RegionsToWatchRow, since, now time.Time, down bool) bool {
|
||||
if s.smtp == nil {
|
||||
return true
|
||||
}
|
||||
var to []string
|
||||
link := "/admin"
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if r.OrgID == nil {
|
||||
to, err = q.AdminEmails(ctx)
|
||||
} else {
|
||||
link = "/settings/regions"
|
||||
to, err = q.OrgOwnerEmails(ctx, *r.OrgID)
|
||||
}
|
||||
return err
|
||||
})
|
||||
if err != nil || len(to) == 0 {
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "finding whom to tell about a region failed", "region", r.ID, "error", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
l := s.catalog.Match("")
|
||||
data := map[string]any{
|
||||
"Region": r.Name, "Org": deref(r.OrgName), "Link": s.ticketLink(link),
|
||||
"Since": since.UTC().Format("2006-01-02 15:04 MST"),
|
||||
"Minutes": int(now.Sub(since).Minutes()),
|
||||
}
|
||||
kind := "email.region_back"
|
||||
if down {
|
||||
kind = "email.region_down"
|
||||
}
|
||||
if since.IsZero() {
|
||||
data["Since"], data["Minutes"] = "–", 0
|
||||
}
|
||||
if err := s.smtp.Send(ctx, notify.Mail{To: to, Subject: l.T(kind+".subject", data), Body: l.T(kind+".body", data)}); err != nil {
|
||||
s.log.WarnContext(ctx, "mail about a region failed", "region", r.ID, "error", err)
|
||||
return false
|
||||
}
|
||||
s.log.InfoContext(ctx, "told about a region", "region", r.ID, "down", down, "recipients", len(to))
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
|
||||
)
|
||||
|
||||
func TestUncheckedMonitorsAndRegionsWithoutChecker(t *testing.T) {
|
||||
mail := notifytest.NewSMTP(t)
|
||||
e := newEnvWith(t, func(c *config.API) {
|
||||
c.SMTPURL, c.SignupVerify, c.RegionAlertAfter = mail.URL(), "off", 3*time.Minute
|
||||
})
|
||||
ctx := context.Background()
|
||||
owner := e.browser(t)
|
||||
ownerEmail := "o@" + uniq("rw") + ".test"
|
||||
owner.signup(ownerEmail, uniq("rw-"))
|
||||
// An organization's own region: its owners hear about it.
|
||||
regionName := uniq("Office ")
|
||||
_, reg := owner.do("POST", "/api/v1/org/regions", map[string]any{"key": uniq("office-"), "name": regionName})
|
||||
region := reg["id"].(string)
|
||||
regionID := uuid.MustParse(region)
|
||||
st, agent := owner.do("POST", "/api/v1/org/agents", map[string]any{"kind": "checker", "name": "office-1", "region_id": region})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create agent = %d %v", st, agent)
|
||||
}
|
||||
tok := agent["token"].(string)
|
||||
mailed := func(to, want string) {
|
||||
t.Helper()
|
||||
waitFor(t, 5*time.Second, "a mail saying "+want, func() bool {
|
||||
for _, m := range mail.Messages() {
|
||||
if strings.Contains(strings.Join(m.To, ","), to) && strings.Contains(m.Data, want) && strings.Contains(m.Data, regionName) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
// A monitor whose only region last reported ten minutes ago is not
|
||||
// up: nobody is checking it.
|
||||
_, mon := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "Shop", "type": "http", "target": "https://example.test", "interval_seconds": 60, "regions": []string{region}})
|
||||
id := mon["id"].(string)
|
||||
org := uuid.MustParse(owner.orgID())
|
||||
if err := e.asSystem(t, func(tx pgx.Tx) error {
|
||||
if _, err := tx.Exec(ctx, `UPDATE monitors SET created_at = now() - interval '1 hour' WHERE id = $1`, id); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.Exec(ctx, `INSERT INTO check_results (time, org_id, monitor_id, region, checker_id, ok, latency_ms) VALUES (now() - interval '10 minutes', $1, $2, $3, $4, true, 10)`,
|
||||
org, id, region, uuid.New())
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _, dash := owner.page("/")
|
||||
for _, want := range []string{"not being checked", "1 monitor is not being checked"} {
|
||||
if !strings.Contains(dash, want) {
|
||||
t.Errorf("dashboard lacks %q", want)
|
||||
}
|
||||
}
|
||||
if _, _, detail := owner.page("/monitors/" + id); !strings.Contains(detail, "no data since") || !strings.Contains(detail, "1 monitor is not being checked") {
|
||||
t.Error("the monitor page does not say the region has no recent data")
|
||||
}
|
||||
|
||||
// On a status page it shows as unknown, not as operational.
|
||||
slug := uniq("rw-")
|
||||
_, page := owner.do("POST", "/api/v1/org/statuspages", map[string]any{"slug": slug, "title": "Shop status"})
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string)+"/monitors", map[string]any{"monitors": []map[string]any{{"monitor_id": id}}})
|
||||
owner.do("PUT", "/api/v1/org/statuspages/"+page["id"].(string), map[string]any{"slug": slug, "title": "Shop status", "published": true})
|
||||
snap, err := e.statuspageClient(t, &org).Page(ctx, "", slug)
|
||||
if err != nil || len(snap.Sections) != 1 || snap.Sections[0].Components[0].Status != agentapi.PageUnknown {
|
||||
t.Errorf("status page = %+v, %v; want the component unknown", snap.Sections, err)
|
||||
}
|
||||
|
||||
// The region has a checker but no live instance: the watch notes it at
|
||||
// once and tells the owners once it has lasted.
|
||||
now := time.Now()
|
||||
if err := e.api.WatchRegionsOf(ctx, now, regionID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, dash := owner.page("/"); !strings.Contains(dash, "Region "+regionName+" has had no active checker since") {
|
||||
t.Error("the dashboard does not name the region without a checker")
|
||||
}
|
||||
if err := e.api.WatchRegionsOf(ctx, now.Add(5*time.Minute), regionID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mailed(ownerEmail, "has no active checker")
|
||||
sent := len(mail.Messages())
|
||||
if err := e.api.WatchRegionsOf(ctx, now.Add(10*time.Minute), regionID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
if n := countMails(mail.Messages()[sent:], regionName); n != 0 {
|
||||
t.Errorf("the region was announced %d more times", n)
|
||||
}
|
||||
|
||||
// A checker coming back is announced too.
|
||||
e.startChecker(t, tok)
|
||||
waitFor(t, 15*time.Second, "the checker to count as live", func() bool {
|
||||
_ = e.api.WatchRegionsOf(ctx, time.Now(), regionID)
|
||||
for _, m := range mail.Messages() {
|
||||
if strings.Contains(m.Data, "is checking again") && strings.Contains(m.Data, regionName) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
if _, _, dash := owner.page("/"); strings.Contains(dash, "Region "+regionName+" has had no active checker") {
|
||||
t.Error("the dashboard still names the region")
|
||||
}
|
||||
}
|
||||
|
||||
func countMails(ms []notifytest.Message, about string) int {
|
||||
n := 0
|
||||
for _, m := range ms {
|
||||
if strings.Contains(m.Data, about) {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -22,6 +22,8 @@ import (
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
|
||||
@@ -127,7 +129,18 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
|
||||
failing := map[uuid.UUID]int{}
|
||||
reported := map[uuid.UUID]int{}
|
||||
latestByMonitor := map[uuid.UUID][]store.LatestResultsRow{}
|
||||
// A region that has not reported for longer than the evaluator waits
|
||||
// is unknown, whatever its last result said.
|
||||
staleBefore := map[uuid.UUID]time.Time{}
|
||||
for _, m := range listed {
|
||||
if !check.Passive(check.Type(m.MonitorType)) {
|
||||
staleBefore[m.MonitorID] = now.Add(-evaluate.StaleAfter(time.Duration(m.IntervalSeconds) * time.Second))
|
||||
}
|
||||
}
|
||||
for _, l := range latest {
|
||||
if cut, ok := staleBefore[l.MonitorID]; ok && l.Time.Before(cut) {
|
||||
continue
|
||||
}
|
||||
reported[l.MonitorID]++
|
||||
if !l.Ok {
|
||||
failing[l.MonitorID]++
|
||||
|
||||
Reference in new issue
Block a user