-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathserver.go
More file actions
320 lines (273 loc) · 8.5 KB
/
Copy pathserver.go
File metadata and controls
320 lines (273 loc) · 8.5 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package server
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
urlpkg "net/url"
"strings"
"text/template"
"github.com/alexbakker/alertmanager-ntfy/internal/alertmanager"
"github.com/alexbakker/alertmanager-ntfy/internal/config"
ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
keyRequestID = "request_id"
)
type Server struct {
e *gin.Engine
cfg *config.Config
logger *zap.Logger
http *http.Client
}
func New(logger *zap.Logger, cfg *config.Config) *Server {
gin.SetMode(gin.ReleaseMode)
e := gin.New()
e.Use(func(c *gin.Context) {
// If there's no X-Request-Id in the headers, we generate one ourselves
// so that we can correlate log lines to a single request
var requestID string
if requestID = c.Writer.Header().Get("X-Request-Id"); requestID == "" {
requestID = generateRequestID()
}
c.Set(keyRequestID, requestID)
c.Next()
})
e.Use(ginzap.GinzapWithConfig(logger, &ginzap.Config{
Context: ginzap.Fn(func(c *gin.Context) []zapcore.Field {
requestID, ok := c.Get("request_id")
if !ok {
panic("request_id is not set in gin context")
}
return []zapcore.Field{zap.String(keyRequestID, requestID.(string))}
}),
}))
e.Use(ginzap.RecoveryWithZap(logger, true))
s := Server{
e: e,
cfg: cfg,
logger: logger,
http: &http.Client{Timeout: cfg.Ntfy.Timeout},
}
if cfg.HTTP.Auth.Valid() {
s.e.POST("/hook", gin.BasicAuth(gin.Accounts{cfg.HTTP.Auth.Username: cfg.HTTP.Auth.Password}), s.handleWebhook)
} else {
logger.Warn("Basic auth is disabled")
s.e.POST("/hook", s.handleWebhook)
}
s.e.GET("/health", s.handleHealthCheck)
return &s
}
func (s *Server) handleHealthCheck(c *gin.Context) {
logger := s.logger
if requestID, ok := c.Get(keyRequestID); ok {
logger = logger.With(zap.String(keyRequestID, requestID.(string)))
}
logger.Debug("Handling healthcheck")
c.JSON(200, gin.H{
"status": "OK",
})
}
func (s *Server) handleWebhook(c *gin.Context) {
logger := s.logger
if requestID, ok := c.Get(keyRequestID); ok {
logger = logger.With(zap.String(keyRequestID, requestID.(string)))
}
logger.Info("Handling webhook")
var payload alertmanager.Payload
if err := json.NewDecoder(c.Request.Body).Decode(&payload); err != nil {
logger.Error("Failed to unmarshal webhook payload", zap.Error(err))
c.Status(http.StatusBadRequest)
return
}
if len(payload.Alerts) == 0 {
logger.Warn("Received an empty list of alerts")
c.Status(http.StatusOK)
return
}
if !s.cfg.Ntfy.Async {
if s.forwardAlerts(logger, &payload) {
c.Status(http.StatusOK)
} else {
c.Status(http.StatusBadGateway)
}
return
}
go s.forwardAlerts(logger, &payload)
c.Status(http.StatusAccepted)
}
func (s *Server) forwardAlerts(logger *zap.Logger, payload *alertmanager.Payload) bool {
success := true
for _, alert := range payload.Alerts {
logger := logger.With(zap.String("alert_fingerprint", alert.Fingerprint))
if err := s.forwardAlert(logger, payload, alert); err != nil {
logger.Error("Failed to forward alert to ntfy", zap.Error(err))
success = false
} else {
logger.Info("Successfully forwarded alert to ntfy")
}
}
return success
}
func (s *Server) forwardAlert(logger *zap.Logger, payload *alertmanager.Payload, alert *alertmanager.Alert) error {
tmplCtx := templateContext{Alert: alert, Payload: payload}
var titleBuf bytes.Buffer
if err := (*template.Template)(s.cfg.Ntfy.Notification.Templates.Title).Execute(&titleBuf, &tmplCtx); err != nil {
return fmt.Errorf("render title template: %w", err)
}
title := strings.TrimSpace(titleBuf.String())
var descBuf bytes.Buffer
if err := (*template.Template)(s.cfg.Ntfy.Notification.Templates.Description).Execute(&descBuf, &tmplCtx); err != nil {
return fmt.Errorf("render description template: %w", err)
}
description := strings.TrimSpace(descBuf.String())
// If the description is empty, send the title as the description so that
// the ntfy app doesn't fall back to setting "triggered" as the description.
if description == "" {
description = title
title = ""
}
url, err := s.getUrl(alert, payload)
if err != nil {
return err
}
req, err := http.NewRequest("POST", url.String(), strings.NewReader(description))
if err != nil {
return fmt.Errorf("http request: %w", err)
}
if s.cfg.Ntfy.Auth != nil {
if s.cfg.Ntfy.Auth.BasicAuth.Valid() {
req.SetBasicAuth(s.cfg.Ntfy.Auth.BasicAuth.Username, s.cfg.Ntfy.Auth.BasicAuth.Password)
} else if s.cfg.Ntfy.Auth.Token != nil && *s.cfg.Ntfy.Auth.Token != "" {
req.Header.Add("Authorization", "Bearer "+*s.cfg.Ntfy.Auth.Token)
}
}
var tags []string
for _, tag := range s.cfg.Ntfy.Notification.Tags {
if tag.Condition != nil {
match, err := tag.Condition.Evaluable.EvalBool(context.Background(), exprMap(alert, payload))
if err != nil {
// Expression evaluation errors should not prevent the notification from being sent
logger.Warn(
"Tag condition expression evaluation failed",
zap.String("expression", tag.Condition.Text),
zap.Error(err),
)
continue
}
if !match {
continue
}
}
tags = append(tags, tag.Tag)
}
labelTags, err := s.renderLabelsTemplate(&tmplCtx)
if err != nil {
logger.Warn(
"Labels template rendering failed, falling back to default format",
zap.Error(err),
)
labelTags = convertLabelsToTags(alert.Labels)
}
tags = append(tags, labelTags...)
if title != "" {
req.Header.Set("X-Title", title)
}
if len(tags) > 0 {
req.Header.Set("X-Tags", strings.Join(tags, tagSeparator))
}
if s.cfg.Ntfy.Notification.Priority != nil {
priority, err := evalStringExpr(s.cfg.Ntfy.Notification.Priority, alert, payload)
if err != nil {
// Expression evaluation errors should not prevent the notification from being sent
logger.Warn(
"Priority expression evaluation failed",
zap.String("expression", s.cfg.Ntfy.Notification.Priority.Expression.Text),
zap.Error(err),
)
}
if priority != "" {
req.Header.Set("X-Priority", priority)
}
}
for headerName, headerTemplate := range s.cfg.Ntfy.Notification.Templates.Headers {
var headerBuf bytes.Buffer
if err := (*template.Template)(headerTemplate).Execute(&headerBuf, &tmplCtx); err != nil {
return fmt.Errorf("render header %s template: %w", headerName, err)
}
headerValue := strings.ReplaceAll(strings.TrimSpace(headerBuf.String()), "\n", "")
req.Header.Set(headerName, headerValue)
}
res, err := s.http.Do(req)
if err != nil {
return fmt.Errorf("http request: %w", err)
}
defer res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
body, _ := io.ReadAll(io.LimitReader(res.Body, 1024))
logger.Error(
"ntfy returned non-2xx response",
zap.Int("status", res.StatusCode),
zap.String("response_body", string(body)),
zap.String("url", req.URL.String()),
zap.Any("headers", req.Header),
zap.String("body", description),
)
return fmt.Errorf("http %d: %s", res.StatusCode, string(body))
}
return nil
}
func (s *Server) Run(addr string) error {
return s.e.Run(addr)
}
func (s *Server) getUrl(alert *alertmanager.Alert, payload *alertmanager.Payload) (*urlpkg.URL, error) {
url, err := urlpkg.Parse(s.cfg.Ntfy.BaseURL)
if err != nil {
return nil, err
}
topic, err := evalStringExpr(&s.cfg.Ntfy.Notification.Topic, alert, payload)
if err != nil {
return nil, fmt.Errorf("topic expression eval: %w", err)
}
if topic == "" {
return nil, errors.New("topic is empty")
}
url.Path, err = urlpkg.JoinPath(url.Path, topic)
if err != nil {
return nil, fmt.Errorf("url path join: %w", err)
}
return url, nil
}
func evalStringExpr(expr *config.StringExpression, alert *alertmanager.Alert, payload *alertmanager.Payload) (string, error) {
if expr.Expression != nil {
return expr.Expression.Evaluable.EvalString(context.Background(), exprMap(alert, payload))
}
return expr.Text, nil
}
func (s *Server) renderLabelsTemplate(ctx *templateContext) ([]string, error) {
if s.cfg.Ntfy.Notification.Templates.Labels == nil {
return convertLabelsToTags(ctx.Labels), nil
}
var labelsBuf bytes.Buffer
if err := (*template.Template)(s.cfg.Ntfy.Notification.Templates.Labels).Execute(&labelsBuf, ctx); err != nil {
return nil, fmt.Errorf("render labels template: %w", err)
}
renderedLabels := strings.TrimSpace(labelsBuf.String())
if renderedLabels == "" {
return []string{}, nil
}
var tags []string
for _, tag := range strings.Split(renderedLabels, tagSeparator) {
tag = strings.TrimSpace(tag)
if tag != "" {
tags = append(tags, tag)
}
}
return tags, nil
}