feat: heartbeat monitors #75

Merged
Sebi merged 2 commits from feat/heartbeats into main 2026-11-22 11:11:58 +00:00
18 changed files with 1366 additions and 587 deletions

No files matched your search

+1
View File
@@ -89,6 +89,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
go srv.RunScheduler(ctx)
go srv.RunNotifier(ctx)
go srv.RunHousekeeping(ctx)
go srv.RunHeartbeats(ctx)
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
}
+35 -8
View File
@@ -18,6 +18,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/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/maintenance"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
@@ -80,10 +81,12 @@ func (s *Server) dashboard(c *gin.Context) {
}
type monitorData struct {
tree groupTree
maint map[uuid.UUID][]store.MaintenanceWindow
rows []web.MonitorRow
byID map[uuid.UUID]store.Monitor
// heartbeatLabel names the pseudo-region of heartbeat results.
heartbeatLabel string
tree groupTree
maint map[uuid.UUID][]store.MaintenanceWindow
rows []web.MonitorRow
byID map[uuid.UUID]store.Monitor
// buckets cover the selected range at its resolution.
buckets map[uuid.UUID][]web.Bucket
down map[uuid.UUID][]web.Span
@@ -178,6 +181,7 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
d := monitorData{
byID: map[uuid.UUID]store.Monitor{}, down: map[uuid.UUID][]web.Span{},
regionOf: map[uuid.UUID]store.Region{}, rng: rng, now: now,
heartbeatLabel: i18n.T(ctx, "monitors.type_heartbeat"),
}
var (
monitors []store.Monitor
@@ -259,14 +263,19 @@ func (s *Server) loadMonitorData(ctx context.Context, p *principal, rng web.Time
}
d.byID[m.ID] = m
row := web.MonitorRow{ID: m.ID.String(), Name: m.Name, Type: m.Type, Target: m.Target, Latency: "–", Uptime: "–"}
keys := idStrings(regionsOf[m.ID])
if check.Passive(check.Type(m.Type)) {
// The target of a heartbeat is its secret ping token.
row.Target, keys = "", []string{heartbeatRegion}
}
if m.GroupID != nil {
row.GroupID = m.GroupID.String()
}
var latencies []int32
failing, reported := 0, 0
for _, rid := range regionsOf[m.ID] {
rs := web.RegionStatus{Name: d.regionName(rid), Status: web.StatusUnknown, Detail: "–"}
if l, ok := latestOf[m.ID][rid.String()]; ok {
for _, key := range keys {
rs := web.RegionStatus{Name: d.regionNameString(key), Status: web.StatusUnknown, Detail: "–"}
if l, ok := latestOf[m.ID][key]; ok {
reported++
rs.Detail = l.Time.Format("15:04:05")
if l.Ok {
@@ -337,6 +346,7 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
}
v := web.MonitorDetailView{
Interval: (time.Duration(m.IntervalSeconds) * time.Second).String(),
PingURL: s.detailPingURL(p, d, m),
CanWrite: canInGroup(p, authz.MonitorsWrite, d.tree, m.GroupID),
Latency: web.Latency(d.buckets[id], d.now.Add(-d.rng.Window).Truncate(d.rng.Bucket), d.now, 480, 96),
Maintenance: maintenanceItems(d.maint[id], d.now),
@@ -406,6 +416,9 @@ func (s *Server) monitorDetail(c *gin.Context, p *principal, page web.Page, me w
}
func (d monitorData) regionNameString(id string) string {
if id == heartbeatRegion {
return d.heartbeatLabel
}
if u, err := uuid.Parse(id); err == nil {
return d.regionName(u)
}
@@ -461,7 +474,7 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
ctx := c.Request.Context()
f := web.MonitorForm{
Type: "http", IntervalSeconds: 60, TimeoutMS: 10000, Confirmations: 2, Enabled: true,
MinInterval: s.minInterval(), Method: "GET", ExpectStatus: "2xx, 3xx",
MinInterval: s.minInterval(), Method: "GET", ExpectStatus: "2xx, 3xx", GraceSeconds: check.DefaultHeartbeatGrace,
FollowRedirects: true, VerifyTLS: true, DNSRecord: "A", TLSMinDays: 14,
}
var (
@@ -541,6 +554,11 @@ func fillForm(f *web.MonitorForm, m store.Monitor) {
var c check.TLSConfig
_ = json.Unmarshal(m.Config, &c)
f.TLSMinDays, f.TLSServerName = c.MinDaysValid, c.ServerName
case check.Heartbeat:
var c check.HeartbeatConfig
_ = json.Unmarshal(m.Config, &c)
f.GraceSeconds = c.GraceSeconds
f.Target = ""
}
}
@@ -860,3 +878,12 @@ func maintenanceItems(ws []store.MaintenanceWindow, now time.Time) []web.Mainten
}
return out
}
// detailPingURL shows the ping URL of a heartbeat monitor to those who may
// change the monitor; anyone holding it can report the job healthy.
func (s *Server) detailPingURL(p *principal, d monitorData, m store.Monitor) string {
if !check.Passive(check.Type(m.Type)) || !canInGroup(p, authz.MonitorsWrite, d.tree, m.GroupID) {
return ""
}
return s.pingURL(m.Target)
}
+151
View File
@@ -0,0 +1,151 @@
package api
import (
"context"
"errors"
"io"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"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/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// heartbeatRegion is the region heartbeat results are filed under: pings
// arrive from wherever the job runs, not from a checker region.
const heartbeatRegion = "heartbeat"
// newPingToken returns the secret that makes up a ping URL.
func newPingToken() string { return auth.RandomToken() }
func (s *Server) pingURL(token string) string {
return strings.TrimSuffix(s.cfg.PublicURL, "/") + "/hb/" + token
}
func (s *Server) mountHeartbeats(r gin.IRouter) {
methods := []string{http.MethodGet, http.MethodHead, http.MethodPost}
r.Match(methods, "/hb/:token", s.ping)
r.Match(methods, "/hb/:token/fail", s.ping)
}
// ping records a heartbeat. Jobs call it with curl or wget, so it takes
// GET, HEAD and POST, needs no headers and answers in plain text. A path
// ending in /fail reports a failure; a message may come as ?msg= or as the
// POST body.
func (s *Server) ping(c *gin.Context) {
token := c.Param("token")
ctx := c.Request.Context()
if !s.limit(c, "ping:"+token, 60, time.Minute) {
return
}
var m store.HeartbeatMonitorRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
m, err = q.HeartbeatMonitor(ctx, token)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
c.String(http.StatusNotFound, "unknown heartbeat\n")
return
}
if err != nil {
internalError(c, err)
return
}
if !m.Enabled {
c.String(http.StatusOK, "OK (paused)\n")
return
}
ok := !strings.HasSuffix(c.FullPath(), "/fail")
msg := c.Query("msg")
if msg == "" && c.Request.Method == http.MethodPost {
body, _ := io.ReadAll(io.LimitReader(c.Request.Body, 2000))
msg = strings.TrimSpace(string(body))
}
if !ok && msg == "" {
msg = "reported failure"
}
if err := s.recordHeartbeat(ctx, m.ID, m.OrgID, m.IntervalSeconds, m.Confirmations, ok, msg, time.Now()); err != nil {
internalError(c, err)
return
}
c.String(http.StatusOK, "OK\n")
}
// recordHeartbeat stores a ping or a missed deadline and evaluates it like
// a checker result.
func (s *Server) recordHeartbeat(ctx context.Context, id, org uuid.UUID, interval, confirmations int32, ok bool, msg string, at time.Time) error {
row := store.InsertCheckResultsParams{Time: at, OrgID: org, MonitorID: id, Region: heartbeatRegion, Ok: ok}
if msg != "" {
row.Error = ptr(truncateValid(msg, 500))
}
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
_, err := q.InsertCheckResults(ctx, []store.InsertCheckResultsParams{row})
return err
})
if err != nil {
return err
}
s.evaluateResults(ctx, heartbeatRegion,
[]agentapi.Result{{MonitorID: id, ScheduledAt: at, StartedAt: at, OK: ok}},
map[uuid.UUID]store.MonitorsForResultsRow{id: {
ID: id, OrgID: org, IntervalSeconds: interval, Confirmations: confirmations, Regions: []string{heartbeatRegion},
}})
return nil
}
// missedPing is the error recorded for an overdue heartbeat.
const missedPing = "no ping received in time"
// RunHeartbeats records a failure for every heartbeat monitor whose ping is
// overdue, until ctx ends. Every replica runs it; a short Redis lock lets
// one of them do each round.
func (s *Server) RunHeartbeats(ctx context.Context) {
tick := time.NewTicker(10 * time.Second)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
}
got, err := s.rdb.SetNX(ctx, "lock:heartbeats", 1, 9*time.Second).Result()
if err != nil || !got {
continue
}
if err := s.CheckHeartbeats(ctx, time.Now()); err != nil && ctx.Err() == nil {
s.log.ErrorContext(ctx, "checking heartbeats failed", "error", err)
}
}
}
// CheckHeartbeats records missed deadlines as of now. A recorded failure
// restarts the wait, so a silent job fails once per interval plus grace.
func (s *Server) CheckHeartbeats(ctx context.Context, now time.Time) error {
var due []store.HeartbeatsDueRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
due, err = q.HeartbeatsDue(ctx)
return err
})
if err != nil {
return err
}
for _, m := range due {
deadline := m.WaitingSince.Add(time.Duration(m.IntervalSeconds+m.GraceSeconds) * time.Second)
if now.Before(deadline) {
continue
}
if err := s.recordHeartbeat(ctx, m.ID, m.OrgID, m.IntervalSeconds+m.GraceSeconds, m.Confirmations, false, missedPing, now); err != nil {
return err
}
}
return nil
}
+153
View File
@@ -0,0 +1,153 @@
package api_test
import (
"context"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
)
func TestHeartbeatMonitor(t *testing.T) {
e := newEnv(t)
owner := e.browser(t)
owner.signup("o@"+uniq("hb")+".test", uniq("hb-"))
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "Nightly backup", "type": "heartbeat", "interval_seconds": 3600, "config": map[string]any{"grace_seconds": 300},
})
if st != http.StatusCreated {
t.Fatalf("create heartbeat = %d %v", st, body)
}
id := body["id"].(string)
pingURL, _ := body["ping_url"].(string)
token := body["target"].(string)
if !strings.HasSuffix(pingURL, "/hb/"+token) || len(token) < 40 {
t.Fatalf("ping_url = %q, target = %q", pingURL, token)
}
path := "/hb/" + token
ping := func(method, suffix, payload string) (int, string) {
t.Helper()
req, _ := http.NewRequest(method, e.srv.URL+path+suffix, strings.NewReader(payload))
resp, err := e.srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
defer func() { _ = resp.Body.Close() }()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, string(b)
}
incidents := func() []any {
_, b := owner.do("GET", "/api/v1/org/incidents", nil)
return b["incidents"].([]any)
}
open := func() bool {
for _, i := range incidents() {
if i.(map[string]any)["resolved_at"] == nil {
return true
}
}
return false
}
if st, _ := ping("GET", "x", ""); st != http.StatusNotFound {
t.Errorf("unknown token = %d, want 404", st)
}
// Silence past interval plus grace is an outage.
ctx := context.Background()
waitingFor := func(d time.Duration) {
t.Helper()
err := e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `UPDATE monitors SET updated_at = now() - $2::interval WHERE id = $1`, id, d)
return err
})
if err != nil {
t.Fatal(err)
}
}
waitingFor(50 * time.Minute)
if err := e.api.CheckHeartbeats(ctx, time.Now()); err != nil {
t.Fatal(err)
}
if open() {
t.Fatal("incident before the deadline")
}
waitingFor(66 * time.Minute)
if err := e.api.CheckHeartbeats(ctx, time.Now()); err != nil {
t.Fatal(err)
}
if !open() {
t.Fatal("no incident after a missed ping")
}
// A failure restarts the wait instead of piling up.
if err := e.api.CheckHeartbeats(ctx, time.Now()); err != nil {
t.Fatal(err)
}
if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1 AND NOT ok`, id); n != 1 {
t.Errorf("failures recorded = %d, want 1", n)
}
// The next ping resolves it.
if st, out := ping("HEAD", "", ""); st != http.StatusOK {
t.Fatalf("ping = %d %q", st, out)
}
if open() {
t.Fatal("ping did not resolve the incident")
}
// A reported failure is an outage at once, with its message.
if st, _ := ping("POST", "/fail", "disk full"); st != http.StatusOK {
t.Fatalf("fail ping = %d", st)
}
if !open() {
t.Fatal("reported failure opened no incident")
}
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
if !strings.Contains(mustJSON(list), "disk full") {
t.Error("failure message is not stored")
}
ping("POST", "", "")
// Editing keeps the URL; readers never see it.
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, map[string]any{
"name": "Nightly backup", "type": "heartbeat", "interval_seconds": 7200,
})
if st != http.StatusOK || body["target"] != token {
t.Errorf("edit = %d, target %v, want unchanged", st, body["target"])
}
viewer := e.joinVia(t, owner.invite("v@"+uniq("hb")+".test", owner.roleID("viewer")))
_, vl := viewer.do("GET", "/api/v1/org/monitors", nil)
if strings.Contains(mustJSON(vl), token) {
t.Error("a viewer sees the ping token")
}
for _, b := range []*browser{owner, viewer} {
_, _, html := b.page("/")
if strings.Contains(html, token) {
t.Error("the dashboard shows the ping token")
}
}
if _, _, html := owner.page("/monitors/" + id); !strings.Contains(html, pingURL) {
t.Error("the monitor page does not show the ping URL to its editor")
}
if _, _, html := viewer.page("/monitors/" + id); strings.Contains(html, token) {
t.Error("the monitor page shows the ping URL to a viewer")
}
// Other monitor types still need a target and regions.
st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "x", "type": "tcp", "target": "example.com:443", "interval_seconds": 60})
expect(t, "tcp without regions", st, body, http.StatusUnprocessableEntity, "invalid_region")
// Paused heartbeats accept pings but never fail.
owner.do("PUT", "/api/v1/org/monitors/"+id, map[string]any{"name": "Nightly backup", "type": "heartbeat", "interval_seconds": 7200, "enabled": false})
before := len(incidents())
if st, out := ping("GET", "", ""); st != http.StatusOK || !strings.Contains(out, "paused") {
t.Errorf("ping while paused = %d %q", st, out)
}
if err := e.api.CheckHeartbeats(ctx, time.Now().Add(48*time.Hour)); err != nil {
t.Fatal(err)
}
if len(incidents()) != before {
t.Error("a paused heartbeat failed")
}
}
+48 -6
View File
@@ -21,14 +21,16 @@ import (
)
type monitorRequest struct {
Name string `json:"name" binding:"required,max=200"`
Type string `json:"type" binding:"required"`
Target string `json:"target" binding:"required,max=2000"`
Name string `json:"name" binding:"required,max=200"`
Type string `json:"type" binding:"required"`
// Target is ignored for heartbeat monitors, whose target is their
// generated ping token.
Target string `json:"target" binding:"max=2000"`
IntervalSeconds int `json:"interval_seconds" binding:"required"`
TimeoutMS int `json:"timeout_ms"`
Config json.RawMessage `json:"config"`
Enabled *bool `json:"enabled"`
Regions []uuid.UUID `json:"regions" binding:"required,min=1,max=50"`
Regions []uuid.UUID `json:"regions" binding:"max=50"`
// Confirmations is how many failures in a row make a region count as
// down; 0 keeps the default of 2.
Confirmations int `json:"confirmations" binding:"min=0,max=10"`
@@ -58,6 +60,16 @@ type monitorView struct {
GroupID *uuid.UUID `json:"group_id"`
Regions []uuid.UUID `json:"regions"`
Latest []latestView `json:"latest"`
// PingURL is where heartbeat monitors are pinged.
PingURL string `json:"ping_url,omitempty"`
}
// withPingURL adds the ping URL of heartbeat monitors.
func (s *Server) withPingURL(v monitorView) monitorView {
if check.Passive(check.Type(v.Type)) && v.Target != "" {
v.PingURL = s.pingURL(v.Target)
}
return v
}
func viewMonitor(m store.Monitor, regions []uuid.UUID) monitorView {
@@ -99,6 +111,21 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest, t groupTre
fail(c, http.StatusUnprocessableEntity, "invalid_interval", "Min", s.minInterval())
return false
}
heartbeat := check.Passive(check.Type(req.Type))
if heartbeat {
// Pings arrive from one place, so one late ping is an outage, and
// there is neither a target nor a timeout to check against.
req.Target, req.Regions = "", nil
if req.Confirmations == 0 {
req.Confirmations = 1
}
if req.TimeoutMS == 0 {
req.TimeoutMS = 1000
}
} else if len(req.Regions) == 0 {
fail(c, http.StatusUnprocessableEntity, "invalid_region")
return false
}
if req.Confirmations == 0 {
req.Confirmations = 2
}
@@ -183,6 +210,11 @@ func (s *Server) listMonitors(c *gin.Context) {
continue
}
v := viewMonitor(m, byMonitor[m.ID])
if check.Passive(check.Type(m.Type)) && !canInGroup(p, authz.MonitorsWrite, t, m.GroupID) {
// Whoever knows the ping URL can report the job healthy.
v.Target = ""
}
v = s.withPingURL(v)
if l := latestBy[m.ID]; l != nil {
v.Latest = l
}
@@ -212,6 +244,9 @@ func (s *Server) createMonitor(c *gin.Context) {
if !s.validateMonitor(c, &req, t) {
return
}
if check.Passive(check.Type(req.Type)) {
req.Target = newPingToken()
}
var m store.Monitor
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
@@ -234,7 +269,7 @@ func (s *Server) createMonitor(c *gin.Context) {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, viewMonitor(m, req.Regions))
c.JSON(http.StatusCreated, s.withPingURL(viewMonitor(m, req.Regions)))
}
func setRegions(ctx context.Context, q *store.Queries, m store.Monitor, regions []uuid.UUID) error {
@@ -306,6 +341,13 @@ func (s *Server) updateMonitor(c *gin.Context) {
if previous, err = q.MonitorRegions(ctx, id); err != nil {
return err
}
if check.Passive(check.Type(req.Type)) {
// The ping URL stays the same across edits.
req.Target = old.Target
if old.Type != req.Type {
req.Target = newPingToken()
}
}
m, err = q.UpdateMonitor(ctx, store.UpdateMonitorParams{
ID: id, Name: req.Name, Type: req.Type, Target: req.Target,
IntervalSeconds: int32(req.IntervalSeconds), TimeoutMs: int32(req.TimeoutMS),
@@ -329,7 +371,7 @@ func (s *Server) updateMonitor(c *gin.Context) {
internalError(c, err)
return
}
c.JSON(http.StatusOK, viewMonitor(m, req.Regions))
c.JSON(http.StatusOK, s.withPingURL(viewMonitor(m, req.Regions)))
}
func (s *Server) deleteMonitor(c *gin.Context) {
+1
View File
@@ -84,6 +84,7 @@ func (s *Server) Mount(r gin.IRouter) {
// Agents authenticate with tokens and never carry cookies, so they skip
// the session and CSRF middleware.
s.mountAgentAPI(r)
s.mountHeartbeats(r)
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit())
+9 -1
View File
@@ -22,10 +22,16 @@ const (
ICMP Type = "icmp"
DNS Type = "dns"
TLS Type = "tls"
// Heartbeat monitors are pinged by the monitored job; no checker runs
// them.
Heartbeat Type = "heartbeat"
)
// Types lists every check type.
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS}
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, Heartbeat}
// Passive reports whether t is reported to us rather than run by checkers.
func Passive(t Type) bool { return t == Heartbeat }
// Spec is everything needed to run one check.
type Spec struct {
@@ -77,6 +83,8 @@ var impls = map[Type]impl{
ICMP: icmpCheck{},
DNS: dnsCheck{},
TLS: tlsCheck{},
Heartbeat: heartbeatCheck{},
}
// Validate checks target and config for type t and returns the normalized
+36
View File
@@ -0,0 +1,36 @@
package check
import (
"context"
"encoding/json"
)
// HeartbeatConfig configures a heartbeat monitor.
type HeartbeatConfig struct {
// GraceSeconds is how late a ping may be before the monitor counts as
// failed, to absorb jobs that run a little longer than usual.
GraceSeconds int `json:"grace_seconds"`
}
// DefaultHeartbeatGrace applies when no grace period is set.
const DefaultHeartbeatGrace = 60
type heartbeatCheck struct{}
func (heartbeatCheck) validate(_ string, config json.RawMessage) (json.RawMessage, error) {
c, err := decode[HeartbeatConfig](config)
if err != nil {
return nil, err
}
if c.GraceSeconds == 0 {
c.GraceSeconds = DefaultHeartbeatGrace
}
if c.GraceSeconds < 0 || c.GraceSeconds > 86400 {
return nil, invalid("invalid_grace")
}
return encode(c), nil
}
func (heartbeatCheck) run(context.Context, Spec) Outcome {
return Outcome{Error: "heartbeat monitors are not run by checkers"}
}
+1 -1
View File
@@ -151,7 +151,7 @@ func TestDynamicFamilies(t *testing.T) {
en := catalogKeys(t)["en"]
families := map[string][]string{
"status.": {"up", "degraded", "down", "unknown", "paused", "maintenance"},
"monitors.type_": {"http", "tcp", "tls", "dns", "icmp"},
"monitors.type_": {"http", "tcp", "tls", "dns", "icmp", "heartbeat"},
"channels.type_": {"webhook", "email"},
"agents.kind_": {"checker", "statuspage"},
"page.status.": {"operational", "degraded", "outage", "unknown", "maintenance"},
+8
View File
@@ -152,6 +152,7 @@
"error.invalid_domain": "Eine der Domains ist ungültig.",
"error.invalid_email": "Bitte eine gültige E-Mail-Adresse eingeben.",
"error.invalid_expect_status": "Erwartete Statuscodes müssen Codes wie 200 oder Klassen wie 2xx sein.",
"error.invalid_grace": "Die Toleranz muss zwischen 0 Sekunden und einem Tag liegen.",
"error.invalid_group": "Unbekannte Gruppe.",
"error.invalid_header": "Ein Request-Header ist ungültig.",
"error.invalid_input": "Eingaben prüfen.",
@@ -440,6 +441,9 @@
"monitors.edit": "Monitor bearbeiten",
"monitors.expect_status": "Erwarteter Status (z. B. 2xx, 301)",
"monitors.follow_redirects": "Weiterleitungen folgen",
"monitors.grace": "Toleranz (Sekunden)",
"monitors.grace_hint": "Wie spät ein Ping sein darf, für Jobs, die manchmal länger laufen.",
"monitors.heartbeat_hint": "Dein Job ruft bei jedem Lauf eine geheime URL auf. Kommt innerhalb von Intervall plus Toleranz kein Aufruf, gilt der Monitor als ausgefallen. Die URL wird nach dem Speichern angezeigt.",
"monitors.history": "Verlauf, letzte {{.Range}}",
"monitors.interval": "Intervall (Sekunden)",
"monitors.interval_hint": "Mindestens {{.Min}} Sekunden.",
@@ -449,6 +453,9 @@
"monitors.latency": "Durchschnittliche Latenz",
"monitors.method": "Methode",
"monitors.new": "Neuer Monitor",
"monitors.ping_intro": "Rufe diese URL am Ende jedes erfolgreichen Laufs auf, per GET, HEAD oder POST. Mit angehängtem /fail meldest du einen Fehler; ein POST-Body oder ?msg= wird als Meldung gespeichert.",
"monitors.ping_secret": "Halte die URL geheim: Wer sie kennt, kann den Job als gesund melden. Nur Mitglieder, die diesen Monitor bearbeiten dürfen, sehen sie.",
"monitors.ping_url": "Ping-URL",
"monitors.range": "Zeitraum",
"monitors.range_not_enough": "Für weniger als die Hälfte dieses Zeitraums liegen bisher Daten vor.",
"monitors.range_note": "SLA und Balken: letzte {{.Range}}",
@@ -464,6 +471,7 @@
"monitors.tls_server_name": "Servername (optional)",
"monitors.type": "Check-Typ",
"monitors.type_dns": "DNS",
"monitors.type_heartbeat": "Heartbeat",
"monitors.type_http": "HTTP(S)",
"monitors.type_icmp": "Ping (ICMP)",
"monitors.type_tcp": "TCP-Port",
+8
View File
@@ -152,6 +152,7 @@
"error.invalid_domain": "One of the domains is not valid.",
"error.invalid_email": "Please enter a valid email address.",
"error.invalid_expect_status": "Expected status codes must be codes like 200 or classes like 2xx.",
"error.invalid_grace": "The grace period must be between 0 seconds and one day.",
"error.invalid_group": "Unknown group.",
"error.invalid_header": "A request header is not valid.",
"error.invalid_input": "Please check your input.",
@@ -440,6 +441,9 @@
"monitors.edit": "Edit monitor",
"monitors.expect_status": "Expected status (e.g. 2xx, 301)",
"monitors.follow_redirects": "Follow redirects",
"monitors.grace": "Grace period (seconds)",
"monitors.grace_hint": "How late a ping may be, for jobs that sometimes run longer.",
"monitors.heartbeat_hint": "Your job calls a secret URL each time it runs. If no call arrives within the interval plus the grace period, the monitor is down. The URL is shown after saving.",
"monitors.history": "History, last {{.Range}}",
"monitors.interval": "Interval (seconds)",
"monitors.interval_hint": "At least {{.Min}} seconds.",
@@ -449,6 +453,9 @@
"monitors.latency": "Average latency",
"monitors.method": "Method",
"monitors.new": "New monitor",
"monitors.ping_intro": "Call this URL at the end of every successful run, with GET, HEAD or POST. Append /fail to report a failure; a POST body or ?msg= is stored as the message.",
"monitors.ping_secret": "Keep the URL secret: anyone who knows it can report the job as healthy. Only members who may edit this monitor see it.",
"monitors.ping_url": "Ping URL",
"monitors.range": "Time range",
"monitors.range_not_enough": "Less than half of this period is covered by data yet.",
"monitors.range_note": "SLA and bars: last {{.Range}}",
@@ -464,6 +471,7 @@
"monitors.tls_server_name": "Server name (optional)",
"monitors.type": "Check type",
"monitors.type_dns": "DNS",
"monitors.type_heartbeat": "Heartbeat",
"monitors.type_http": "HTTP(S)",
"monitors.type_icmp": "Ping (ICMP)",
"monitors.type_tcp": "TCP port",
@@ -0,0 +1,13 @@
-- +goose Up
-- Heartbeat monitors are pinged by the monitored job instead of being
-- checked. Their target is the secret token of the ping URL.
ALTER TABLE monitors DROP CONSTRAINT monitors_type_check;
ALTER TABLE monitors ADD CONSTRAINT monitors_type_check
CHECK (type IN ('http', 'tcp', 'icmp', 'dns', 'tls', 'heartbeat'));
CREATE UNIQUE INDEX monitors_heartbeat_token_idx ON monitors (target) WHERE type = 'heartbeat';
-- +goose Down
DROP INDEX monitors_heartbeat_token_idx;
DELETE FROM monitors WHERE type = 'heartbeat';
ALTER TABLE monitors DROP CONSTRAINT monitors_type_check;
ALTER TABLE monitors ADD CONSTRAINT monitors_type_check CHECK (type IN ('http', 'tcp', 'icmp', 'dns', 'tls'));
+89
View File
@@ -0,0 +1,89 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: heartbeats.sql
package store
import (
"context"
"time"
"github.com/google/uuid"
)
const heartbeatMonitor = `-- name: HeartbeatMonitor :one
SELECT id, org_id, interval_seconds, confirmations, enabled
FROM monitors WHERE type = 'heartbeat' AND target = $1
`
type HeartbeatMonitorRow struct {
ID uuid.UUID
OrgID uuid.UUID
IntervalSeconds int32
Confirmations int32
Enabled bool
}
// System scope: the monitor a ping token belongs to.
func (q *Queries) HeartbeatMonitor(ctx context.Context, target string) (HeartbeatMonitorRow, error) {
row := q.db.QueryRow(ctx, heartbeatMonitor, target)
var i HeartbeatMonitorRow
err := row.Scan(
&i.ID,
&i.OrgID,
&i.IntervalSeconds,
&i.Confirmations,
&i.Enabled,
)
return i, err
}
const heartbeatsDue = `-- name: HeartbeatsDue :many
SELECT m.id, m.org_id, m.interval_seconds, m.confirmations,
coalesce((m.config->>'grace_seconds')::integer, 0)::integer AS grace_seconds,
greatest(m.updated_at, coalesce((SELECT max(r.time) FROM check_results r
WHERE r.org_id = m.org_id AND r.monitor_id = m.id AND r.time > now() - interval '3 days'), m.updated_at))::timestamptz AS waiting_since
FROM monitors m
WHERE m.type = 'heartbeat' AND m.enabled
`
type HeartbeatsDueRow struct {
ID uuid.UUID
OrgID uuid.UUID
IntervalSeconds int32
Confirmations int32
GraceSeconds int32
WaitingSince time.Time
}
// System scope: enabled heartbeat monitors with their grace period and
// since when they are being waited for: the latest result, or the last
// change of the monitor, which covers new and re-enabled ones. The result
// lookup is bounded because the longest interval plus grace is two days.
func (q *Queries) HeartbeatsDue(ctx context.Context) ([]HeartbeatsDueRow, error) {
rows, err := q.db.Query(ctx, heartbeatsDue)
if err != nil {
return nil, err
}
defer rows.Close()
items := []HeartbeatsDueRow{}
for rows.Next() {
var i HeartbeatsDueRow
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.IntervalSeconds,
&i.Confirmations,
&i.GraceSeconds,
&i.WaitingSince,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
+7
View File
@@ -103,6 +103,13 @@ type Querier interface {
GetStatusPage(ctx context.Context, id uuid.UUID) (StatusPage, error)
GetUser(ctx context.Context, id uuid.UUID) (User, error)
GetUserByEmail(ctx context.Context, email string) (User, error)
// System scope: the monitor a ping token belongs to.
HeartbeatMonitor(ctx context.Context, target string) (HeartbeatMonitorRow, error)
// System scope: enabled heartbeat monitors with their grace period and
// since when they are being waited for: the latest result, or the last
// change of the monitor, which covers new and re-enabled ones. The result
// lookup is bounded because the longest interval plus grace is two days.
HeartbeatsDue(ctx context.Context) ([]HeartbeatsDueRow, error)
// Per monitor and hour since $2, across all regions.
HourlyBuckets(ctx context.Context, arg HourlyBucketsParams) ([]HourlyBucketsRow, error)
IncidentsForMonitors(ctx context.Context, arg IncidentsForMonitorsParams) ([]Incident, error)
+16
View File
@@ -0,0 +1,16 @@
-- name: HeartbeatMonitor :one
-- System scope: the monitor a ping token belongs to.
SELECT id, org_id, interval_seconds, confirmations, enabled
FROM monitors WHERE type = 'heartbeat' AND target = $1;
-- name: HeartbeatsDue :many
-- System scope: enabled heartbeat monitors with their grace period and
-- since when they are being waited for: the latest result, or the last
-- change of the monitor, which covers new and re-enabled ones. The result
-- lookup is bounded because the longest interval plus grace is two days.
SELECT m.id, m.org_id, m.interval_seconds, m.confirmations,
coalesce((m.config->>'grace_seconds')::integer, 0)::integer AS grace_seconds,
greatest(m.updated_at, coalesce((SELECT max(r.time) FROM check_results r
WHERE r.org_id = m.org_id AND r.monitor_id = m.id AND r.time > now() - interval '3 days'), m.updated_at))::timestamptz AS waiting_since
FROM monitors m
WHERE m.type = 'heartbeat' AND m.enabled;
+11
View File
@@ -179,6 +179,17 @@
fs.hidden = !active;
fs.disabled = !active;
}
// [data-hide-for] holds fields a type does without, e.g. heartbeats
// have neither target nor regions.
for (const el of sel.form.querySelectorAll("[data-hide-for]")) {
const hide = el.dataset.hideFor.split(" ").includes(sel.value);
el.hidden = hide;
if (el.tagName === "FIELDSET") el.disabled = hide;
for (const input of el.querySelectorAll("input[required], input[data-required]")) {
input.required = !hide;
input.dataset.required = "";
}
}
});
document.addEventListener("change", async (ev) => {
+35 -6
View File
@@ -246,6 +246,8 @@ type MonitorDetailView struct {
CanWrite bool
// Maintenance lists current and upcoming maintenance.
Maintenance []MaintenanceItem
// PingURL is set for heartbeat monitors the viewer may change.
PingURL string
}
// MaintenanceItem is one occurrence of planned maintenance.
@@ -265,7 +267,13 @@ templ MonitorDetail(p Page, me Me, v MonitorDetailView) {
@statusDot(v.Row.Status)
<span>{ v.Row.Name }</span>
</h1>
<p class="mt-1 font-mono text-xs text-muted">{ v.Row.Type } · { v.Row.Target } · { v.Interval }</p>
<p class="mt-1 font-mono text-xs text-muted">
{ i18n.T(ctx, "monitors.type_"+v.Row.Type) }
if v.Row.Target != "" {
{ " · " + v.Row.Target }
}
{ " · " + v.Interval }
</p>
</div>
if v.CanWrite {
<a href={ templ.SafeURL("/monitors/" + v.Row.ID + "/edit") } class="border border-ink px-3 py-1.5 text-sm hover:bg-ink hover:text-paper">{ i18n.T(ctx, "sso.action.edit") }</a>
@@ -306,6 +314,9 @@ templ MonitorDetail(p Page, me Me, v MonitorDetailView) {
<p class="mt-2 text-xs text-muted">{ i18n.T(ctx, "monitors.by_region_hint") }</p>
</section>
}
if v.PingURL != "" {
@pingSection(v.PingURL)
}
if len(v.Maintenance) > 0 {
<section class="mb-10">
@sectionHeading("maintenance.title")
@@ -447,6 +458,7 @@ type MonitorForm struct {
DNSExpect string
TLSMinDays int
TLSServerName string
GraceSeconds int
}
templ typeFields(typ, current string) {
@@ -504,13 +516,19 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {
<label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.type") }</span>
<select name="type" data-type-select class="w-full border border-rule bg-transparent px-2 py-1.5 text-sm">
for _, t := range []string{"http", "tcp", "tls", "dns", "icmp"} {
for _, t := range []string{"http", "tcp", "tls", "dns", "icmp", "heartbeat"} {
<option value={ t } selected?={ t == f.Type }>{ i18n.T(ctx, "monitors.type_"+t) }</option>
}
</select>
</label>
@valueField(i18n.T(ctx, "monitors.target"), "target", f.Target, "https://example.com", true)
<p class="-mt-3 mb-4 text-xs text-muted">{ i18n.T(ctx, "monitors.target_hint") }</p>
<div data-hide-for="heartbeat" hidden?={ f.Type == "heartbeat" }>
@valueField(i18n.T(ctx, "monitors.target"), "target", f.Target, "https://example.com", f.Type != "heartbeat")
<p class="-mt-3 mb-4 text-xs text-muted">{ i18n.T(ctx, "monitors.target_hint") }</p>
</div>
@typeFields("heartbeat", f.Type) {
<p class="mb-4 text-xs text-muted">{ i18n.T(ctx, "monitors.heartbeat_hint") }</p>
@numberField(i18n.T(ctx, "monitors.grace"), "config.grace_seconds", f.GraceSeconds, 0, 86400, i18n.T(ctx, "monitors.grace_hint"))
}
@typeFields("http", f.Type) {
<label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.method") }</span>
@@ -547,9 +565,11 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {
</div>
<div>
@numberField(i18n.T(ctx, "monitors.interval"), "interval_seconds", f.IntervalSeconds, f.MinInterval, 86400, i18n.T(ctx, "monitors.interval_hint", "Min", f.MinInterval))
@numberField(i18n.T(ctx, "monitors.timeout"), "timeout_ms", f.TimeoutMS, 100, 60000, "")
<div data-hide-for="heartbeat" hidden?={ f.Type == "heartbeat" }>
@numberField(i18n.T(ctx, "monitors.timeout"), "timeout_ms", f.TimeoutMS, 100, 60000, "")
</div>
@numberField(i18n.T(ctx, "monitors.confirmations"), "confirmations", f.Confirmations, 1, 10, i18n.T(ctx, "monitors.confirmations_hint"))
<fieldset class="mb-4">
<fieldset class="mb-4" data-hide-for="heartbeat" hidden?={ f.Type == "heartbeat" } disabled?={ f.Type == "heartbeat" }>
<legend class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.regions") }</legend>
<p class="mb-2 text-xs text-muted">{ i18n.T(ctx, "monitors.regions_hint") }</p>
for _, r := range f.Regions {
@@ -753,3 +773,12 @@ func partialTitle(ctx context.Context, partial bool) string {
}
return i18n.T(ctx, "monitors.range_not_enough")
}
templ pingSection(url string) {
<section class="mb-10">
@sectionHeading("monitors.ping_url")
<p class="mb-3 max-w-2xl text-sm text-muted">{ i18n.T(ctx, "monitors.ping_intro") }</p>
<pre class="overflow-x-auto border border-rule px-3 py-2 font-mono text-xs leading-relaxed">{ "curl -fsS -m 10 --retry 3 " + url + "\n" }{ "curl -fsS -m 10 --retry 3 --data-raw \"$output\" " + url + "/fail" }</pre>
<p class="mt-2 max-w-2xl text-xs text-muted">{ i18n.T(ctx, "monitors.ping_secret") }</p>
</section>
}
File diff suppressed because it is too large. Load diff