268 lines
8.1 KiB
Go
268 lines
8.1 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 assigned to the monitor, 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
|
|
}
|
|
routes, err := q.MonitorAlertRoutes(ctx, m.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
quiet := map[uuid.UUID]bool{}
|
|
seen := map[uuid.UUID]bool{}
|
|
var channels []uuid.UUID
|
|
for _, r := range routes {
|
|
muted, ok := quiet[r.GroupID]
|
|
if !ok {
|
|
muted = isQuietRawAt(r.QuietHours, at)
|
|
quiet[r.GroupID] = muted
|
|
}
|
|
if muted || seen[r.ChannelID] {
|
|
continue
|
|
}
|
|
seen[r.ChannelID] = true
|
|
channels = append(channels, r.ChannelID)
|
|
}
|
|
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))
|
|
}
|
|
if p, ok := notify.Lookup(typ); ok {
|
|
settings, locale, err := s.openProviderSettings(typ, config)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return p.Send(ctx, settings, s.messageFor(ev, locale), !s.cloud())
|
|
}
|
|
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),
|
|
}
|
|
}
|