Monitors and groups get one-off or recurring maintenance. While it is in progress, failures neither open incidents nor alert, so the SLA is not affected; successes still resolve earlier incidents. The console shows monitors under maintenance and lists windows on a new page and on monitor pages. Status pages announce maintenance in progress and planned for the next two weeks and mark affected components; the occurrences are part of the snapshot and evaluated when the page is shown, so this also works from cache during an API outage. Maintenance and status page descriptions are rendered as Markdown. Closes #71 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
245 lines
7.5 KiB
Go
245 lines
7.5 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"slices"
|
|
"strings"
|
|
"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/evaluate"
|
|
"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"
|
|
)
|
|
|
|
const (
|
|
maxNotifyAttempts = 10
|
|
notifyBatch = 20
|
|
)
|
|
|
|
// evaluateResults feeds stored results to the evaluator in time order and
|
|
// acts on the resulting transitions.
|
|
func (s *Server) evaluateResults(ctx context.Context, region string, results []agentapi.Result, monitors map[uuid.UUID]store.MonitorsForResultsRow) {
|
|
slices.SortFunc(results, func(a, b agentapi.Result) int { return a.StartedAt.Compare(b.StartedAt) })
|
|
ids := make([]uuid.UUID, 0, len(monitors))
|
|
for id := range monitors {
|
|
ids = append(ids, id)
|
|
}
|
|
planned := s.monitorsInMaintenance(ctx, ids)
|
|
for _, r := range results {
|
|
m, ok := monitors[r.MonitorID]
|
|
if !ok {
|
|
continue
|
|
}
|
|
// Failures during planned maintenance are expected: they neither
|
|
// open incidents nor count towards one afterwards. Successes still
|
|
// go through, so an incident from before can resolve.
|
|
if _, _, active := inMaintenance(planned[m.ID], r.StartedAt); active && !r.OK {
|
|
continue
|
|
}
|
|
t, err := s.eval.Observe(ctx, evaluate.Observation{
|
|
MonitorID: m.ID, Region: region, OK: r.OK, At: r.StartedAt,
|
|
Interval: time.Duration(m.IntervalSeconds) * time.Second, Confirmations: int(m.Confirmations), Regions: m.Regions,
|
|
})
|
|
if err == nil && t != evaluate.None {
|
|
err = s.transition(ctx, m, t, r.StartedAt)
|
|
}
|
|
if err != nil {
|
|
// The next result re-evaluates; a missed transition only delays
|
|
// the alert by one interval.
|
|
s.log.ErrorContext(ctx, "evaluating result failed", "monitor", m.ID, "error", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// transition opens or resolves the monitor's incident and queues a
|
|
// notification for every enabled channel of the org, in one transaction.
|
|
func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow, t evaluate.Transition, at time.Time) error {
|
|
return s.db.Tx(ctx, tenant.Org(m.OrgID, uuid.Nil), func(q *store.Queries) error {
|
|
var (
|
|
inc store.Incident
|
|
event string
|
|
err error
|
|
)
|
|
switch t {
|
|
case evaluate.Down:
|
|
cause := map[string]string{}
|
|
latest, lerr := q.LatestResultsForMonitor(ctx, store.LatestResultsForMonitorParams{OrgID: m.OrgID, MonitorID: m.ID})
|
|
if lerr != nil {
|
|
return lerr
|
|
}
|
|
for _, l := range latest {
|
|
if !l.Ok {
|
|
cause[l.Region] = deref(l.Error)
|
|
}
|
|
}
|
|
raw, _ := json.Marshal(cause)
|
|
inc, err = q.OpenIncident(ctx, store.OpenIncidentParams{OrgID: m.OrgID, MonitorID: m.ID, StartedAt: at, Cause: raw})
|
|
event = notify.Opened
|
|
case evaluate.Up:
|
|
inc, err = q.ResolveIncident(ctx, store.ResolveIncidentParams{MonitorID: m.ID, ResolvedAt: &at})
|
|
event = notify.Resolved
|
|
}
|
|
// No row means the incident already exists or is already resolved,
|
|
// e.g. after the evaluation state was lost; nothing to announce.
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
channels, err := q.ListEnabledChannelIDs(ctx, m.OrgID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, ch := range channels {
|
|
if err := q.EnqueueNotification(ctx, store.EnqueueNotificationParams{OrgID: m.OrgID, ChannelID: ch, IncidentID: inc.ID, Event: event}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
s.log.InfoContext(ctx, "incident "+event, "monitor", m.ID, "incident", inc.ID, "channels", len(channels))
|
|
return nil
|
|
})
|
|
}
|
|
|
|
// RunNotifier delivers queued notifications until ctx ends. Every API replica
|
|
// runs it; rows are leased so each is sent by one replica at a time.
|
|
func (s *Server) RunNotifier(ctx context.Context) {
|
|
tick := time.NewTicker(2 * time.Second)
|
|
defer tick.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-tick.C:
|
|
for s.deliverBatch(ctx) == notifyBatch && ctx.Err() == nil {
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (s *Server) deliverBatch(ctx context.Context) int {
|
|
var rows []store.NotificationDetailsRow
|
|
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
ids, err := q.ClaimNotifications(ctx, notifyBatch)
|
|
if err != nil || len(ids) == 0 {
|
|
return err
|
|
}
|
|
rows, err = q.NotificationDetails(ctx, ids)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
if ctx.Err() == nil {
|
|
s.log.WarnContext(ctx, "claiming notifications failed", "error", err)
|
|
}
|
|
return 0
|
|
}
|
|
for _, n := range rows {
|
|
sendErr := s.send(ctx, n.ChannelType, n.ChannelConfig, eventOf(n))
|
|
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
if sendErr == nil {
|
|
return q.MarkNotificationSent(ctx, n.ID)
|
|
}
|
|
return q.MarkNotificationFailed(ctx, store.MarkNotificationFailedParams{
|
|
ID: n.ID, LastError: ptr(truncateValid(sendErr.Error(), 500)), MaxAttempts: maxNotifyAttempts,
|
|
RetryInSeconds: int32(retryDelay(int(n.Attempts)).Seconds()),
|
|
})
|
|
})
|
|
if err != nil {
|
|
s.log.WarnContext(ctx, "recording notification result failed", "notification", n.ID, "error", err)
|
|
}
|
|
if sendErr != nil {
|
|
s.log.WarnContext(ctx, "notification failed", "notification", n.ID, "channel", n.ChannelID, "attempt", n.Attempts+1, "error", sendErr)
|
|
}
|
|
}
|
|
return len(rows)
|
|
}
|
|
|
|
// retryDelay grows from 30 s to about four hours over ten attempts.
|
|
func retryDelay(attempts int) time.Duration {
|
|
return min(30*time.Second<<attempts, 4*time.Hour)
|
|
}
|
|
|
|
func eventOf(n store.NotificationDetailsRow) notify.Event {
|
|
ev := notify.Event{
|
|
Kind: n.Event, IncidentID: n.IncidentID, StartedAt: n.StartedAt, ResolvedAt: n.ResolvedAt,
|
|
Monitor: notify.Monitor{ID: n.MonitorID, Name: n.MonitorName, Type: n.MonitorType, Target: n.MonitorTarget},
|
|
}
|
|
_ = json.Unmarshal(n.Cause, &ev.Cause)
|
|
return ev
|
|
}
|
|
|
|
// webhookConfig is stored for webhook channels; Secret is sealed.
|
|
type webhookConfig struct {
|
|
URL string `json:"url"`
|
|
Secret string `json:"secret"`
|
|
}
|
|
|
|
// emailConfig is stored for email channels.
|
|
type emailConfig struct {
|
|
To []string `json:"to"`
|
|
Locale string `json:"locale"`
|
|
}
|
|
|
|
var errMailDisabled = errors.New("email is not configured on this server (UPTIME_SMTP_URL)")
|
|
|
|
func (s *Server) send(ctx context.Context, typ string, config []byte, ev notify.Event) error {
|
|
switch typ {
|
|
case "webhook":
|
|
var c webhookConfig
|
|
if err := json.Unmarshal(config, &c); err != nil {
|
|
return err
|
|
}
|
|
sealedSecret, err := base64.StdEncoding.DecodeString(c.Secret)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
secret, err := s.keys.Open(sealedSecret, []byte(c.URL))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return notify.Webhook{URL: c.URL, Secret: secret, AllowPrivate: !s.cloud()}.Send(ctx, ev)
|
|
case "email":
|
|
if s.smtp == nil {
|
|
return errMailDisabled
|
|
}
|
|
var c emailConfig
|
|
if err := json.Unmarshal(config, &c); err != nil {
|
|
return err
|
|
}
|
|
return s.smtp.Send(ctx, s.mailFor(ev, c.To, c.Locale))
|
|
}
|
|
return fmt.Errorf("unknown channel type %q", typ)
|
|
}
|
|
|
|
func (s *Server) mailFor(ev notify.Event, to []string, locale string) notify.Mail {
|
|
l := s.catalog.Match(locale)
|
|
data := map[string]any{
|
|
"Monitor": ev.Monitor.Name,
|
|
"Target": ev.Monitor.Target,
|
|
"Since": ev.StartedAt.UTC().Format("2006-01-02 15:04 MST"),
|
|
}
|
|
var cause []string
|
|
for region, msg := range ev.Cause {
|
|
cause = append(cause, region+": "+msg)
|
|
}
|
|
slices.Sort(cause)
|
|
data["Cause"] = strings.Join(cause, "\n")
|
|
if ev.ResolvedAt != nil {
|
|
data["Duration"] = ev.ResolvedAt.Sub(ev.StartedAt).Round(time.Second).String()
|
|
}
|
|
return notify.Mail{
|
|
To: to,
|
|
Subject: l.T("email."+ev.Kind+".subject", data),
|
|
Body: l.T("email."+ev.Kind+".body", data),
|
|
}
|
|
}
|