Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LabelSet: Fix alphabetical sorting for prometheus LabelSet #575

Merged
merged 4 commits into from Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 7 additions & 4 deletions model/labelset.go
Expand Up @@ -130,12 +130,15 @@ func (l LabelSet) Merge(other LabelSet) LabelSet {
}

func (l LabelSet) String() string {
labelNames := make([]string, 0, len(l))
for name := range l {
labelNames = append(labelNames, string(name))
}
sort.Strings(labelNames)
lstrs := make([]string, 0, len(l))
for l, v := range l {
lstrs = append(lstrs, fmt.Sprintf("%s=%q", l, v))
for _, name := range labelNames {
lstrs = append(lstrs, fmt.Sprintf("%s=%q", name, l[LabelName(name)]))
}

sort.Strings(lstrs)
return fmt.Sprintf("{%s}", strings.Join(lstrs, ", "))
}

Expand Down
27 changes: 25 additions & 2 deletions model/labelset_test.go
Expand Up @@ -27,7 +27,10 @@ func TestUnmarshalJSONLabelSet(t *testing.T) {
labelSetJSON := `{
"labelSet": {
"monitor": "codelab",
"foo": "bar"
"foo": "bar",
"foo2": "bar",
"abc": "prometheus",
"foo11": "bar11"
}
}`
var c testConfig
Expand All @@ -38,7 +41,7 @@ func TestUnmarshalJSONLabelSet(t *testing.T) {

labelSetString := c.LabelSet.String()

expected := `{foo="bar", monitor="codelab"}`
expected := `{abc="prometheus", foo="bar", foo11="bar11", foo2="bar", monitor="codelab"}`

if expected != labelSetString {
t.Errorf("expected %s but got %s", expected, labelSetString)
Expand Down Expand Up @@ -117,3 +120,23 @@ func TestLabelSetMerge(t *testing.T) {
}
}
}

// Benchmark Results for LabelSet's String() method
// ---------------------------------------------------------------------------------------------------------
// goos: linux
// goarch: amd64
// pkg: github.com/prometheus/common/model
// cpu: 11th Gen Intel(R) Core(TM) i5-1145G7 @ 2.60GHz
// BenchmarkLabelSetStringMethod-8 732376 1532 ns/op

func BenchmarkLabelSetStringMethod(b *testing.B) {
ls := make(LabelSet)
ls["monitor"] = "codelab"
ls["foo2"] = "bar"
ls["foo"] = "bar"
ls["abc"] = "prometheus"
ls["foo11"] = "bar11"
for i := 0; i < b.N; i++ {
_ = ls.String()
}
}