-
Notifications
You must be signed in to change notification settings - Fork 455
/
alertmanager_template.go
91 lines (81 loc) · 2.54 KB
/
alertmanager_template.go
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
// SPDX-License-Identifier: AGPL-3.0-only
package alertmanager
import (
"encoding/json"
"fmt"
tmplhtml "html/template"
"net/url"
tmpltext "text/template"
"github.com/prometheus/alertmanager/template"
)
type grafanaDatasource struct {
Type string `json:"type,omitempty"`
UID string `json:"uid,omitempty"`
}
type grafanaExploreRange struct {
From string `json:"from"`
To string `json:"to"`
}
type grafanaExploreQuery struct {
Datasource grafanaDatasource `json:"datasource"`
Expr string `json:"expr"`
Instant bool `json:"instant"`
Range bool `json:"range"`
RefID string `json:"refId"`
}
type grafanaExploreParams struct {
Range grafanaExploreRange `json:"range"`
Queries []grafanaExploreQuery `json:"queries"`
}
// grafanaExploreURL is a template helper function to generate Grafana range query explore URL in the alert template.
func grafanaExploreURL(grafanaURL, datasource, from, to, expr string) (string, error) {
res, err := json.Marshal(&grafanaExploreParams{
Range: grafanaExploreRange{
From: from,
To: to,
},
Queries: []grafanaExploreQuery{
{
Datasource: grafanaDatasource{
Type: "prometheus",
UID: datasource,
},
Expr: expr,
Instant: false,
Range: true,
RefID: "A",
},
},
})
return grafanaURL + "/explore?left=" + url.QueryEscape(string(res)), err
}
// queryFromGeneratorURL returns a PromQL expression parsed out from a GeneratorURL in Prometheus alert
func queryFromGeneratorURL(generatorURL string) (string, error) {
u, err := url.Parse(generatorURL)
if err != nil {
return "", fmt.Errorf("failed to parse generator URL: %w", err)
}
// See https://github.com/prometheus/prometheus/blob/259bb5c69263635887541964d1bfd7acc46682c6/util/strutil/strconv.go#L28
queryParam, ok := u.Query()["g0.expr"]
if !ok || len(queryParam) < 1 {
return "", fmt.Errorf("query not found in the generator URL")
}
query, err := url.QueryUnescape(queryParam[0])
if err != nil {
return "", fmt.Errorf("failed to URL decode the query: %w", err)
}
return query, nil
}
// WithCustomFunctions returns template.Option which adds additional template functions
// to the default ones.
func WithCustomFunctions(userID string) template.Option {
funcs := tmpltext.FuncMap{
"tenantID": func() string { return userID },
"grafanaExploreURL": grafanaExploreURL,
"queryFromGeneratorURL": queryFromGeneratorURL,
}
return func(text *tmpltext.Template, html *tmplhtml.Template) {
text.Funcs(funcs)
html.Funcs(funcs)
}
}