From d738892c0ba3f3e72504c2850f5e7e6a4fd9178d Mon Sep 17 00:00:00 2001 From: Greg <2653109+glinton@users.noreply.github.com> Date: Tue, 2 Apr 2019 13:42:48 -0600 Subject: [PATCH] Remove tags that would create invalid label names in prometheus output (#5663) --- .../prometheus_client/prometheus_client.go | 33 ++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/plugins/outputs/prometheus_client/prometheus_client.go b/plugins/outputs/prometheus_client/prometheus_client.go index db7b0c207..da051daf9 100644 --- a/plugins/outputs/prometheus_client/prometheus_client.go +++ b/plugins/outputs/prometheus_client/prometheus_client.go @@ -24,7 +24,10 @@ import ( "github.com/prometheus/client_golang/prometheus/promhttp" ) -var invalidNameCharRE = regexp.MustCompile(`[^a-zA-Z0-9_]`) +var ( + invalidNameCharRE = regexp.MustCompile(`[^a-zA-Z0-9_]`) + validNameCharRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*`) +) // SampleID uniquely identifies a Sample type SampleID string @@ -343,6 +346,10 @@ func sanitize(value string) string { return invalidNameCharRE.ReplaceAllString(value, "_") } +func isValidTagName(tag string) bool { + return validNameCharRE.MatchString(tag) +} + func getPromValueType(tt telegraf.ValueType) prometheus.ValueType { switch tt { case telegraf.Counter: @@ -414,7 +421,11 @@ func (p *PrometheusClient) Write(metrics []telegraf.Metric) error { labels := make(map[string]string) for k, v := range tags { - labels[sanitize(k)] = v + tName := sanitize(k) + if !isValidTagName(tName) { + continue + } + labels[tName] = v } // Prometheus doesn't have a string value type, so convert string @@ -423,7 +434,11 @@ func (p *PrometheusClient) Write(metrics []telegraf.Metric) error { for fn, fv := range point.Fields() { switch fv := fv.(type) { case string: - labels[sanitize(fn)] = fv + tName := sanitize(fn) + if !isValidTagName(tName) { + continue + } + labels[tName] = fv } } } @@ -469,6 +484,10 @@ func (p *PrometheusClient) Write(metrics []telegraf.Metric) error { } mname = sanitize(point.Name()) + if !isValidTagName(mname) { + continue + } + p.addMetricFamily(point, sample, mname, sampleID) case telegraf.Histogram: @@ -511,6 +530,10 @@ func (p *PrometheusClient) Write(metrics []telegraf.Metric) error { } mname = sanitize(point.Name()) + if !isValidTagName(mname) { + continue + } + p.addMetricFamily(point, sample, mname, sampleID) default: @@ -555,7 +578,9 @@ func (p *PrometheusClient) Write(metrics []telegraf.Metric) error { mname = sanitize(fmt.Sprintf("%s_%s", point.Name(), fn)) } } - + if !isValidTagName(mname) { + continue + } p.addMetricFamily(point, sample, mname, sampleID) }