feat(api): open incidents and notify channels when monitors go down
Results are evaluated as they arrive. Transitions open or resolve the monitor's incident and queue a notification per enabled channel in the same transaction; every API replica delivers the outbox with leases and exponential retries. Organizations manage webhook and email channels, can send test notifications and list incidents. Email requires UPTIME_SMTP_URL. Closes #14 Closes #15 Closes #16 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
01ef543e62
commit
5f42e3e650
12 files changed
+822
-13
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user