-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.go
More file actions
70 lines (59 loc) · 1.85 KB
/
plugin.go
File metadata and controls
70 lines (59 loc) · 1.85 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
package availability
import (
"bytes"
"context"
"fmt"
"regexp"
"strings"
"text/template"
)
const (
// SLIPluginVersion is the version of the plugin spec.
SLIPluginVersion = "prometheus/v1"
// SLIPluginID is the registering ID of the plugin.
SLIPluginID = "sloth-common/slok-go-http-metrics/availability"
)
var queryTpl = template.Must(template.New("").Option("missingkey=error").Parse(`
sum(rate(http_request_duration_seconds_count{ {{.filterError}}code=~"(5..|429)" }[{{"{{.window}}"}}]))
/
sum(rate(http_request_duration_seconds_count{ {{.filterTotal}} }[{{"{{.window}}"}}]))
`))
// SLIPlugin will return a query that will return the availability error based on https://github.com/slok/go-http-metrics
// status response codes.
// Counts as an error event the requests that have >=500 and 429 status codes.
func SLIPlugin(ctx context.Context, meta, labels, options map[string]string) (string, error) {
filter, err := getFilter(options)
if err != nil {
return "", fmt.Errorf("could not get filter: %w", err)
}
filterTotal := filter
filterError := filter
if filterError != "" {
filterError = filter + ","
}
// Create query.
var b bytes.Buffer
data := map[string]string{
"filterError": filterError,
"filterTotal": filterTotal,
}
err = queryTpl.Execute(&b, data)
if err != nil {
return "", fmt.Errorf("could not render query template: %w", err)
}
return b.String(), nil
}
var filterRegex = regexp.MustCompile(`(?m)^{?([^=]+="[^=,"]+",)*([^=]+="[^=,"]+")$`)
func getFilter(options map[string]string) (string, error) {
filter, ok := options["filter"]
if !ok || (ok && filter == "") {
return "", fmt.Errorf("filter is required")
}
// Sanitize and check filter.
filter = strings.Trim(filter, "{},")
match := filterRegex.MatchString(filter)
if !match {
return "", fmt.Errorf("invalid prometheus filter: %s", filter)
}
return filter, nil
}