Strips invalid characters in `promAdjust`.
The `promAdjust` function in `auto.go` previously allowed characters that were not valid in prometheus metric names (e.g. '>'). This commit updates `promAdjust` to remove invalid characters. The `TestPromAdjust` function is updated with testcases that include invalid characters.
This commit is contained in:
parent
e88db3cd5e
commit
cc896c9996
|
@ -1,22 +1,30 @@
|
|||
package metrics
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
)
|
||||
|
||||
// per `prometheus/common/model/metric.go` and the `IsValidMetricName` function
|
||||
// only alphanumeric characters, underscore and `:` are valid characters in
|
||||
// a Prometheus metric name
|
||||
var invalidPromChars = regexp.MustCompile(`[^[:alnum:]\_:]+`)
|
||||
|
||||
// promAdjust adjusts a name for use by Prometheus: It strips off a single label
|
||||
// of prefix (which is always the name of the service, and therefore duplicated
|
||||
// by Prometheus' instance labels), and replaces "-" and "." with "_".
|
||||
// by Prometheus' instance labels), and replaces "-" and "." with "_". Invalid
|
||||
// metric name characters that remain (e.g. `>`) are removed.
|
||||
func promAdjust(name string) string {
|
||||
name = strings.Replace(name, "-", "_", -1)
|
||||
labels := strings.Split(name, ".")
|
||||
if len(labels) < 2 {
|
||||
return labels[0]
|
||||
return invalidPromChars.ReplaceAllString(labels[0], "")
|
||||
}
|
||||
return strings.Join(labels[1:], "_")
|
||||
name = strings.Join(labels[1:], "_")
|
||||
return invalidPromChars.ReplaceAllString(name, "")
|
||||
}
|
||||
|
||||
// autoProm implements a bridge from statsd-style metrics to Prometheus-style
|
||||
|
|
|
@ -16,11 +16,13 @@ func TestPromAdjust(t *testing.T) {
|
|||
{"RA.FOO-BAR", "FOO_BAR"},
|
||||
{"RA.FOO-BAR", "FOO_BAR"},
|
||||
{"RA", "RA"},
|
||||
{"RA>CA", "RACA"},
|
||||
{"RA?CA!- 99 @#$%&()", "RACA_99"},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.input, func(t *testing.T) {
|
||||
if promAdjust(tc.input) != tc.output {
|
||||
t.Errorf("expected %q, got %q", tc.input, tc.output)
|
||||
if result := promAdjust(tc.input); result != tc.output {
|
||||
t.Errorf("promAdjust(%q) - expected %q, got %q", tc.input, tc.output, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue