-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathalerting.go
More file actions
67 lines (54 loc) · 1.6 KB
/
Copy pathalerting.go
File metadata and controls
67 lines (54 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"bytes"
"io"
"log"
"net/http"
"sync"
"sync/atomic"
"github.com/VictoriaMetrics/metrics"
)
var demoAlertFire = atomic.Int64{}
var alertingWebhooksMutex sync.Mutex
var alertingWebhooks [][]byte
func initAlerting() {
metrics.NewGauge(`demo_alert_firing`, func() float64 {
return float64(demoAlertFire.Load())
})
http.Handle("/alerting/webhook", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
b, err := io.ReadAll(r.Body)
if err != nil {
log.Printf("Error reading body: %s", err)
http.Error(rw, "cannot read body", http.StatusBadRequest)
return
}
alertingWebhooksMutex.Lock()
if len(alertingWebhooks) > 100 {
alertingWebhooks = alertingWebhooks[1:]
}
alertingWebhooks = append(alertingWebhooks, bytes.TrimSpace(b))
alertingWebhooksMutex.Unlock()
rw.WriteHeader(http.StatusNoContent)
}))
http.Handle("/alerting/receivedWebhooks", http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
rw.WriteHeader(http.StatusOK)
alertingWebhooksMutex.Lock()
for _, webhook := range alertingWebhooks {
if _, err := rw.Write(webhook); err != nil {
log.Printf("Error writing webhook: %s", err)
break
}
if _, err := rw.Write([]byte("\n")); err != nil {
log.Printf("Error writing webhook: %s", err)
break
}
}
alertingWebhooksMutex.Unlock()
}))
http.Handle("/alerting/fireDemoAlert", http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
demoAlertFire.Store(1)
}))
http.Handle("/alerting/resolveDemoAlert", http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
demoAlertFire.Store(0)
}))
}