/
alerts.go
96 lines (75 loc) · 2.05 KB
/
alerts.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
92
93
94
95
96
package docs
import (
"bytes"
"log"
"sort"
"text/template"
promv1 "github.com/prometheus-operator/prometheus-operator/pkg/apis/monitoring/v1"
)
const defaultAlertsTemplate = `# Operator Alerts
{{- range . }}
### {{.Name}}
**Summary:** {{ index .Annotations "summary" }}.
**Description:** {{ index .Annotations "description" }}.
**Severity:** {{ index .Labels "severity" }}.
{{- if .For }}
**For:** {{ .For }}.
{{- end -}}
{{- end }}
## Developing new alerts
All alerts documented here are auto-generated and reflect exactly what is being
exposed. After developing new alerts or changing old ones please regenerate
this document.
`
type alertDocs struct {
Name string
Expr string
For string
Annotations map[string]string
Labels map[string]string
}
// BuildAlertsDocsWithCustomTemplate returns a string with the documentation
// for the given alerts, using the given template.
func BuildAlertsDocsWithCustomTemplate(
alerts []promv1.Rule,
tplString string,
) string {
tpl, err := template.New("alerts").Parse(tplString)
if err != nil {
log.Fatalln(err)
}
var allDocs []alertDocs
if alerts != nil {
allDocs = append(allDocs, buildAlertsDocs(alerts)...)
}
buf := bytes.NewBufferString("")
err = tpl.Execute(buf, allDocs)
if err != nil {
log.Fatalln(err)
}
return buf.String()
}
// BuildAlertsDocs returns a string with the documentation for the given
// metrics.
func BuildAlertsDocs(alerts []promv1.Rule) string {
return BuildAlertsDocsWithCustomTemplate(alerts, defaultAlertsTemplate)
}
func buildAlertsDocs(alerts []promv1.Rule) []alertDocs {
alertsDocs := make([]alertDocs, len(alerts))
for i, alert := range alerts {
alertsDocs[i] = alertDocs{
Name: alert.Alert,
Expr: alert.Expr.String(),
For: string(*alert.For),
Annotations: alert.Annotations,
Labels: alert.Labels,
}
}
sortAlertsDocs(alertsDocs)
return alertsDocs
}
func sortAlertsDocs(alertsDocs []alertDocs) {
sort.Slice(alertsDocs, func(i, j int) bool {
return alertsDocs[i].Name < alertsDocs[j].Name
})
}