From 74e5b596da3a76a71671a182e3f0d56c687f2bcc Mon Sep 17 00:00:00 2001 From: Ziqi Zhao Date: Wed, 27 Apr 2022 17:30:05 +0800 Subject: [PATCH] add stripDomain to template function (#10475) * add stripDomain to template function Signed-off-by: Ziqi Zhao --- docs/configuration/template_reference.md | 1 + template/template.go | 15 ++++++++++ template/template_test.go | 35 ++++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/docs/configuration/template_reference.md b/docs/configuration/template_reference.md index 34557ecd8..5c96ee597 100644 --- a/docs/configuration/template_reference.md +++ b/docs/configuration/template_reference.md @@ -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. | | 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. | +| stripDomain | string | string | Removes the domain part of a FQDN. Leaves port untouched. | ### Others diff --git a/template/template.go b/template/template.go index 696263998..4058ad3ae 100644 --- a/template/template.go +++ b/template/template.go @@ -196,6 +196,21 @@ func NewTemplateExpander( } 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) { v, err := convertToFloat(i) if err != nil { diff --git a/template/template_test.go b/template/template_test.go index 342a95112..45d1a66e7 100644 --- a/template/template_test.go +++ b/template/template_test.go @@ -480,6 +480,41 @@ func TestTemplateExpansion(t *testing.T) { text: "{{ printf \"%0.2f\" (parseDuration \"1h2m10ms\") }}", 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", + }, }) }