mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
This commit adds filterLabels, filterLabelsRe, removeLabels, and removeLabelsRe functions to templates for custom labels and annotations. It allows for use cases such as removing all private labels.
92 lines
2.2 KiB
Go
92 lines
2.2 KiB
Go
package template
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/url"
|
|
"regexp"
|
|
"text/template"
|
|
)
|
|
|
|
type query struct {
|
|
Datasource string `json:"datasource"`
|
|
Expr string `json:"expr"`
|
|
}
|
|
|
|
var (
|
|
defaultFuncs = template.FuncMap{
|
|
"filterLabels": filterLabelsFunc,
|
|
"filterLabelsRe": filterLabelsReFunc,
|
|
"graphLink": graphLinkFunc,
|
|
"removeLabels": removeLabelsFunc,
|
|
"removeLabelslRe": removeLabelsReFunc,
|
|
"tableLink": tableLinkFunc,
|
|
}
|
|
)
|
|
|
|
// filterLabelsFunc removes all labels that do not match the string.
|
|
func filterLabelsFunc(m Labels, match string) Labels {
|
|
res := make(Labels)
|
|
for k, v := range m {
|
|
if k == match {
|
|
res[k] = v
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
|
|
// filterLabelsReFunc removes all labels that do not match the regex.
|
|
func filterLabelsReFunc(m Labels, pattern string) Labels {
|
|
re := regexp.MustCompile(pattern)
|
|
res := make(Labels)
|
|
for k, v := range m {
|
|
if re.MatchString(k) {
|
|
res[k] = v
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
|
|
func graphLinkFunc(data string) string {
|
|
var q query
|
|
if err := json.Unmarshal([]byte(data), &q); err != nil {
|
|
return ""
|
|
}
|
|
datasource := url.QueryEscape(q.Datasource)
|
|
expr := url.QueryEscape(q.Expr)
|
|
return fmt.Sprintf(`/explore?left={"datasource":%[1]q,"queries":[{"datasource":%[1]q,"expr":%q,"instant":false,"range":true,"refId":"A"}],"range":{"from":"now-1h","to":"now"}}`, datasource, expr)
|
|
}
|
|
|
|
// removeLabelsFunc removes all labels that match the string.
|
|
func removeLabelsFunc(m Labels, match string) Labels {
|
|
res := make(Labels)
|
|
for k, v := range m {
|
|
if k != match {
|
|
res[k] = v
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
|
|
// removeLabelsReFunc removes all labels that match the regex.
|
|
func removeLabelsReFunc(m Labels, pattern string) Labels {
|
|
re := regexp.MustCompile(pattern)
|
|
res := make(Labels)
|
|
for k, v := range m {
|
|
if !re.MatchString(k) {
|
|
res[k] = v
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
|
|
func tableLinkFunc(data string) string {
|
|
var q query
|
|
if err := json.Unmarshal([]byte(data), &q); err != nil {
|
|
return ""
|
|
}
|
|
datasource := url.QueryEscape(q.Datasource)
|
|
expr := url.QueryEscape(q.Expr)
|
|
return fmt.Sprintf(`/explore?left={"datasource":%[1]q,"queries":[{"datasource":%[1]q,"expr":%q,"instant":true,"range":false,"refId":"A"}],"range":{"from":"now-1h","to":"now"}}`, datasource, expr)
|
|
}
|