add stripDomain to template function (#10475)

* add stripDomain to template function

Signed-off-by: Ziqi Zhao <zzqwf12345@163.com>
This commit is contained in:
Ziqi Zhao 2022-04-27 17:30:05 +08:00 committed by GitHub
parent e2ede285a2
commit 74e5b596da
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 51 additions and 0 deletions

View file

@ -76,6 +76,7 @@ versions.
| graphLink | expr | string | Returns path to graph view in the [expression browser](https://prometheus.io/docs/visualization/browser/) for the expression. | | graphLink | expr | string | Returns path to graph view in the [expression browser](https://prometheus.io/docs/visualization/browser/) for the expression. |
| tableLink | expr | string | Returns path to tabular ("Table") view in the [expression browser](https://prometheus.io/docs/visualization/browser/) for the expression. | | tableLink | expr | string | Returns path to tabular ("Table") view in the [expression browser](https://prometheus.io/docs/visualization/browser/) for the expression. |
| parseDuration | string | float | Parses a duration string such as "1h" into the number of seconds it represents. | | parseDuration | string | float | Parses a duration string such as "1h" into the number of seconds it represents. |
| stripDomain | string | string | Removes the domain part of a FQDN. Leaves port untouched. |
### Others ### Others

View file

@ -196,6 +196,21 @@ func NewTemplateExpander(
} }
return host return host
}, },
"stripDomain": func(hostPort string) string {
host, port, err := net.SplitHostPort(hostPort)
if err != nil {
host = hostPort
}
ip := net.ParseIP(host)
if ip != nil {
return hostPort
}
host = strings.Split(host, ".")[0]
if port != "" {
return net.JoinHostPort(host, port)
}
return host
},
"humanize": func(i interface{}) (string, error) { "humanize": func(i interface{}) (string, error) {
v, err := convertToFloat(i) v, err := convertToFloat(i)
if err != nil { if err != nil {

View file

@ -480,6 +480,41 @@ func TestTemplateExpansion(t *testing.T) {
text: "{{ printf \"%0.2f\" (parseDuration \"1h2m10ms\") }}", text: "{{ printf \"%0.2f\" (parseDuration \"1h2m10ms\") }}",
output: "3720.01", output: "3720.01",
}, },
{
// Simple hostname.
text: "{{ \"foo.example.com\" | stripDomain }}",
output: "foo",
},
{
// Hostname with port.
text: "{{ \"foo.example.com:12345\" | stripDomain }}",
output: "foo:12345",
},
{
// Simple IPv4 address.
text: "{{ \"192.0.2.1\" | stripDomain }}",
output: "192.0.2.1",
},
{
// IPv4 address with port.
text: "{{ \"192.0.2.1:12345\" | stripDomain }}",
output: "192.0.2.1:12345",
},
{
// Simple IPv6 address.
text: "{{ \"2001:0DB8::1\" | stripDomain }}",
output: "2001:0DB8::1",
},
{
// IPv6 address with port.
text: "{{ \"[2001:0DB8::1]:12345\" | stripDomain }}",
output: "[2001:0DB8::1]:12345",
},
{
// Value can't be split into host and port.
text: "{{ \"[2001:0DB8::1]::12345\" | stripDomain }}",
output: "[2001:0DB8::1]::12345",
},
}) })
} }