Merge pull request 'feat: multi-region evaluation, incidents and notifications (M5)' (#51) from feat/m5-alerting into main
Reviewed-on: #51
This commit was merged in pull request #51.
This commit is contained in:
commit
53f8c063fb
26 files changed
+2279
-24
No files matched your search
@@ -13,6 +13,7 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
|
||||
@@ -57,6 +58,9 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := notify.ParseSMTP(cfg.SMTPURL); err != nil {
|
||||
return err
|
||||
}
|
||||
deps, err := platform.Connect(ctx, cfg.Storage, log)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -74,6 +78,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
|
||||
r.StaticFS("/static", web.Static())
|
||||
srv.Mount(r)
|
||||
go srv.RunScheduler(ctx)
|
||||
go srv.RunNotifier(ctx)
|
||||
|
||||
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
|
||||
}
|
||||
|
||||
+13
-9
@@ -187,18 +187,20 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
ids[i] = r.MonitorID
|
||||
}
|
||||
now := time.Now()
|
||||
monitors := map[uuid.UUID]store.MonitorsForResultsRow{}
|
||||
var accepted []agentapi.Result
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
monitors, err := q.MonitorsForJobs(ctx, store.MonitorsForJobsParams{Region: region, Ids: ids})
|
||||
rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{Region: region, Ids: ids})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
orgOf := make(map[uuid.UUID]uuid.UUID, len(monitors))
|
||||
for _, m := range monitors {
|
||||
orgOf[m.ID] = m.OrgID
|
||||
for _, m := range rows {
|
||||
monitors[m.ID] = m
|
||||
}
|
||||
rows := make([]store.InsertCheckResultsParams, 0, len(req.Results))
|
||||
params := make([]store.InsertCheckResultsParams, 0, len(req.Results))
|
||||
for _, r := range req.Results {
|
||||
org, ok := orgOf[r.MonitorID]
|
||||
m, ok := monitors[r.MonitorID]
|
||||
org := m.OrgID
|
||||
// A checker may only report monitors of its own region, and
|
||||
// timestamps far from now are rejected rather than skewing
|
||||
// history.
|
||||
@@ -215,18 +217,20 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
if r.Error != "" {
|
||||
row.Error = ptr(truncateValid(r.Error, 500))
|
||||
}
|
||||
rows = append(rows, row)
|
||||
params = append(params, row)
|
||||
accepted = append(accepted, r)
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
if len(params) == 0 {
|
||||
return nil
|
||||
}
|
||||
_, err = q.InsertCheckResults(ctx, rows)
|
||||
_, err = q.InsertCheckResults(ctx, params)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.evaluateResults(ctx, region, accepted, monitors)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
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) })
|
||||
for _, r := range results {
|
||||
m, ok := monitors[r.MonitorID]
|
||||
if !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),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
|
||||
)
|
||||
|
||||
// receiver records verified webhook deliveries.
|
||||
type receiver struct {
|
||||
srv *httptest.Server
|
||||
secret atomic.Value
|
||||
mu sync.Mutex
|
||||
events []notify.Event
|
||||
forged int
|
||||
}
|
||||
|
||||
func newReceiver(t *testing.T) *receiver {
|
||||
r := &receiver{}
|
||||
r.secret.Store("")
|
||||
r.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
body, _ := io.ReadAll(req.Body)
|
||||
ts, _ := strconv.ParseInt(req.Header.Get(notify.TimestampHeader), 10, 64)
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if req.Header.Get(notify.SignatureHeader) != notify.Sign([]byte(r.secret.Load().(string)), body, ts) {
|
||||
r.forged++
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
var ev notify.Event
|
||||
_ = json.Unmarshal(body, &ev)
|
||||
r.events = append(r.events, ev)
|
||||
}))
|
||||
t.Cleanup(r.srv.Close)
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *receiver) kinds() []string {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
var out []string
|
||||
for _, e := range r.events {
|
||||
out = append(out, e.Kind)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestAlerting(t *testing.T) {
|
||||
mail := notifytest.NewSMTP(t)
|
||||
e := newEnvWith(t, func(c *config.API) { c.SMTPURL = mail.URL() })
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
go e.api.RunNotifier(ctx)
|
||||
|
||||
var healthy atomic.Bool
|
||||
healthy.Store(true)
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if !healthy.Load() {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}
|
||||
}))
|
||||
defer target.Close()
|
||||
|
||||
eu, us := uniq("eu-"), uniq("us-")
|
||||
e.startChecker(t, e.agentToken(t, eu))
|
||||
e.startChecker(t, e.agentToken(t, us))
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("a")+".test", uniq("alert-"))
|
||||
|
||||
hook := newReceiver(t)
|
||||
st, body := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "Ops hook", "type": "webhook", "url": hook.srv.URL})
|
||||
if st != http.StatusCreated || body["signing_secret"] == "" {
|
||||
t.Fatalf("create webhook channel = %d %v", st, body)
|
||||
}
|
||||
hook.secret.Store(body["signing_secret"].(string))
|
||||
hookID := body["channel"].(map[string]any)["id"].(string)
|
||||
|
||||
st, body = owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "Ops mail", "type": "email", "to": []string{"ops@example.test"}, "locale": "de"})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create email channel = %d %v", st, body)
|
||||
}
|
||||
|
||||
st, body = owner.do("POST", "/api/v1/org/channels/"+hookID+"/test", nil)
|
||||
if st != http.StatusNoContent || len(hook.kinds()) != 1 || hook.kinds()[0] != notify.Test {
|
||||
t.Fatalf("test webhook = %d %v, received %v", st, body, hook.kinds())
|
||||
}
|
||||
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Shop", "type": "http", "target": target.URL, "interval_seconds": 10, "confirmations": 1, "regions": []string{eu, us},
|
||||
})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
monitorID := body["id"].(string)
|
||||
waitFor(t, 10*time.Second, "first healthy results", func() bool {
|
||||
_, body := owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
return len(body["monitors"].([]any)[0].(map[string]any)["latest"].([]any)) == 2
|
||||
})
|
||||
|
||||
healthy.Store(false)
|
||||
waitFor(t, 20*time.Second, "incident opened and announced", func() bool {
|
||||
return len(hook.kinds()) == 2 && len(mail.Messages()) == 1
|
||||
})
|
||||
_, body = owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
incidents := body["incidents"].([]any)
|
||||
if len(incidents) != 1 {
|
||||
t.Fatalf("incidents = %v, want one", incidents)
|
||||
}
|
||||
inc := incidents[0].(map[string]any)
|
||||
if inc["monitor_id"] != monitorID || inc["resolved_at"] != nil || len(inc["cause"].(map[string]any)) != 2 {
|
||||
t.Errorf("open incident = %v, want unresolved with a cause per region", inc)
|
||||
}
|
||||
if msg := mail.Messages()[0].Data; !strings.Contains(msg, "Subject: [DOWN] Shop") || !strings.Contains(msg, "ist in allen Regionen nicht erreichbar") {
|
||||
t.Errorf("down mail = %q, want German down notice", msg)
|
||||
}
|
||||
|
||||
healthy.Store(true)
|
||||
waitFor(t, 20*time.Second, "incident resolved and announced", func() bool {
|
||||
return len(hook.kinds()) == 3 && len(mail.Messages()) == 2
|
||||
})
|
||||
if got := strings.Join(hook.kinds(), ","); got != "test,opened,resolved" {
|
||||
t.Errorf("webhook events = %s, want test,opened,resolved", got)
|
||||
}
|
||||
_, body = owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
if inc := body["incidents"].([]any)[0].(map[string]any); inc["resolved_at"] == nil {
|
||||
t.Errorf("incident after recovery = %v, want resolved", inc)
|
||||
}
|
||||
if hook.forged != 0 {
|
||||
t.Errorf("receiver saw %d requests with bad signatures", hook.forged)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmailChannelNeedsSMTP(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("m")+".test", uniq("mail-"))
|
||||
st, body := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "x", "type": "email", "to": []string{"a@b.test"}})
|
||||
expect(t, "email channel without smtp", st, body, http.StatusUnprocessableEntity, "email_not_configured")
|
||||
st, body = owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "x", "type": "webhook", "url": "ftp://x"})
|
||||
expect(t, "webhook with bad url", st, body, http.StatusUnprocessableEntity, "invalid_webhook_url")
|
||||
}
|
||||
|
||||
// TestLostEvaluationStateDoesNotDuplicateIncidents simulates Redis losing
|
||||
// the evaluation state while an incident is open: the next failure tries to
|
||||
// open the incident again, which must neither fail nor notify twice.
|
||||
func TestLostEvaluationStateDoesNotDuplicateIncidents(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
go e.api.RunScheduler(ctx)
|
||||
go e.api.RunNotifier(ctx)
|
||||
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer target.Close()
|
||||
region := uniq("eu-")
|
||||
e.startChecker(t, e.agentToken(t, region))
|
||||
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("l")+".test", uniq("lost-"))
|
||||
hook := newReceiver(t)
|
||||
_, body := owner.do("POST", "/api/v1/org/channels", map[string]any{"name": "hook", "type": "webhook", "url": hook.srv.URL})
|
||||
hook.secret.Store(body["signing_secret"].(string))
|
||||
_, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{
|
||||
"name": "Down", "type": "http", "target": target.URL, "interval_seconds": 10, "confirmations": 1, "regions": []string{region},
|
||||
})
|
||||
monitorID := body["id"].(string)
|
||||
|
||||
waitFor(t, 10*time.Second, "incident announced", func() bool { return len(hook.kinds()) == 1 })
|
||||
if err := e.rdb.Del(context.Background(), "eval:"+monitorID).Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Wait for the next run, which sees a fresh state and transitions again.
|
||||
time.Sleep(12 * time.Second)
|
||||
_, body = owner.do("GET", "/api/v1/org/incidents", nil)
|
||||
if n := len(body["incidents"].([]any)); n != 1 {
|
||||
t.Errorf("incidents = %d, want 1", n)
|
||||
}
|
||||
if got := hook.kinds(); len(got) != 1 {
|
||||
t.Errorf("webhook events = %v, want a single opened", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
)
|
||||
|
||||
type channelRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
Type string `json:"type" binding:"required,oneof=webhook email"`
|
||||
URL string `json:"url" binding:"max=2000"`
|
||||
To []string `json:"to" binding:"max=20,dive,max=320"`
|
||||
Locale string `json:"locale" binding:"max=10"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type channelView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Enabled bool `json:"enabled"`
|
||||
URL string `json:"url,omitempty"`
|
||||
To []string `json:"to,omitempty"`
|
||||
Locale string `json:"locale,omitempty"`
|
||||
}
|
||||
|
||||
func viewChannel(ch store.NotificationChannel) channelView {
|
||||
v := channelView{ID: ch.ID, Name: ch.Name, Type: ch.Type, Enabled: ch.Enabled}
|
||||
switch ch.Type {
|
||||
case "webhook":
|
||||
var c webhookConfig
|
||||
_ = json.Unmarshal(ch.Config, &c)
|
||||
v.URL = c.URL
|
||||
case "email":
|
||||
var c emailConfig
|
||||
_ = json.Unmarshal(ch.Config, &c)
|
||||
v.To, v.Locale = c.To, c.Locale
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// channelConfig validates req and builds the stored config. For webhooks a
|
||||
// new signing secret is created unless previous holds one for the same URL;
|
||||
// the plain secret is returned only when it is new.
|
||||
func (s *Server) channelConfig(req *channelRequest, previous []byte) (config []byte, newSecret, code string) {
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
if req.Name == "" {
|
||||
return nil, "", "invalid_input"
|
||||
}
|
||||
switch req.Type {
|
||||
case "webhook":
|
||||
u, err := url.Parse(strings.TrimSpace(req.URL))
|
||||
if err != nil || u.Host == "" || u.User != nil || (u.Scheme != "https" && (s.cloud() || u.Scheme != "http")) {
|
||||
return nil, "", "invalid_webhook_url"
|
||||
}
|
||||
req.URL = u.String()
|
||||
var secret []byte
|
||||
if previous != nil {
|
||||
var old webhookConfig
|
||||
if json.Unmarshal(previous, &old) == nil {
|
||||
if sealedOld, err := base64.StdEncoding.DecodeString(old.Secret); err == nil {
|
||||
secret, _ = s.keys.Open(sealedOld, []byte(old.URL))
|
||||
}
|
||||
}
|
||||
}
|
||||
if secret == nil {
|
||||
b := make([]byte, 32)
|
||||
_, _ = rand.Read(b)
|
||||
secret = []byte(hex.EncodeToString(b))
|
||||
newSecret = string(secret)
|
||||
}
|
||||
// The secret is bound to the URL so a copied config row cannot be
|
||||
// pointed at another receiver with the same secret.
|
||||
sealedSecret := s.keys.Seal(secret, []byte(req.URL))
|
||||
config, _ = json.Marshal(webhookConfig{URL: req.URL, Secret: base64.StdEncoding.EncodeToString(sealedSecret)})
|
||||
return config, newSecret, ""
|
||||
case "email":
|
||||
if s.smtp == nil {
|
||||
return nil, "", "email_not_configured"
|
||||
}
|
||||
if len(req.To) == 0 {
|
||||
return nil, "", "invalid_email"
|
||||
}
|
||||
for i, to := range req.To {
|
||||
to = normalizeEmail(to)
|
||||
if a, err := mail.ParseAddress(to); err != nil || a.Address != to {
|
||||
return nil, "", "invalid_email"
|
||||
}
|
||||
req.To[i] = to
|
||||
}
|
||||
if req.Locale == "" || !s.catalog.IsSupported(req.Locale) {
|
||||
req.Locale = "en"
|
||||
}
|
||||
config, _ = json.Marshal(emailConfig{To: req.To, Locale: req.Locale})
|
||||
return config, "", ""
|
||||
}
|
||||
return nil, "", "invalid_input"
|
||||
}
|
||||
|
||||
func (s *Server) listChannels(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.NotificationChannel
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListChannels(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]channelView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = viewChannel(r)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"channels": out, "email_available": s.smtp != nil})
|
||||
}
|
||||
|
||||
func (s *Server) createChannel(c *gin.Context) {
|
||||
var req channelRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
config, secret, code := s.channelConfig(&req, nil)
|
||||
if code != "" {
|
||||
fail(c, http.StatusUnprocessableEntity, code)
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var row store.NotificationChannel
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
row, err = q.CreateChannel(ctx, store.CreateChannelParams{
|
||||
OrgID: p.Org.ID, Name: req.Name, Type: req.Type, Config: config, Enabled: req.Enabled == nil || *req.Enabled,
|
||||
})
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, gin.H{"channel": viewChannel(row), "signing_secret": secret})
|
||||
}
|
||||
|
||||
func (s *Server) updateChannel(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
var req channelRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var (
|
||||
row store.NotificationChannel
|
||||
secret string
|
||||
code string
|
||||
)
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
old, err := q.GetChannel(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if old.Type != req.Type {
|
||||
code = "channel_type_immutable"
|
||||
return nil
|
||||
}
|
||||
var config []byte
|
||||
config, secret, code = s.channelConfig(&req, old.Config)
|
||||
if code != "" {
|
||||
return nil
|
||||
}
|
||||
row, err = q.UpdateChannel(ctx, store.UpdateChannelParams{ID: id, Name: req.Name, Config: config, Enabled: req.Enabled == nil || *req.Enabled})
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows):
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
case err != nil:
|
||||
internalError(c, err)
|
||||
case code != "":
|
||||
fail(c, http.StatusUnprocessableEntity, code)
|
||||
default:
|
||||
c.JSON(http.StatusOK, gin.H{"channel": viewChannel(row), "signing_secret": secret})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deleteChannel(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
n, err = q.DeleteChannel(ctx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// testChannel sends a sample event right away so users can verify their
|
||||
// receiver; the error is returned to the user.
|
||||
func (s *Server) testChannel(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
if !s.limit(c, "channel_test:"+id.String(), 10, time.Minute) {
|
||||
return
|
||||
}
|
||||
var ch store.NotificationChannel
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
ch, err = q.GetChannel(ctx, id)
|
||||
return err
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
ev := notify.Event{
|
||||
Kind: notify.Test, IncidentID: uuid.Nil, StartedAt: time.Now(),
|
||||
Monitor: notify.Monitor{Name: "Example monitor", Type: "http", Target: "https://example.com"},
|
||||
}
|
||||
if err := s.send(ctx, ch.Type, ch.Config, ev); err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusBadGateway, gin.H{
|
||||
"error": "channel_test_failed", "message": truncateValid(err.Error(), 300),
|
||||
})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type incidentView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
MonitorID uuid.UUID `json:"monitor_id"`
|
||||
MonitorName string `json:"monitor_name"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ResolvedAt *time.Time `json:"resolved_at"`
|
||||
Cause map[string]string `json:"cause"`
|
||||
}
|
||||
|
||||
func (s *Server) listIncidents(c *gin.Context) {
|
||||
p := current(c)
|
||||
ctx := c.Request.Context()
|
||||
var rows []store.ListIncidentsRow
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListIncidents(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
out := make([]incidentView, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = incidentView{ID: r.ID, MonitorID: r.MonitorID, MonitorName: r.MonitorName, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt}
|
||||
_ = json.Unmarshal(r.Cause, &out[i].Cause)
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"incidents": out})
|
||||
}
|
||||
@@ -28,6 +28,9 @@ type monitorRequest struct {
|
||||
Config json.RawMessage `json:"config"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
Regions []string `json:"regions" binding:"required,min=1,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"`
|
||||
}
|
||||
|
||||
type latestView struct {
|
||||
@@ -48,6 +51,7 @@ type monitorView struct {
|
||||
TimeoutMS int32 `json:"timeout_ms"`
|
||||
Config json.RawMessage `json:"config"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Confirmations int32 `json:"confirmations"`
|
||||
Regions []string `json:"regions"`
|
||||
Latest []latestView `json:"latest"`
|
||||
}
|
||||
@@ -55,7 +59,7 @@ type monitorView struct {
|
||||
func viewMonitor(m store.Monitor, regions []string) monitorView {
|
||||
return monitorView{
|
||||
ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds,
|
||||
TimeoutMS: m.TimeoutMs, Config: m.Config, Enabled: m.Enabled, Regions: regions, Latest: []latestView{},
|
||||
TimeoutMS: m.TimeoutMs, Config: m.Config, Enabled: m.Enabled, Confirmations: m.Confirmations, Regions: regions, Latest: []latestView{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +84,9 @@ func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest) bool {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_interval", "Min", s.minInterval())
|
||||
return false
|
||||
}
|
||||
if req.Confirmations == 0 {
|
||||
req.Confirmations = 2
|
||||
}
|
||||
if req.TimeoutMS == 0 {
|
||||
req.TimeoutMS = min(10000, req.IntervalSeconds*1000/2)
|
||||
}
|
||||
@@ -176,7 +183,7 @@ func (s *Server) createMonitor(c *gin.Context) {
|
||||
m, err = q.CreateMonitor(ctx, store.CreateMonitorParams{
|
||||
OrgID: p.Org.ID, Name: req.Name, Type: req.Type, Target: req.Target,
|
||||
IntervalSeconds: int32(req.IntervalSeconds), TimeoutMs: int32(req.TimeoutMS),
|
||||
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled,
|
||||
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled, Confirmations: int32(req.Confirmations),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -241,7 +248,7 @@ func (s *Server) updateMonitor(c *gin.Context) {
|
||||
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),
|
||||
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled,
|
||||
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled, Confirmations: int32(req.Confirmations),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -295,6 +302,7 @@ func (s *Server) deleteMonitor(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
_ = s.eval.Forget(ctx, id)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,9 @@ 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/config"
|
||||
"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/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
||||
@@ -38,6 +40,8 @@ type Server struct {
|
||||
totp *auth.TOTPVerifier
|
||||
sso *sso.Client
|
||||
sched *schedule.Scheduler
|
||||
eval *evaluate.Evaluator
|
||||
smtp *notify.SMTP
|
||||
}
|
||||
|
||||
// Deps are the external resources a Server needs.
|
||||
@@ -50,9 +54,13 @@ type Deps struct {
|
||||
}
|
||||
|
||||
// New returns a Server. It does not register any routes; see Mount.
|
||||
// cfg must have passed Validate.
|
||||
func New(cfg config.API, d Deps) *Server {
|
||||
allowPrivate := cfg.SSOAllowPrivate()
|
||||
mail, _ := notify.ParseSMTP(cfg.SMTPURL)
|
||||
return &Server{
|
||||
eval: evaluate.New(d.Redis),
|
||||
smtp: mail,
|
||||
cfg: cfg,
|
||||
log: d.Log,
|
||||
db: d.DB,
|
||||
@@ -105,6 +113,14 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
org.PUT("/monitors/:id", can(authz.MonitorsWrite), s.updateMonitor)
|
||||
org.DELETE("/monitors/:id", can(authz.MonitorsWrite), s.deleteMonitor)
|
||||
|
||||
org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents)
|
||||
|
||||
org.GET("/channels", can(authz.NotificationsRead), s.listChannels)
|
||||
org.POST("/channels", can(authz.NotificationsWrite), s.createChannel)
|
||||
org.PUT("/channels/:id", can(authz.NotificationsWrite), s.updateChannel)
|
||||
org.DELETE("/channels/:id", can(authz.NotificationsWrite), s.deleteChannel)
|
||||
org.POST("/channels/:id/test", can(authz.NotificationsWrite), s.testChannel)
|
||||
|
||||
org.GET("/sso", can(authz.OrgManage), s.listSSOProviders)
|
||||
org.POST("/sso", sessionOnly(), can(authz.OrgManage), s.createSSOProvider)
|
||||
org.PUT("/sso/:id", sessionOnly(), can(authz.OrgManage), s.updateSSOProvider)
|
||||
|
||||
@@ -34,10 +34,17 @@ import (
|
||||
type env struct {
|
||||
srv *httptest.Server
|
||||
dbPool *pgxpool.Pool
|
||||
rdb *redis.Client
|
||||
api *api.Server
|
||||
}
|
||||
|
||||
func newEnv(t *testing.T) *env {
|
||||
t.Helper()
|
||||
return newEnvWith(t, nil)
|
||||
}
|
||||
|
||||
// newEnvWith lets a test adjust the API configuration before start.
|
||||
func newEnvWith(t *testing.T, adjust func(*config.API)) *env {
|
||||
t.Helper()
|
||||
dsn, redisURL := os.Getenv("UPTIME_TEST_DATABASE_URL"), os.Getenv("UPTIME_TEST_REDIS_URL")
|
||||
if dsn == "" || redisURL == "" {
|
||||
@@ -76,7 +83,7 @@ func newEnv(t *testing.T) *env {
|
||||
}
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
e := &env{dbPool: pool}
|
||||
e := &env{dbPool: pool, rdb: rdb}
|
||||
r := platform.NewRouter(log)
|
||||
e.srv = httptest.NewUnstartedServer(r)
|
||||
e.srv.StartTLS()
|
||||
@@ -90,6 +97,9 @@ func newEnv(t *testing.T) *env {
|
||||
PublicURL: e.srv.URL,
|
||||
SSOPrivateNetworks: "true",
|
||||
}
|
||||
if adjust != nil {
|
||||
adjust(&cfg)
|
||||
}
|
||||
e.api = api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog})
|
||||
e.api.Mount(r)
|
||||
return e
|
||||
|
||||
@@ -80,6 +80,10 @@ type API struct {
|
||||
// SSOPrivateNetworks is "auto", "true" or "false". Auto allows
|
||||
// organizations' IdPs on private networks only in the self-hosted edition.
|
||||
SSOPrivateNetworks string `env:"UPTIME_SSO_ALLOW_PRIVATE_NETWORKS" envDefault:"auto"`
|
||||
// SMTPURL configures outgoing mail for email notification channels,
|
||||
// e.g. smtp://user:pass@host:587?from=alerts@example.com. Empty disables
|
||||
// email channels.
|
||||
SMTPURL string `env:"UPTIME_SMTP_URL"`
|
||||
}
|
||||
|
||||
// SSOAllowPrivate resolves SSOPrivateNetworks.
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// Package evaluate turns per-region check results into a monitor state.
|
||||
//
|
||||
// A monitor goes down only when every region it is assigned to has failed
|
||||
// the configured number of times in a row and reported recently. A region
|
||||
// without recent results counts as unknown and keeps the monitor up: one
|
||||
// checker losing its network must not page anyone. Any successful region
|
||||
// brings the monitor back up.
|
||||
//
|
||||
// The state lives in Redis and each observation is applied by one Lua
|
||||
// script, so concurrent results on several API replicas produce exactly one
|
||||
// transition.
|
||||
package evaluate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// Transition is the change an observation caused.
|
||||
type Transition int
|
||||
|
||||
// Transitions.
|
||||
const (
|
||||
None Transition = iota
|
||||
Down
|
||||
Up
|
||||
)
|
||||
|
||||
func (t Transition) String() string {
|
||||
switch t {
|
||||
case Down:
|
||||
return "down"
|
||||
case Up:
|
||||
return "up"
|
||||
}
|
||||
return "none"
|
||||
}
|
||||
|
||||
// Observation is one check result with the monitor settings needed to judge
|
||||
// it.
|
||||
type Observation struct {
|
||||
MonitorID uuid.UUID
|
||||
Region string
|
||||
OK bool
|
||||
At time.Time
|
||||
Interval time.Duration
|
||||
Confirmations int
|
||||
// Regions are all regions the monitor is assigned to.
|
||||
Regions []string
|
||||
}
|
||||
|
||||
// staleAfter is how old a region's last result may be before the region
|
||||
// counts as unknown.
|
||||
func staleAfter(interval time.Duration) time.Duration {
|
||||
return max(3*interval, 2*time.Minute)
|
||||
}
|
||||
|
||||
const stateTTL = 7 * 24 * time.Hour
|
||||
|
||||
// observeScript applies one result.
|
||||
//
|
||||
// KEYS: monitor state hash.
|
||||
// ARGV: region, ok (1/0), at ms, confirmations, stale-before ms, ttl s,
|
||||
// then every assigned region.
|
||||
var observeScript = redis.NewScript(`
|
||||
local key, region = KEYS[1], ARGV[1]
|
||||
local ok, at, need, stale = ARGV[2] == '1', tonumber(ARGV[3]), tonumber(ARGV[4]), tonumber(ARGV[5])
|
||||
local last = tonumber(redis.call('HGET', key, 'a:' .. region) or '0')
|
||||
if at < last then return 'none' end
|
||||
redis.call('HSET', key, 'a:' .. region, string.format('%.0f', at))
|
||||
if ok then
|
||||
redis.call('HSET', key, 'f:' .. region, 0)
|
||||
else
|
||||
redis.call('HINCRBY', key, 'f:' .. region, 1)
|
||||
end
|
||||
redis.call('EXPIRE', key, ARGV[6])
|
||||
local state = redis.call('HGET', key, 'state') or 'up'
|
||||
if state == 'down' then
|
||||
if ok then
|
||||
redis.call('HSET', key, 'state', 'up')
|
||||
return 'up'
|
||||
end
|
||||
return 'none'
|
||||
end
|
||||
for i = 7, #ARGV do
|
||||
local r = ARGV[i]
|
||||
local fails = tonumber(redis.call('HGET', key, 'f:' .. r) or '0')
|
||||
local seen = tonumber(redis.call('HGET', key, 'a:' .. r) or '0')
|
||||
if fails < need or seen < stale then return 'none' end
|
||||
end
|
||||
redis.call('HSET', key, 'state', 'down')
|
||||
return 'down'
|
||||
`)
|
||||
|
||||
// Evaluator is safe for concurrent use.
|
||||
type Evaluator struct {
|
||||
rdb redis.UniversalClient
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// New returns an Evaluator on rdb.
|
||||
func New(rdb redis.UniversalClient) *Evaluator {
|
||||
return &Evaluator{rdb: rdb, now: time.Now}
|
||||
}
|
||||
|
||||
// Observe applies o and reports the resulting transition.
|
||||
func (e *Evaluator) Observe(ctx context.Context, o Observation) (Transition, error) {
|
||||
ok := "0"
|
||||
if o.OK {
|
||||
ok = "1"
|
||||
}
|
||||
stale := e.now().Add(-staleAfter(o.Interval)).UnixMilli()
|
||||
args := []any{o.Region, ok, o.At.UnixMilli(), max(o.Confirmations, 1), stale, int(stateTTL.Seconds())}
|
||||
for _, r := range o.Regions {
|
||||
args = append(args, r)
|
||||
}
|
||||
res, err := observeScript.Run(ctx, e.rdb, []string{"eval:" + o.MonitorID.String()}, args...).Text()
|
||||
if err != nil {
|
||||
return None, fmt.Errorf("evaluate: %w", err)
|
||||
}
|
||||
switch res {
|
||||
case "down":
|
||||
return Down, nil
|
||||
case "up":
|
||||
return Up, nil
|
||||
}
|
||||
return None, nil
|
||||
}
|
||||
|
||||
// Forget drops the state of a deleted monitor.
|
||||
func (e *Evaluator) Forget(ctx context.Context, id uuid.UUID) error {
|
||||
return e.rdb.Del(ctx, "eval:"+id.String()).Err()
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package evaluate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func newTest(t *testing.T) (*Evaluator, *time.Time) {
|
||||
t.Helper()
|
||||
url := os.Getenv("UPTIME_TEST_REDIS_URL")
|
||||
if url == "" {
|
||||
t.Skip("UPTIME_TEST_REDIS_URL not set")
|
||||
}
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rdb := redis.NewClient(opts)
|
||||
t.Cleanup(func() { _ = rdb.Close() })
|
||||
now := time.UnixMilli(1_800_000_000_000)
|
||||
e := New(rdb)
|
||||
e.now = func() time.Time { return now }
|
||||
return e, &now
|
||||
}
|
||||
|
||||
type step struct {
|
||||
region string
|
||||
ok bool
|
||||
want Transition
|
||||
}
|
||||
|
||||
func play(t *testing.T, e *Evaluator, now *time.Time, regions []string, confirmations int, steps []step) {
|
||||
t.Helper()
|
||||
id := uuid.New()
|
||||
for i, s := range steps {
|
||||
*now = now.Add(time.Second)
|
||||
got, err := e.Observe(context.Background(), Observation{
|
||||
MonitorID: id, Region: s.region, OK: s.ok, At: *now,
|
||||
Interval: time.Minute, Confirmations: confirmations, Regions: regions,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != s.want {
|
||||
t.Errorf("step %d (%s ok=%t) = %v, want %v", i, s.region, s.ok, got, s.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownOnlyWhenAllRegionsFail(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
play(t, e, now, []string{"eu", "us"}, 2, []step{
|
||||
{"eu", false, None},
|
||||
{"eu", false, None}, // eu confirmed down, us has not reported
|
||||
{"us", true, None},
|
||||
{"us", false, None},
|
||||
{"eu", false, None},
|
||||
{"us", false, Down}, // both regions failed twice in a row
|
||||
{"us", false, None}, // no repeated transition
|
||||
{"eu", true, Up}, // one healthy region is enough to recover
|
||||
{"eu", true, None},
|
||||
})
|
||||
}
|
||||
|
||||
func TestSingleRegionWithConfirmations(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
play(t, e, now, []string{"eu"}, 3, []step{
|
||||
{"eu", false, None},
|
||||
{"eu", false, None},
|
||||
{"eu", true, None}, // a success resets the count
|
||||
{"eu", false, None},
|
||||
{"eu", false, None},
|
||||
{"eu", false, Down},
|
||||
})
|
||||
}
|
||||
|
||||
func TestSilentRegionBlocksAlert(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
id := uuid.New()
|
||||
obs := func(region string, ok bool) Transition {
|
||||
got, err := e.Observe(context.Background(), Observation{
|
||||
MonitorID: id, Region: region, OK: ok, At: *now,
|
||||
Interval: time.Minute, Confirmations: 1, Regions: []string{"eu", "us"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
obs("us", false)
|
||||
// us stops reporting for longer than three intervals.
|
||||
*now = now.Add(5 * time.Minute)
|
||||
if got := obs("eu", false); got != None {
|
||||
t.Errorf("eu failure with us silent = %v, want none", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutOfOrderResultIgnored(t *testing.T) {
|
||||
e, now := newTest(t)
|
||||
id := uuid.New()
|
||||
obs := func(at time.Time, ok bool) Transition {
|
||||
got, err := e.Observe(context.Background(), Observation{
|
||||
MonitorID: id, Region: "eu", OK: ok, At: at, Interval: time.Minute, Confirmations: 1, Regions: []string{"eu"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
if got := obs(*now, false); got != Down {
|
||||
t.Fatalf("first failure = %v, want down", got)
|
||||
}
|
||||
if got := obs(now.Add(-time.Minute), true); got != None {
|
||||
t.Errorf("older success = %v, want ignored", got)
|
||||
}
|
||||
}
|
||||
@@ -133,6 +133,18 @@ func TestEveryPermissionHasALabel(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Notification mails are looked up as "email.<event>.subject|body".
|
||||
func TestEveryMailEventHasTexts(t *testing.T) {
|
||||
en := catalogKeys(t)["en"]
|
||||
for _, ev := range []string{"opened", "resolved", "test"} {
|
||||
for _, part := range []string{"subject", "body"} {
|
||||
if id := "email." + ev + "." + part; !en[id] {
|
||||
t.Errorf("en.json is missing %q", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The language switcher builds "lang.<code>" dynamically.
|
||||
func TestEveryLanguageHasAName(t *testing.T) {
|
||||
c, err := Load()
|
||||
|
||||
@@ -32,9 +32,18 @@
|
||||
"console.nav.tokens": "API-Tokens",
|
||||
"console.sso_required_action": "Mit SSO anmelden",
|
||||
"console.totp_missing_action": "Jetzt einrichten",
|
||||
"email.opened.body": "{{.Monitor}} ({{.Target}}) ist in allen Regionen nicht erreichbar seit {{.Since}}.\n\nLetzte Fehler:\n{{.Cause}}\n\nDu erhältst diese Nachricht, weil ein Benachrichtigungskanal deiner Organisation diese Adresse nutzt.",
|
||||
"email.opened.subject": "[DOWN] {{.Monitor}}",
|
||||
"email.resolved.body": "{{.Monitor}} ({{.Target}}) ist nach {{.Duration}} wieder erreichbar.",
|
||||
"email.resolved.subject": "[UP] {{.Monitor}}",
|
||||
"email.test.body": "Dies ist ein Test. Wenn du ihn lesen kannst, funktioniert der Kanal.",
|
||||
"email.test.subject": "Testbenachrichtigung von uptimesebi",
|
||||
"error.agent_protocol_unsupported": "Diese Agent-Version wird von der API nicht unterstützt. Bitte den Agent aktualisieren.",
|
||||
"error.already_assigned": "Das Mitglied hat diese Rolle bereits.",
|
||||
"error.already_member": "Diese Person ist bereits Mitglied.",
|
||||
"error.channel_test_failed": "Die Testbenachrichtigung konnte nicht zugestellt werden.",
|
||||
"error.channel_type_immutable": "Der Typ eines Kanals kann nicht geändert werden.",
|
||||
"error.email_not_configured": "E-Mail ist auf diesem Server nicht verfügbar.",
|
||||
"error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.",
|
||||
"error.forbidden": "Dafür fehlt dir die Berechtigung.",
|
||||
"error.internal": "Interner Fehler.",
|
||||
@@ -56,6 +65,7 @@
|
||||
"error.invalid_target": "Das Ziel passt nicht zu diesem Check-Typ.",
|
||||
"error.invalid_timeout": "Der Timeout muss zwischen 100 ms und 60 s liegen und kürzer als das Intervall sein.",
|
||||
"error.invalid_type": "Unbekannter Check-Typ.",
|
||||
"error.invalid_webhook_url": "Die Webhook-URL muss eine https-URL ohne Zugangsdaten sein.",
|
||||
"error.invitation_email_mismatch": "Diese Einladung ging an eine andere E-Mail-Adresse als die, mit der du angemeldet bist.",
|
||||
"error.invitation_invalid": "Diese Einladung ist ungültig, abgelaufen oder wurde bereits verwendet.",
|
||||
"error.keyword_needs_get": "Keyword-Checks brauchen GET-Anfragen.",
|
||||
|
||||
@@ -32,9 +32,18 @@
|
||||
"console.nav.tokens": "API tokens",
|
||||
"console.sso_required_action": "Sign in with SSO",
|
||||
"console.totp_missing_action": "Set up now",
|
||||
"email.opened.body": "{{.Monitor}} ({{.Target}}) is down in all of its regions since {{.Since}}.\n\nLast errors:\n{{.Cause}}\n\nYou receive this because a notification channel of your organization is set up for this address.",
|
||||
"email.opened.subject": "[DOWN] {{.Monitor}}",
|
||||
"email.resolved.body": "{{.Monitor}} ({{.Target}}) is reachable again after {{.Duration}}.",
|
||||
"email.resolved.subject": "[UP] {{.Monitor}}",
|
||||
"email.test.body": "This is a test. If you can read it, the channel works.",
|
||||
"email.test.subject": "Test notification from uptimesebi",
|
||||
"error.agent_protocol_unsupported": "This agent version is not supported by the API. Please update the agent.",
|
||||
"error.already_assigned": "The member already has this role.",
|
||||
"error.already_member": "This person is already a member.",
|
||||
"error.channel_test_failed": "The test notification could not be delivered.",
|
||||
"error.channel_type_immutable": "The type of a channel cannot be changed.",
|
||||
"error.email_not_configured": "Email is not available on this server.",
|
||||
"error.email_taken": "This email address is already registered.",
|
||||
"error.forbidden": "You are not allowed to do this.",
|
||||
"error.internal": "Internal error.",
|
||||
@@ -56,6 +65,7 @@
|
||||
"error.invalid_target": "The target is not valid for this check type.",
|
||||
"error.invalid_timeout": "The timeout must be between 100 ms and 60 s and shorter than the interval.",
|
||||
"error.invalid_type": "Unknown check type.",
|
||||
"error.invalid_webhook_url": "The webhook URL must be an https URL without credentials.",
|
||||
"error.invitation_email_mismatch": "This invitation was sent to a different email address than the one you are signed in with.",
|
||||
"error.invitation_invalid": "This invitation is invalid, expired or was already used.",
|
||||
"error.keyword_needs_get": "Keyword checks need GET requests.",
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
-- +goose Up
|
||||
-- How many consecutive failures a region needs before it counts as down.
|
||||
ALTER TABLE monitors ADD COLUMN confirmations integer NOT NULL DEFAULT 2 CHECK (confirmations BETWEEN 1 AND 10);
|
||||
|
||||
CREATE TABLE incidents (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
|
||||
monitor_id uuid NOT NULL REFERENCES monitors (id) ON DELETE CASCADE,
|
||||
started_at timestamptz NOT NULL,
|
||||
resolved_at timestamptz,
|
||||
-- Last error per region when the incident opened.
|
||||
cause jsonb NOT NULL DEFAULT '{}',
|
||||
CHECK (resolved_at IS NULL OR resolved_at >= started_at)
|
||||
);
|
||||
|
||||
-- Guards against duplicate incidents even if two evaluations race.
|
||||
CREATE UNIQUE INDEX incidents_one_open_idx ON incidents (monitor_id) WHERE resolved_at IS NULL;
|
||||
CREATE INDEX incidents_org_idx ON incidents (org_id, started_at DESC);
|
||||
|
||||
CREATE TABLE notification_channels (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
|
||||
name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
|
||||
type text NOT NULL CHECK (type IN ('webhook', 'email')),
|
||||
-- Type-specific settings; secrets inside are sealed by the application.
|
||||
config jsonb NOT NULL,
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX notification_channels_org_idx ON notification_channels (org_id);
|
||||
|
||||
-- Outbox: a row per channel and incident event, delivered with retries by
|
||||
-- any API replica.
|
||||
CREATE TABLE notifications (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
|
||||
channel_id uuid NOT NULL REFERENCES notification_channels (id) ON DELETE CASCADE,
|
||||
incident_id uuid NOT NULL REFERENCES incidents (id) ON DELETE CASCADE,
|
||||
event text NOT NULL CHECK (event IN ('opened', 'resolved')),
|
||||
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sent', 'failed')),
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
next_attempt_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
sent_at timestamptz,
|
||||
UNIQUE (channel_id, incident_id, event)
|
||||
);
|
||||
|
||||
CREATE INDEX notifications_due_idx ON notifications (next_attempt_at) WHERE status = 'pending';
|
||||
|
||||
ALTER TABLE incidents ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE incidents FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY incidents_tenant ON incidents FOR ALL
|
||||
USING (app_scope_system() OR org_id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR org_id = app_org_id());
|
||||
|
||||
ALTER TABLE notification_channels ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE notification_channels FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY notification_channels_tenant ON notification_channels FOR ALL
|
||||
USING (app_scope_system() OR org_id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR org_id = app_org_id());
|
||||
|
||||
ALTER TABLE notifications ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE notifications FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY notifications_tenant ON notifications FOR ALL
|
||||
USING (app_scope_system() OR org_id = app_org_id())
|
||||
WITH CHECK (app_scope_system() OR org_id = app_org_id());
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE notifications;
|
||||
DROP TABLE notification_channels;
|
||||
DROP TABLE incidents;
|
||||
ALTER TABLE monitors DROP COLUMN confirmations;
|
||||
@@ -0,0 +1,239 @@
|
||||
// Package notify delivers incident events to notification channels.
|
||||
//
|
||||
// Delivery is at least once: the API keeps an outbox and retries, so
|
||||
// receivers should deduplicate by incident ID and event.
|
||||
package notify
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/smtp"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
|
||||
)
|
||||
|
||||
// Event kinds.
|
||||
const (
|
||||
Opened = "opened"
|
||||
Resolved = "resolved"
|
||||
// Test is sent when a user tries out a channel.
|
||||
Test = "test"
|
||||
)
|
||||
|
||||
// Monitor identifies the affected monitor.
|
||||
type Monitor struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
Target string `json:"target"`
|
||||
}
|
||||
|
||||
// Event is one incident change, also the webhook payload.
|
||||
type Event struct {
|
||||
Kind string `json:"event"`
|
||||
IncidentID uuid.UUID `json:"incident_id"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
|
||||
Cause map[string]string `json:"cause,omitempty"`
|
||||
Monitor Monitor `json:"monitor"`
|
||||
}
|
||||
|
||||
// Webhook signs requests so receivers can verify they came from us: the
|
||||
// signature is HMAC-SHA256 over "<timestamp>.<body>" with the channel secret,
|
||||
// sent as "sha256=<hex>". Receivers should reject old timestamps.
|
||||
type Webhook struct {
|
||||
URL string
|
||||
Secret []byte
|
||||
AllowPrivate bool
|
||||
}
|
||||
|
||||
// Headers set on webhook requests.
|
||||
const (
|
||||
SignatureHeader = "X-Uptimesebi-Signature"
|
||||
TimestampHeader = "X-Uptimesebi-Timestamp"
|
||||
EventHeader = "X-Uptimesebi-Event"
|
||||
)
|
||||
|
||||
// Sign returns the signature header value for body at ts.
|
||||
func Sign(secret, body []byte, ts int64) string {
|
||||
mac := hmac.New(sha256.New, secret)
|
||||
_, _ = fmt.Fprintf(mac, "%d.", ts)
|
||||
_, _ = mac.Write(body)
|
||||
return "sha256=" + hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// Send posts ev as JSON.
|
||||
func (w Webhook) Send(ctx context.Context, ev Event) error {
|
||||
body, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, w.URL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ts := time.Now().Unix()
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", "uptimesebi-webhook")
|
||||
req.Header.Set(EventHeader, ev.Kind)
|
||||
req.Header.Set(TimestampHeader, strconv.FormatInt(ts, 10))
|
||||
req.Header.Set(SignatureHeader, Sign(w.Secret, body, ts))
|
||||
d := netguard.Dialer(w.AllowPrivate, 5*time.Second)
|
||||
client := &http.Client{
|
||||
Transport: &http.Transport{DialContext: d.DialContext, DisableKeepAlives: true},
|
||||
// Redirects would bypass the URL the customer configured.
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
|
||||
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
||||
return fmt.Errorf("webhook answered %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SMTP is the outgoing mail server, parsed from a URL like
|
||||
// smtp://user:pass@host:587?from=alerts@example.com&tls=starttls.
|
||||
// tls is starttls (default), tls for implicit TLS, or none.
|
||||
type SMTP struct {
|
||||
Host string
|
||||
Port string
|
||||
Username string
|
||||
Password string
|
||||
From string
|
||||
TLS string
|
||||
}
|
||||
|
||||
// ParseSMTP parses an SMTP URL. An empty string yields nil: mail is off.
|
||||
func ParseSMTP(raw string) (*SMTP, error) {
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Scheme != "smtp" || u.Hostname() == "" {
|
||||
return nil, errors.New("notify: UPTIME_SMTP_URL must look like smtp://user:pass@host:587?from=alerts@example.com")
|
||||
}
|
||||
s := &SMTP{Host: u.Hostname(), Port: u.Port(), From: u.Query().Get("from"), TLS: u.Query().Get("tls")}
|
||||
if s.Port == "" {
|
||||
s.Port = "587"
|
||||
}
|
||||
if s.TLS == "" {
|
||||
s.TLS = "starttls"
|
||||
}
|
||||
if u.User != nil {
|
||||
s.Username = u.User.Username()
|
||||
s.Password, _ = u.User.Password()
|
||||
}
|
||||
if s.From == "" || (s.TLS != "starttls" && s.TLS != "tls" && s.TLS != "none") {
|
||||
return nil, errors.New("notify: UPTIME_SMTP_URL needs ?from= and tls=starttls|tls|none")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Mail is a plain-text message.
|
||||
type Mail struct {
|
||||
To []string
|
||||
Subject string
|
||||
Body string
|
||||
}
|
||||
|
||||
// Send delivers m.
|
||||
func (s *SMTP) Send(ctx context.Context, m Mail) error {
|
||||
addr := net.JoinHostPort(s.Host, s.Port)
|
||||
d := &net.Dialer{Timeout: 10 * time.Second}
|
||||
var conn net.Conn
|
||||
var err error
|
||||
if s.TLS == "tls" {
|
||||
conn, err = (&tls.Dialer{NetDialer: d, Config: &tls.Config{ServerName: s.Host}}).DialContext(ctx, "tcp", addr)
|
||||
} else {
|
||||
conn, err = d.DialContext(ctx, "tcp", addr)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if dl, ok := ctx.Deadline(); ok {
|
||||
_ = conn.SetDeadline(dl)
|
||||
} else {
|
||||
_ = conn.SetDeadline(time.Now().Add(30 * time.Second))
|
||||
}
|
||||
c, err := smtp.NewClient(conn, s.Host)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return err
|
||||
}
|
||||
defer func() { _ = c.Close() }()
|
||||
if s.TLS == "starttls" {
|
||||
if err := c.StartTLS(&tls.Config{ServerName: s.Host}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if s.Username != "" {
|
||||
if err := c.Auth(smtp.PlainAuth("", s.Username, s.Password, s.Host)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := c.Mail(s.From); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, to := range m.To {
|
||||
if err := c.Rcpt(to); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
w, err := c.Data()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := w.Write(compose(s.From, m)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.Quit()
|
||||
}
|
||||
|
||||
func compose(from string, m Mail) []byte {
|
||||
var b bytes.Buffer
|
||||
fmt.Fprintf(&b, "From: %s\r\n", from)
|
||||
fmt.Fprintf(&b, "To: %s\r\n", strings.Join(m.To, ", "))
|
||||
fmt.Fprintf(&b, "Subject: %s\r\n", encodeHeader(m.Subject))
|
||||
fmt.Fprintf(&b, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
|
||||
fmt.Fprintf(&b, "Message-ID: <%s@uptimesebi>\r\n", uuid.NewString())
|
||||
b.WriteString("MIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n")
|
||||
b.WriteString(strings.ReplaceAll(m.Body, "\n", "\r\n"))
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// encodeHeader applies RFC 2047 encoding when the subject is not ASCII.
|
||||
func encodeHeader(s string) string {
|
||||
for _, r := range s {
|
||||
if r > 127 {
|
||||
return mime.QEncoding.Encode("utf-8", s)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify/notifytest"
|
||||
)
|
||||
|
||||
func event() Event {
|
||||
return Event{Kind: Opened, IncidentID: uuid.New(), StartedAt: time.Now(), Monitor: Monitor{ID: uuid.New(), Name: "Shop", Type: "http", Target: "https://shop.test"}}
|
||||
}
|
||||
|
||||
func TestWebhookSignature(t *testing.T) {
|
||||
secret := []byte("s3cret")
|
||||
var got Event
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
ts, _ := strconv.ParseInt(r.Header.Get(TimestampHeader), 10, 64)
|
||||
if r.Header.Get(SignatureHeader) != Sign(secret, body, ts) || r.Header.Get(EventHeader) != Opened {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
_ = json.Unmarshal(body, &got)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
ev := event()
|
||||
if err := (Webhook{URL: srv.URL, Secret: secret, AllowPrivate: true}).Send(context.Background(), ev); err != nil {
|
||||
t.Fatalf("Send() failed: %v", err)
|
||||
}
|
||||
if got.IncidentID != ev.IncidentID || got.Monitor.Name != "Shop" {
|
||||
t.Errorf("received %+v, want %+v", got, ev)
|
||||
}
|
||||
if err := (Webhook{URL: srv.URL, Secret: []byte("wrong"), AllowPrivate: true}).Send(context.Background(), ev); err == nil {
|
||||
t.Error("Send() with a receiver rejecting the signature succeeded")
|
||||
}
|
||||
if err := (Webhook{URL: srv.URL, Secret: secret}).Send(context.Background(), ev); !errors.Is(err, netguard.ErrForbiddenAddress) {
|
||||
t.Errorf("Send() to loopback without AllowPrivate = %v, want %v", err, netguard.ErrForbiddenAddress)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMTP(t *testing.T) {
|
||||
srv := notifytest.NewSMTP(t)
|
||||
s, err := ParseSMTP(srv.URL())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = s.Send(context.Background(), Mail{To: []string{"ops@example.test"}, Subject: "[DOWN] Shöp", Body: "line 1\nline 2"})
|
||||
if err != nil {
|
||||
t.Fatalf("Send() failed: %v", err)
|
||||
}
|
||||
msgs := srv.Messages()
|
||||
if len(msgs) != 1 || msgs[0].To[0] != "ops@example.test" || msgs[0].From != "alerts@uptimesebi.test" {
|
||||
t.Fatalf("received %+v", msgs)
|
||||
}
|
||||
if !strings.Contains(msgs[0].Data, "Subject: =?utf-8?q?[DOWN]_Sh=C3=B6p?=") || !strings.Contains(msgs[0].Data, "line 1\r\nline 2") {
|
||||
t.Errorf("message data = %q", msgs[0].Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSMTP(t *testing.T) {
|
||||
if s, err := ParseSMTP(""); s != nil || err != nil {
|
||||
t.Errorf("ParseSMTP(\"\") = %v, %v; want nil, nil", s, err)
|
||||
}
|
||||
for _, bad := range []string{"http://x", "smtp://host", "smtp://host?from=a@b&tls=maybe"} {
|
||||
if _, err := ParseSMTP(bad); err == nil {
|
||||
t.Errorf("ParseSMTP(%q) accepted", bad)
|
||||
}
|
||||
}
|
||||
s, err := ParseSMTP("smtp://u:p@mail.test?from=a@b.test")
|
||||
if err != nil || s.Port != "587" || s.TLS != "starttls" || s.Password != "p" {
|
||||
t.Errorf("ParseSMTP defaults = %+v, %v", s, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Package notifytest provides an in-memory SMTP server for tests.
|
||||
package notifytest
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Message is one received mail.
|
||||
type Message struct {
|
||||
From string
|
||||
To []string
|
||||
Data string
|
||||
}
|
||||
|
||||
// SMTP accepts mail without authentication or TLS.
|
||||
type SMTP struct {
|
||||
Addr string
|
||||
|
||||
mu sync.Mutex
|
||||
messages []Message
|
||||
}
|
||||
|
||||
// NewSMTP starts a server that stops when t ends.
|
||||
func NewSMTP(t *testing.T) *SMTP {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &SMTP{Addr: ln.Addr().String()}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
go func() {
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go s.serve(conn)
|
||||
}
|
||||
}()
|
||||
return s
|
||||
}
|
||||
|
||||
// Messages returns what was received so far.
|
||||
func (s *SMTP) Messages() []Message {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]Message(nil), s.messages...)
|
||||
}
|
||||
|
||||
// URL returns an UPTIME_SMTP_URL for this server.
|
||||
func (s *SMTP) URL() string { return "smtp://" + s.Addr + "?from=alerts@uptimesebi.test&tls=none" }
|
||||
|
||||
func (s *SMTP) serve(conn net.Conn) {
|
||||
defer func() { _ = conn.Close() }()
|
||||
r := bufio.NewReader(conn)
|
||||
reply := func(line string) { _, _ = conn.Write([]byte(line + "\r\n")) }
|
||||
reply("220 test")
|
||||
var msg Message
|
||||
for {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
cmd := strings.ToUpper(strings.TrimSpace(line))
|
||||
switch {
|
||||
case strings.HasPrefix(cmd, "EHLO"), strings.HasPrefix(cmd, "HELO"):
|
||||
reply("250 test")
|
||||
case strings.HasPrefix(cmd, "MAIL FROM:"):
|
||||
msg = Message{From: strings.Trim(strings.TrimSpace(line)[10:], "<>")}
|
||||
reply("250 ok")
|
||||
case strings.HasPrefix(cmd, "RCPT TO:"):
|
||||
msg.To = append(msg.To, strings.Trim(strings.TrimSpace(line)[8:], "<>"))
|
||||
reply("250 ok")
|
||||
case cmd == "DATA":
|
||||
reply("354 go")
|
||||
var b strings.Builder
|
||||
for {
|
||||
l, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if l == ".\r\n" {
|
||||
break
|
||||
}
|
||||
b.WriteString(l)
|
||||
}
|
||||
msg.Data = b.String()
|
||||
s.mu.Lock()
|
||||
s.messages = append(s.messages, msg)
|
||||
s.mu.Unlock()
|
||||
reply("250 queued")
|
||||
case cmd == "QUIT":
|
||||
reply("221 bye")
|
||||
return
|
||||
default:
|
||||
reply("250 ok")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,44 @@ func (q *Queries) LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestR
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const latestResultsForMonitor = `-- name: LatestResultsForMonitor :many
|
||||
SELECT DISTINCT ON (region) region, ok, error
|
||||
FROM check_results
|
||||
WHERE org_id = $1 AND monitor_id = $2 AND time > now() - interval '1 day'
|
||||
ORDER BY region, time DESC
|
||||
`
|
||||
|
||||
type LatestResultsForMonitorParams struct {
|
||||
OrgID uuid.UUID
|
||||
MonitorID uuid.UUID
|
||||
}
|
||||
|
||||
type LatestResultsForMonitorRow struct {
|
||||
Region string
|
||||
Ok bool
|
||||
Error *string
|
||||
}
|
||||
|
||||
func (q *Queries) LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error) {
|
||||
rows, err := q.db.Query(ctx, latestResultsForMonitor, arg.OrgID, arg.MonitorID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []LatestResultsForMonitorRow{}
|
||||
for rows.Next() {
|
||||
var i LatestResultsForMonitorRow
|
||||
if err := rows.Scan(&i.Region, &i.Ok, &i.Error); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const recentResults = `-- name: RecentResults :many
|
||||
SELECT time, region, ok, latency_ms, status_code, error
|
||||
FROM check_results
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: incidents.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const claimNotifications = `-- name: ClaimNotifications :many
|
||||
UPDATE notifications SET next_attempt_at = now() + interval '5 minutes'
|
||||
WHERE id IN (
|
||||
SELECT id FROM notifications
|
||||
WHERE status = 'pending' AND next_attempt_at <= now()
|
||||
ORDER BY next_attempt_at
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
// System scope. Leases due rows for five minutes so a crashed sender's rows
|
||||
// come back; SKIP LOCKED lets every API replica work the outbox.
|
||||
func (q *Queries) ClaimNotifications(ctx context.Context, max int32) ([]uuid.UUID, error) {
|
||||
rows, err := q.db.Query(ctx, claimNotifications, max)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []uuid.UUID{}
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const createChannel = `-- name: CreateChannel :one
|
||||
INSERT INTO notification_channels (org_id, name, type, config, enabled)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, org_id, name, type, config, enabled, created_at, updated_at
|
||||
`
|
||||
|
||||
type CreateChannelParams struct {
|
||||
OrgID uuid.UUID
|
||||
Name string
|
||||
Type string
|
||||
Config []byte
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
func (q *Queries) CreateChannel(ctx context.Context, arg CreateChannelParams) (NotificationChannel, error) {
|
||||
row := q.db.QueryRow(ctx, createChannel,
|
||||
arg.OrgID,
|
||||
arg.Name,
|
||||
arg.Type,
|
||||
arg.Config,
|
||||
arg.Enabled,
|
||||
)
|
||||
var i NotificationChannel
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Name,
|
||||
&i.Type,
|
||||
&i.Config,
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteChannel = `-- name: DeleteChannel :execrows
|
||||
DELETE FROM notification_channels WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteChannel(ctx context.Context, id uuid.UUID) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, deleteChannel, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const enqueueNotification = `-- name: EnqueueNotification :exec
|
||||
INSERT INTO notifications (org_id, channel_id, incident_id, event)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT DO NOTHING
|
||||
`
|
||||
|
||||
type EnqueueNotificationParams struct {
|
||||
OrgID uuid.UUID
|
||||
ChannelID uuid.UUID
|
||||
IncidentID uuid.UUID
|
||||
Event string
|
||||
}
|
||||
|
||||
func (q *Queries) EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error {
|
||||
_, err := q.db.Exec(ctx, enqueueNotification,
|
||||
arg.OrgID,
|
||||
arg.ChannelID,
|
||||
arg.IncidentID,
|
||||
arg.Event,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const getChannel = `-- name: GetChannel :one
|
||||
SELECT id, org_id, name, type, config, enabled, created_at, updated_at FROM notification_channels WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetChannel(ctx context.Context, id uuid.UUID) (NotificationChannel, error) {
|
||||
row := q.db.QueryRow(ctx, getChannel, id)
|
||||
var i NotificationChannel
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Name,
|
||||
&i.Type,
|
||||
&i.Config,
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listChannels = `-- name: ListChannels :many
|
||||
SELECT id, org_id, name, type, config, enabled, created_at, updated_at FROM notification_channels ORDER BY name
|
||||
`
|
||||
|
||||
func (q *Queries) ListChannels(ctx context.Context) ([]NotificationChannel, error) {
|
||||
rows, err := q.db.Query(ctx, listChannels)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []NotificationChannel{}
|
||||
for rows.Next() {
|
||||
var i NotificationChannel
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Name,
|
||||
&i.Type,
|
||||
&i.Config,
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listEnabledChannelIDs = `-- name: ListEnabledChannelIDs :many
|
||||
SELECT id FROM notification_channels WHERE org_id = $1 AND enabled
|
||||
`
|
||||
|
||||
func (q *Queries) ListEnabledChannelIDs(ctx context.Context, orgID uuid.UUID) ([]uuid.UUID, error) {
|
||||
rows, err := q.db.Query(ctx, listEnabledChannelIDs, orgID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []uuid.UUID{}
|
||||
for rows.Next() {
|
||||
var id uuid.UUID
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listIncidents = `-- name: ListIncidents :many
|
||||
SELECT i.id, i.org_id, i.monitor_id, i.started_at, i.resolved_at, i.cause, m.name AS monitor_name
|
||||
FROM incidents i
|
||||
JOIN monitors m ON m.id = i.monitor_id
|
||||
ORDER BY i.started_at DESC
|
||||
LIMIT 200
|
||||
`
|
||||
|
||||
type ListIncidentsRow struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
MonitorID uuid.UUID
|
||||
StartedAt time.Time
|
||||
ResolvedAt *time.Time
|
||||
Cause []byte
|
||||
MonitorName string
|
||||
}
|
||||
|
||||
func (q *Queries) ListIncidents(ctx context.Context) ([]ListIncidentsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listIncidents)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListIncidentsRow{}
|
||||
for rows.Next() {
|
||||
var i ListIncidentsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.MonitorID,
|
||||
&i.StartedAt,
|
||||
&i.ResolvedAt,
|
||||
&i.Cause,
|
||||
&i.MonitorName,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markNotificationFailed = `-- name: MarkNotificationFailed :exec
|
||||
UPDATE notifications SET attempts = attempts + 1, last_error = $1,
|
||||
status = CASE WHEN attempts + 1 >= $2::int THEN 'failed' ELSE 'pending' END,
|
||||
next_attempt_at = now() + make_interval(secs => $3::int)
|
||||
WHERE id = $4
|
||||
`
|
||||
|
||||
type MarkNotificationFailedParams struct {
|
||||
LastError *string
|
||||
MaxAttempts int32
|
||||
RetryInSeconds int32
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) MarkNotificationFailed(ctx context.Context, arg MarkNotificationFailedParams) error {
|
||||
_, err := q.db.Exec(ctx, markNotificationFailed,
|
||||
arg.LastError,
|
||||
arg.MaxAttempts,
|
||||
arg.RetryInSeconds,
|
||||
arg.ID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const markNotificationSent = `-- name: MarkNotificationSent :exec
|
||||
UPDATE notifications SET status = 'sent', sent_at = now(), attempts = attempts + 1, last_error = NULL
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) MarkNotificationSent(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, markNotificationSent, id)
|
||||
return err
|
||||
}
|
||||
|
||||
const notificationDetails = `-- name: NotificationDetails :many
|
||||
SELECT n.id, n.org_id, n.event, n.attempts,
|
||||
c.type AS channel_type, c.config AS channel_config, c.id AS channel_id,
|
||||
i.id AS incident_id, i.started_at, i.resolved_at, i.cause,
|
||||
m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type
|
||||
FROM notifications n
|
||||
JOIN notification_channels c ON c.id = n.channel_id
|
||||
JOIN incidents i ON i.id = n.incident_id
|
||||
JOIN monitors m ON m.id = i.monitor_id
|
||||
WHERE n.id = ANY ($1::uuid[])
|
||||
`
|
||||
|
||||
type NotificationDetailsRow struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Event string
|
||||
Attempts int32
|
||||
ChannelType string
|
||||
ChannelConfig []byte
|
||||
ChannelID uuid.UUID
|
||||
IncidentID uuid.UUID
|
||||
StartedAt time.Time
|
||||
ResolvedAt *time.Time
|
||||
Cause []byte
|
||||
MonitorID uuid.UUID
|
||||
MonitorName string
|
||||
MonitorTarget string
|
||||
MonitorType string
|
||||
}
|
||||
|
||||
// System scope.
|
||||
func (q *Queries) NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]NotificationDetailsRow, error) {
|
||||
rows, err := q.db.Query(ctx, notificationDetails, ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []NotificationDetailsRow{}
|
||||
for rows.Next() {
|
||||
var i NotificationDetailsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Event,
|
||||
&i.Attempts,
|
||||
&i.ChannelType,
|
||||
&i.ChannelConfig,
|
||||
&i.ChannelID,
|
||||
&i.IncidentID,
|
||||
&i.StartedAt,
|
||||
&i.ResolvedAt,
|
||||
&i.Cause,
|
||||
&i.MonitorID,
|
||||
&i.MonitorName,
|
||||
&i.MonitorTarget,
|
||||
&i.MonitorType,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const openIncident = `-- name: OpenIncident :one
|
||||
INSERT INTO incidents (org_id, monitor_id, started_at, cause)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (monitor_id) WHERE resolved_at IS NULL DO NOTHING
|
||||
RETURNING id, org_id, monitor_id, started_at, resolved_at, cause
|
||||
`
|
||||
|
||||
type OpenIncidentParams struct {
|
||||
OrgID uuid.UUID
|
||||
MonitorID uuid.UUID
|
||||
StartedAt time.Time
|
||||
Cause []byte
|
||||
}
|
||||
|
||||
func (q *Queries) OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error) {
|
||||
row := q.db.QueryRow(ctx, openIncident,
|
||||
arg.OrgID,
|
||||
arg.MonitorID,
|
||||
arg.StartedAt,
|
||||
arg.Cause,
|
||||
)
|
||||
var i Incident
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.MonitorID,
|
||||
&i.StartedAt,
|
||||
&i.ResolvedAt,
|
||||
&i.Cause,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const resolveIncident = `-- name: ResolveIncident :one
|
||||
UPDATE incidents SET resolved_at = $1
|
||||
WHERE monitor_id = $2 AND resolved_at IS NULL
|
||||
RETURNING id, org_id, monitor_id, started_at, resolved_at, cause
|
||||
`
|
||||
|
||||
type ResolveIncidentParams struct {
|
||||
ResolvedAt *time.Time
|
||||
MonitorID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ResolveIncident(ctx context.Context, arg ResolveIncidentParams) (Incident, error) {
|
||||
row := q.db.QueryRow(ctx, resolveIncident, arg.ResolvedAt, arg.MonitorID)
|
||||
var i Incident
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.MonitorID,
|
||||
&i.StartedAt,
|
||||
&i.ResolvedAt,
|
||||
&i.Cause,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const updateChannel = `-- name: UpdateChannel :one
|
||||
UPDATE notification_channels SET name = $2, config = $3, enabled = $4, updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING id, org_id, name, type, config, enabled, created_at, updated_at
|
||||
`
|
||||
|
||||
type UpdateChannelParams struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
Config []byte
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error) {
|
||||
row := q.db.QueryRow(ctx, updateChannel,
|
||||
arg.ID,
|
||||
arg.Name,
|
||||
arg.Config,
|
||||
arg.Enabled,
|
||||
)
|
||||
var i NotificationChannel
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Name,
|
||||
&i.Type,
|
||||
&i.Config,
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -70,6 +70,15 @@ type CheckResults1h struct {
|
||||
MaxLatencyMs interface{}
|
||||
}
|
||||
|
||||
type Incident struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
MonitorID uuid.UUID
|
||||
StartedAt time.Time
|
||||
ResolvedAt *time.Time
|
||||
Cause []byte
|
||||
}
|
||||
|
||||
type Invitation struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
@@ -101,6 +110,7 @@ type Monitor struct {
|
||||
Enabled bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Confirmations int32
|
||||
}
|
||||
|
||||
type MonitorRegion struct {
|
||||
@@ -109,6 +119,31 @@ type MonitorRegion struct {
|
||||
Region string
|
||||
}
|
||||
|
||||
type Notification struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
ChannelID uuid.UUID
|
||||
IncidentID uuid.UUID
|
||||
Event string
|
||||
Status string
|
||||
Attempts int32
|
||||
NextAttemptAt time.Time
|
||||
LastError *string
|
||||
CreatedAt time.Time
|
||||
SentAt *time.Time
|
||||
}
|
||||
|
||||
type NotificationChannel struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Name string
|
||||
Type string
|
||||
Config []byte
|
||||
Enabled bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Org struct {
|
||||
ID uuid.UUID
|
||||
Slug string
|
||||
|
||||
@@ -56,9 +56,9 @@ func (q *Queries) AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow
|
||||
}
|
||||
|
||||
const createMonitor = `-- name: CreateMonitor :one
|
||||
INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at
|
||||
INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations
|
||||
`
|
||||
|
||||
type CreateMonitorParams struct {
|
||||
@@ -70,6 +70,7 @@ type CreateMonitorParams struct {
|
||||
TimeoutMs int32
|
||||
Config []byte
|
||||
Enabled bool
|
||||
Confirmations int32
|
||||
}
|
||||
|
||||
func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error) {
|
||||
@@ -82,6 +83,7 @@ func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (M
|
||||
arg.TimeoutMs,
|
||||
arg.Config,
|
||||
arg.Enabled,
|
||||
arg.Confirmations,
|
||||
)
|
||||
var i Monitor
|
||||
err := row.Scan(
|
||||
@@ -96,6 +98,7 @@ func (q *Queries) CreateMonitor(ctx context.Context, arg CreateMonitorParams) (M
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -122,7 +125,7 @@ func (q *Queries) DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID)
|
||||
}
|
||||
|
||||
const getMonitor = `-- name: GetMonitor :one
|
||||
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at FROM monitors WHERE id = $1
|
||||
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations FROM monitors WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error) {
|
||||
@@ -140,6 +143,7 @@ func (q *Queries) GetMonitor(ctx context.Context, id uuid.UUID) (Monitor, error)
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -181,7 +185,7 @@ func (q *Queries) ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEna
|
||||
}
|
||||
|
||||
const listMonitors = `-- name: ListMonitors :many
|
||||
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at FROM monitors ORDER BY name
|
||||
SELECT id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations FROM monitors ORDER BY name
|
||||
`
|
||||
|
||||
func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) {
|
||||
@@ -205,6 +209,7 @@ func (q *Queries) ListMonitors(ctx context.Context) ([]Monitor, error) {
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -241,7 +246,7 @@ func (q *Queries) MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]st
|
||||
}
|
||||
|
||||
const monitorsForJobs = `-- name: MonitorsForJobs :many
|
||||
SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at FROM monitors m
|
||||
SELECT m.id, m.org_id, m.name, m.type, m.target, m.interval_seconds, m.timeout_ms, m.config, m.enabled, m.created_at, m.updated_at, m.confirmations FROM monitors m
|
||||
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = $1
|
||||
WHERE m.id = ANY ($2::uuid[]) AND m.enabled
|
||||
`
|
||||
@@ -274,6 +279,60 @@ func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const monitorsForResults = `-- name: MonitorsForResults :many
|
||||
SELECT m.id, m.org_id, m.name, m.target, m.interval_seconds, m.confirmations,
|
||||
(SELECT array_agg(r2.region ORDER BY r2.region) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions
|
||||
FROM monitors m
|
||||
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = $1
|
||||
WHERE m.id = ANY ($2::uuid[]) AND m.enabled
|
||||
`
|
||||
|
||||
type MonitorsForResultsParams struct {
|
||||
Region string
|
||||
Ids []uuid.UUID
|
||||
}
|
||||
|
||||
type MonitorsForResultsRow struct {
|
||||
ID uuid.UUID
|
||||
OrgID uuid.UUID
|
||||
Name string
|
||||
Target string
|
||||
IntervalSeconds int32
|
||||
Confirmations int32
|
||||
Regions []string
|
||||
}
|
||||
|
||||
// System scope: monitors a checker of region may report, with every region
|
||||
// they are assigned to, for evaluation.
|
||||
func (q *Queries) MonitorsForResults(ctx context.Context, arg MonitorsForResultsParams) ([]MonitorsForResultsRow, error) {
|
||||
rows, err := q.db.Query(ctx, monitorsForResults, arg.Region, arg.Ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []MonitorsForResultsRow{}
|
||||
for rows.Next() {
|
||||
var i MonitorsForResultsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.Name,
|
||||
&i.Target,
|
||||
&i.IntervalSeconds,
|
||||
&i.Confirmations,
|
||||
&i.Regions,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -287,9 +346,9 @@ func (q *Queries) MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams
|
||||
|
||||
const updateMonitor = `-- name: UpdateMonitor :one
|
||||
UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5,
|
||||
timeout_ms = $6, config = $7, enabled = $8, updated_at = now()
|
||||
timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at
|
||||
RETURNING id, org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, created_at, updated_at, confirmations
|
||||
`
|
||||
|
||||
type UpdateMonitorParams struct {
|
||||
@@ -301,6 +360,7 @@ type UpdateMonitorParams struct {
|
||||
TimeoutMs int32
|
||||
Config []byte
|
||||
Enabled bool
|
||||
Confirmations int32
|
||||
}
|
||||
|
||||
func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error) {
|
||||
@@ -313,6 +373,7 @@ func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (M
|
||||
arg.TimeoutMs,
|
||||
arg.Config,
|
||||
arg.Enabled,
|
||||
arg.Confirmations,
|
||||
)
|
||||
var i Monitor
|
||||
err := row.Scan(
|
||||
@@ -327,6 +388,7 @@ func (q *Queries) UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (M
|
||||
&i.Enabled,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Confirmations,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -16,6 +16,9 @@ type Querier interface {
|
||||
AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error
|
||||
AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error)
|
||||
AnyUserExists(ctx context.Context) (bool, error)
|
||||
// System scope. Leases due rows for five minutes so a crashed sender's rows
|
||||
// come back; SKIP LOCKED lets every API replica work the outbox.
|
||||
ClaimNotifications(ctx context.Context, max int32) ([]uuid.UUID, error)
|
||||
// Shortens tokens that would outlive a newly set maximum lifetime.
|
||||
ClampAPITokenExpiry(ctx context.Context, arg ClampAPITokenExpiryParams) (int64, error)
|
||||
CountRoleAssignments(ctx context.Context, roleID uuid.UUID) (int64, error)
|
||||
@@ -23,6 +26,7 @@ type Querier interface {
|
||||
CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error)
|
||||
CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error)
|
||||
CreateAssignment(ctx context.Context, arg CreateAssignmentParams) (RoleAssignment, error)
|
||||
CreateChannel(ctx context.Context, arg CreateChannelParams) (NotificationChannel, error)
|
||||
CreateIdentity(ctx context.Context, arg CreateIdentityParams) error
|
||||
CreateInvitation(ctx context.Context, arg CreateInvitationParams) (Invitation, error)
|
||||
CreateMonitor(ctx context.Context, arg CreateMonitorParams) (Monitor, error)
|
||||
@@ -33,6 +37,7 @@ type Querier interface {
|
||||
DeleteAPIToken(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DeleteAgent(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DeleteAssignment(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DeleteChannel(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DeleteInvitation(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DeleteMonitor(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error
|
||||
@@ -43,10 +48,12 @@ type Querier interface {
|
||||
DeleteUser(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
DisableTOTP(ctx context.Context, id uuid.UUID) error
|
||||
EnableTOTP(ctx context.Context, arg EnableTOTPParams) error
|
||||
EnqueueNotification(ctx context.Context, arg EnqueueNotificationParams) error
|
||||
GetAPIToken(ctx context.Context, id uuid.UUID) (ApiToken, error)
|
||||
GetAPITokenByHash(ctx context.Context, tokenHash []byte) (ApiToken, error)
|
||||
GetAgentByHash(ctx context.Context, tokenHash []byte) (Agent, error)
|
||||
GetAssignment(ctx context.Context, id uuid.UUID) (RoleAssignment, error)
|
||||
GetChannel(ctx context.Context, id uuid.UUID) (NotificationChannel, error)
|
||||
GetIdentity(ctx context.Context, arg GetIdentityParams) (UserIdentity, error)
|
||||
GetInvitation(ctx context.Context, id uuid.UUID) (Invitation, error)
|
||||
GetInvitationByHash(ctx context.Context, tokenHash []byte) (GetInvitationByHashRow, error)
|
||||
@@ -66,13 +73,17 @@ type Querier interface {
|
||||
IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
|
||||
// Newest result per monitor and region in the org.
|
||||
LatestResults(ctx context.Context, orgID uuid.UUID) ([]LatestResultsRow, error)
|
||||
LatestResultsForMonitor(ctx context.Context, arg LatestResultsForMonitorParams) ([]LatestResultsForMonitorRow, error)
|
||||
ListAPITokens(ctx context.Context, arg ListAPITokensParams) ([]ListAPITokensRow, error)
|
||||
ListAgents(ctx context.Context) ([]Agent, error)
|
||||
ListAssignments(ctx context.Context, orgID uuid.UUID) ([]ListAssignmentsRow, error)
|
||||
ListChannels(ctx context.Context) ([]NotificationChannel, error)
|
||||
ListEnabledChannelIDs(ctx context.Context, orgID uuid.UUID) ([]uuid.UUID, error)
|
||||
// System scope: every enabled monitor with its regions, for reconciling the
|
||||
// schedule.
|
||||
ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEnabledMonitorsForScheduleRow, error)
|
||||
ListEnabledSSOProviders(ctx context.Context) ([]ListEnabledSSOProvidersRow, error)
|
||||
ListIncidents(ctx context.Context) ([]ListIncidentsRow, error)
|
||||
ListMonitors(ctx context.Context) ([]Monitor, error)
|
||||
ListOrgMembers(ctx context.Context, orgID uuid.UUID) ([]ListOrgMembersRow, error)
|
||||
ListOrgs(ctx context.Context) ([]Org, error)
|
||||
@@ -83,20 +94,30 @@ type Querier interface {
|
||||
ListUserIdentitiesInOrg(ctx context.Context, userID uuid.UUID) ([]ListUserIdentitiesInOrgRow, error)
|
||||
ListUserOrgs(ctx context.Context, userID uuid.UUID) ([]ListUserOrgsRow, error)
|
||||
MarkInvitationAccepted(ctx context.Context, id uuid.UUID) (int64, error)
|
||||
MarkNotificationFailed(ctx context.Context, arg MarkNotificationFailedParams) error
|
||||
MarkNotificationSent(ctx context.Context, id uuid.UUID) error
|
||||
// Every role a member holds, with the scope it applies to.
|
||||
MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error)
|
||||
MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]string, error)
|
||||
// System scope: monitors to hand to a checker of region, skipping ones that
|
||||
// were disabled, deleted or moved out of the region since dispatch.
|
||||
MonitorsForJobs(ctx context.Context, arg MonitorsForJobsParams) ([]Monitor, error)
|
||||
// System scope: monitors a checker of region may report, with every region
|
||||
// they are assigned to, for evaluation.
|
||||
MonitorsForResults(ctx context.Context, arg MonitorsForResultsParams) ([]MonitorsForResultsRow, error)
|
||||
// System scope.
|
||||
NotificationDetails(ctx context.Context, ids []uuid.UUID) ([]NotificationDetailsRow, error)
|
||||
OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error)
|
||||
OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error)
|
||||
RecentResults(ctx context.Context, arg RecentResultsParams) ([]RecentResultsRow, error)
|
||||
RemoveMembership(ctx context.Context, arg RemoveMembershipParams) (int64, error)
|
||||
ResolveIncident(ctx context.Context, arg ResolveIncidentParams) (Incident, error)
|
||||
SetPasswordHash(ctx context.Context, arg SetPasswordHashParams) error
|
||||
SetUserLocale(ctx context.Context, arg SetUserLocaleParams) error
|
||||
TouchAPIToken(ctx context.Context, id uuid.UUID) error
|
||||
TouchAgent(ctx context.Context, arg TouchAgentParams) error
|
||||
TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
|
||||
UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error)
|
||||
UpdateMonitor(ctx context.Context, arg UpdateMonitorParams) (Monitor, error)
|
||||
UpdateOrgPolicy(ctx context.Context, arg UpdateOrgPolicyParams) (Org, error)
|
||||
UpdateRole(ctx context.Context, arg UpdateRoleParams) (Role, error)
|
||||
|
||||
@@ -26,3 +26,9 @@ SELECT monitor_id, sum(total)::bigint AS total, sum(ok_count)::bigint AS ok_coun
|
||||
FROM check_results_1h
|
||||
WHERE org_id = $1 AND bucket >= $2
|
||||
GROUP BY monitor_id;
|
||||
|
||||
-- name: LatestResultsForMonitor :many
|
||||
SELECT DISTINCT ON (region) region, ok, error
|
||||
FROM check_results
|
||||
WHERE org_id = $1 AND monitor_id = $2 AND time > now() - interval '1 day'
|
||||
ORDER BY region, time DESC;
|
||||
@@ -0,0 +1,79 @@
|
||||
-- name: OpenIncident :one
|
||||
INSERT INTO incidents (org_id, monitor_id, started_at, cause)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT (monitor_id) WHERE resolved_at IS NULL DO NOTHING
|
||||
RETURNING *;
|
||||
|
||||
-- name: ResolveIncident :one
|
||||
UPDATE incidents SET resolved_at = sqlc.arg(resolved_at)
|
||||
WHERE monitor_id = sqlc.arg(monitor_id) AND resolved_at IS NULL
|
||||
RETURNING *;
|
||||
|
||||
-- name: ListIncidents :many
|
||||
SELECT i.*, m.name AS monitor_name
|
||||
FROM incidents i
|
||||
JOIN monitors m ON m.id = i.monitor_id
|
||||
ORDER BY i.started_at DESC
|
||||
LIMIT 200;
|
||||
|
||||
-- name: ListEnabledChannelIDs :many
|
||||
SELECT id FROM notification_channels WHERE org_id = $1 AND enabled;
|
||||
|
||||
-- name: EnqueueNotification :exec
|
||||
INSERT INTO notifications (org_id, channel_id, incident_id, event)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- name: ClaimNotifications :many
|
||||
-- System scope. Leases due rows for five minutes so a crashed sender's rows
|
||||
-- come back; SKIP LOCKED lets every API replica work the outbox.
|
||||
UPDATE notifications SET next_attempt_at = now() + interval '5 minutes'
|
||||
WHERE id IN (
|
||||
SELECT id FROM notifications
|
||||
WHERE status = 'pending' AND next_attempt_at <= now()
|
||||
ORDER BY next_attempt_at
|
||||
LIMIT sqlc.arg(max)
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING id;
|
||||
|
||||
-- name: NotificationDetails :many
|
||||
-- System scope.
|
||||
SELECT n.id, n.org_id, n.event, n.attempts,
|
||||
c.type AS channel_type, c.config AS channel_config, c.id AS channel_id,
|
||||
i.id AS incident_id, i.started_at, i.resolved_at, i.cause,
|
||||
m.id AS monitor_id, m.name AS monitor_name, m.target AS monitor_target, m.type AS monitor_type
|
||||
FROM notifications n
|
||||
JOIN notification_channels c ON c.id = n.channel_id
|
||||
JOIN incidents i ON i.id = n.incident_id
|
||||
JOIN monitors m ON m.id = i.monitor_id
|
||||
WHERE n.id = ANY (sqlc.arg(ids)::uuid[]);
|
||||
|
||||
-- name: MarkNotificationSent :exec
|
||||
UPDATE notifications SET status = 'sent', sent_at = now(), attempts = attempts + 1, last_error = NULL
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: MarkNotificationFailed :exec
|
||||
UPDATE notifications SET attempts = attempts + 1, last_error = sqlc.arg(last_error),
|
||||
status = CASE WHEN attempts + 1 >= sqlc.arg(max_attempts)::int THEN 'failed' ELSE 'pending' END,
|
||||
next_attempt_at = now() + make_interval(secs => sqlc.arg(retry_in_seconds)::int)
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
-- name: CreateChannel :one
|
||||
INSERT INTO notification_channels (org_id, name, type, config, enabled)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING *;
|
||||
|
||||
-- name: UpdateChannel :one
|
||||
UPDATE notification_channels SET name = $2, config = $3, enabled = $4, updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *;
|
||||
|
||||
-- name: GetChannel :one
|
||||
SELECT * FROM notification_channels WHERE id = $1;
|
||||
|
||||
-- name: ListChannels :many
|
||||
SELECT * FROM notification_channels ORDER BY name;
|
||||
|
||||
-- name: DeleteChannel :execrows
|
||||
DELETE FROM notification_channels WHERE id = $1;
|
||||
@@ -1,11 +1,11 @@
|
||||
-- name: CreateMonitor :one
|
||||
INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
INSERT INTO monitors (org_id, name, type, target, interval_seconds, timeout_ms, config, enabled, confirmations)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
RETURNING *;
|
||||
|
||||
-- name: UpdateMonitor :one
|
||||
UPDATE monitors SET name = $2, type = $3, target = $4, interval_seconds = $5,
|
||||
timeout_ms = $6, config = $7, enabled = $8, updated_at = now()
|
||||
timeout_ms = $6, config = $7, enabled = $8, confirmations = $9, updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *;
|
||||
|
||||
@@ -45,3 +45,12 @@ GROUP BY m.id, m.interval_seconds;
|
||||
SELECT m.* FROM monitors m
|
||||
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = sqlc.arg(region)
|
||||
WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled;
|
||||
|
||||
-- name: MonitorsForResults :many
|
||||
-- System scope: monitors a checker of region may report, with every region
|
||||
-- they are assigned to, for evaluation.
|
||||
SELECT m.id, m.org_id, m.name, m.target, m.interval_seconds, m.confirmations,
|
||||
(SELECT array_agg(r2.region ORDER BY r2.region) FROM monitor_regions r2 WHERE r2.monitor_id = m.id)::text[] AS regions
|
||||
FROM monitors m
|
||||
JOIN monitor_regions r ON r.monitor_id = m.id AND r.region = sqlc.arg(region)
|
||||
WHERE m.id = ANY (sqlc.arg(ids)::uuid[]) AND m.enabled;
|
||||
Reference in new issue
Block a user