File size: 5,728 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package grafana

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"text/template"
	"time"

	"github.com/pkg/errors"
	"github.com/target/goalert/alert"
	"github.com/target/goalert/integrationkey"
	"github.com/target/goalert/permission"
	"github.com/target/goalert/retry"
	"github.com/target/goalert/util/errutil"
	"github.com/target/goalert/util/log"
	"github.com/target/goalert/validation/validate"
)

var detailsTmpl = template.Must(template.New("details").Funcs(template.FuncMap{
	"escapeTableCell": func(s string) string {
		s = strings.ReplaceAll(s, "\n", "<br />")
		s = strings.ReplaceAll(s, "|", "\\|")
		return s
	},
	"codeBlock": func(s string) string {
		delim := "```"
		for strings.Contains(s, delim) {
			delim += "`"
		}

		return delim + "\n" + s + "\n" + delim
	},
}).Parse(`
{{- if .Labels }}
| Label | Value |
| ----- | ----- |
{{- range $k, $v := .Labels }}
| {{ $k }} | {{escapeTableCell $v }} |
{{- end }}
{{- end }}


{{- if .Annotations }}
| Annotation | Value |
| ---------- | ----- |
{{- range $k, $v := .Annotations }}
| {{ $k }} | {{escapeTableCell $v }} |
{{- end }}
{{- end }}


{{if .GeneratorURL}}Source: {{ .GeneratorURL }}{{end}}

{{if .SlienceURL}}Silence: {{ .SlienceURL }}{{end}}

{{if .ImageURL}}![Panel Snapshot]({{ .ImageURL }}){{end}}

{{codeBlock .ValueString }}
`))

func clientError(w http.ResponseWriter, code int, err error) bool {
	if err == nil {
		return false
	}

	http.Error(w, http.StatusText(code), code)
	return true
}

func alertsFromLegacy(ctx context.Context, req *http.Request, serviceID string, data []byte) ([]alert.Alert, error) {
	var g struct {
		RuleName string
		RuleID   int
		Message  string
		State    string
		Title    string
		RuleURL  string
		ImageURL string
	}
	err := json.Unmarshal(data, &g)
	if err != nil {
		return nil, err
	}

	var grafanaState alert.Status
	switch g.State {
	case "alerting":
		grafanaState = alert.StatusTriggered
	case "ok":
		grafanaState = alert.StatusClosed
	case "no_data":
		// no data..
		return nil, nil
	default:
		return nil, errors.Errorf("grafana: unknown state: %s", g.State)
	}

	var urlStr string
	if validate.AbsoluteURL("RuleURL", g.RuleURL) == nil {
		urlStr = g.RuleURL
	}
	body := strings.TrimSpace(urlStr + "\n\n" + g.Message)

	if validate.AbsoluteURL("ImageURL", g.ImageURL) == nil {
		body += "\n\n![Panel Snapshot](" + g.ImageURL + ")"
	}

	// dedupe is description, source, and serviceID
	return []alert.Alert{{
		Summary:   validate.SanitizeText(g.RuleName, alert.MaxSummaryLength),
		Details:   validate.SanitizeText(body, alert.MaxDetailsLength),
		Status:    grafanaState,
		ServiceID: serviceID,
		Source:    alert.SourceGrafana,
		Dedup:     alert.NewUserDedup(req.FormValue("dedup")),
	}}, nil
}

func alertsFromV1(ctx context.Context, serviceID string, data []byte) ([]alert.Alert, error) {
	var g struct {
		Alerts []struct {
			Status              string
			Labels, Annotations map[string]string
			ValueString         string
			Fingerprint         string
			GeneratorURL        string
			SlienceURL          string
			ImageURL            string
		}
	}
	err := json.Unmarshal(data, &g)
	if err != nil {
		return nil, err
	}

	var alerts []alert.Alert
	for _, a := range g.Alerts {
		var alertStatus alert.Status
		switch a.Status {
		case "firing":
			alertStatus = alert.StatusTriggered
		case "resolved":
			alertStatus = alert.StatusClosed
		default:
			return nil, errors.Errorf("grafana: unknown status: %s", a.Status)
		}

		var buf strings.Builder
		err := detailsTmpl.Execute(&buf, a)
		if err != nil {
			return nil, err
		}
		summary := a.Annotations["summary"]
		if summary == "" {
			summary = a.Labels["alertname"]
		}

		alerts = append(alerts, alert.Alert{
			Summary:   validate.SanitizeText(summary, alert.MaxSummaryLength),
			Details:   validate.SanitizeText(buf.String(), alert.MaxDetailsLength),
			Status:    alertStatus,
			ServiceID: serviceID,
			Source:    alert.SourceGrafana,
			Dedup:     alert.NewUserDedup(a.Fingerprint),
		})
	}

	return alerts, nil
}

func GrafanaToEventsAPI(aDB *alert.Store, intDB *integrationkey.Store) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		err := permission.LimitCheckAny(ctx, permission.Service)
		if errutil.HTTPError(ctx, w, err) {
			return
		}
		serviceID := permission.ServiceID(ctx)

		data, err := io.ReadAll(r.Body)
		if errutil.HTTPError(ctx, w, err) {
			return
		}

		var versionInfo struct{ Version string }
		err = json.Unmarshal(data, &versionInfo)
		if clientError(w, http.StatusBadRequest, err) {
			return
		}

		var alerts []alert.Alert
		switch versionInfo.Version {
		case "1":
			alerts, err = alertsFromV1(ctx, serviceID, data)
		case "":
			alerts, err = alertsFromLegacy(ctx, r, serviceID, data)
		default:
			clientError(w, http.StatusBadRequest, errors.Errorf("grafana: unknown payload version: %s", versionInfo.Version))
			return
		}

		if clientError(w, http.StatusBadRequest, err) {
			log.Logf(ctx, "bad request from grafana: %v", err)
			return
		}
		if len(alerts) == 0 {
			// no data
			return
		}
		if len(alerts) > 10 {
			log.Log(ctx, fmt.Errorf("grafana: too many alerts (truncating to 10): %d", len(alerts)))
			alerts = alerts[:10]
		}

		var hasFailures bool
		for _, a := range alerts {
			err = retry.DoTemporaryError(func(int) error {
				_, _, err = aDB.CreateOrUpdate(ctx, &a)
				return err
			},
				retry.Log(ctx),
				retry.Limit(10),
				retry.FibBackoff(time.Second),
			)
			if err != nil {
				log.Log(ctx, fmt.Errorf("grafana: create alert: %w", err))
				hasFailures = true
			}
		}

		if hasFailures {
			http.Error(w, "failed to create alerts", http.StatusInternalServerError)
			return
		}
	}
}