mirror of
https://github.com/prometheus/prometheus.git
synced 2024-12-25 05:34:05 -08:00
Fix SanitizeLabelName for certain invalid labels
SanitizeLabelName was not correctly sanitizing label names that: 1. Started with a digit (0-9) 2. Were empty This commit changes the santization code to catch both of these edge cases and adds new tests to validate it works correctly in them both. In the first case, a leading digit will be replaced with an underscore, and in the latter, the function will return a single underscore. Signed-off-by: Nick Moore <nicholas.moore@grafana.com>
This commit is contained in:
parent
c70d85baed
commit
758914e1fb
|
@ -16,12 +16,9 @@ package strutil
|
|||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/grafana/regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var invalidLabelCharRE = regexp.MustCompile(`[^a-zA-Z0-9_]`)
|
||||
|
||||
// TableLinkForExpression creates an escaped relative link to the table view of
|
||||
// the provided expression.
|
||||
func TableLinkForExpression(expr string) string {
|
||||
|
@ -36,8 +33,19 @@ func GraphLinkForExpression(expr string) string {
|
|||
return fmt.Sprintf("/graph?g0.expr=%s&g0.tab=0", escapedExpression)
|
||||
}
|
||||
|
||||
// SanitizeLabelName replaces anything that doesn't match
|
||||
// client_label.LabelNameRE with an underscore.
|
||||
// SanitizeLabelName replaces any invalid character with an underscore, and if
|
||||
// given an empty string, returns a string containing a single underscore.
|
||||
func SanitizeLabelName(name string) string {
|
||||
return invalidLabelCharRE.ReplaceAllString(name, "_")
|
||||
if len(name) == 0 {
|
||||
return "_"
|
||||
}
|
||||
var validSb strings.Builder
|
||||
for i, b := range name {
|
||||
if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || (b >= '0' && b <= '9' && i > 0)) {
|
||||
validSb.WriteRune('_')
|
||||
} else {
|
||||
validSb.WriteRune(b)
|
||||
}
|
||||
}
|
||||
return validSb.String()
|
||||
}
|
||||
|
|
|
@ -58,4 +58,12 @@ func TestSanitizeLabelName(t *testing.T) {
|
|||
actual = SanitizeLabelName("barClient.LABEL$$##")
|
||||
expected = "barClient_LABEL____"
|
||||
require.Equal(t, expected, actual, "SanitizeLabelName failed for label (%s)", expected)
|
||||
|
||||
actual = SanitizeLabelName("0zerothClient1LABEL")
|
||||
expected = "_zerothClient1LABEL"
|
||||
require.Equal(t, expected, actual, "SanitizeLabelName failed for label (%s)", expected)
|
||||
|
||||
actual = SanitizeLabelName("")
|
||||
expected = "_"
|
||||
require.Equal(t, expected, actual, "SanitizeLabelName failed for the empty label")
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue