Skip to content

Commit e8be06d

Browse files
authored
LabelSet: Fix alphabetical sorting for prometheus LabelSet (#575)
* custom sorting for LabelSet. See: #543 Signed-off-by: Syed Nihal <[email protected]> * implement custom sorting for prometheus labelset. see: #543 Signed-off-by: Syed Nihal <[email protected]> * implement custom sorting for prometheus labelset. see: #543 Signed-off-by: Syed Nihal <[email protected]> * fix sorting issue of prometheus labelset. see: #543 Signed-off-by: Syed Nihal <[email protected]> --------- Signed-off-by: Syed Nihal <[email protected]>
1 parent 52e512c commit e8be06d

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

model/labelset.go

+7-4
Original file line numberDiff line numberDiff line change
@@ -130,12 +130,15 @@ func (l LabelSet) Merge(other LabelSet) LabelSet {
130130
}
131131

132132
func (l LabelSet) String() string {
133+
labelNames := make([]string, 0, len(l))
134+
for name := range l {
135+
labelNames = append(labelNames, string(name))
136+
}
137+
sort.Strings(labelNames)
133138
lstrs := make([]string, 0, len(l))
134-
for l, v := range l {
135-
lstrs = append(lstrs, fmt.Sprintf("%s=%q", l, v))
139+
for _, name := range labelNames {
140+
lstrs = append(lstrs, fmt.Sprintf("%s=%q", name, l[LabelName(name)]))
136141
}
137-
138-
sort.Strings(lstrs)
139142
return fmt.Sprintf("{%s}", strings.Join(lstrs, ", "))
140143
}
141144

model/labelset_test.go

+25-2
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,10 @@ func TestUnmarshalJSONLabelSet(t *testing.T) {
2727
labelSetJSON := `{
2828
"labelSet": {
2929
"monitor": "codelab",
30-
"foo": "bar"
30+
"foo": "bar",
31+
"foo2": "bar",
32+
"abc": "prometheus",
33+
"foo11": "bar11"
3134
}
3235
}`
3336
var c testConfig
@@ -38,7 +41,7 @@ func TestUnmarshalJSONLabelSet(t *testing.T) {
3841

3942
labelSetString := c.LabelSet.String()
4043

41-
expected := `{foo="bar", monitor="codelab"}`
44+
expected := `{abc="prometheus", foo="bar", foo11="bar11", foo2="bar", monitor="codelab"}`
4245

4346
if expected != labelSetString {
4447
t.Errorf("expected %s but got %s", expected, labelSetString)
@@ -117,3 +120,23 @@ func TestLabelSetMerge(t *testing.T) {
117120
}
118121
}
119122
}
123+
124+
// Benchmark Results for LabelSet's String() method
125+
// ---------------------------------------------------------------------------------------------------------
126+
// goos: linux
127+
// goarch: amd64
128+
// pkg: github.com/prometheus/common/model
129+
// cpu: 11th Gen Intel(R) Core(TM) i5-1145G7 @ 2.60GHz
130+
// BenchmarkLabelSetStringMethod-8 732376 1532 ns/op
131+
132+
func BenchmarkLabelSetStringMethod(b *testing.B) {
133+
ls := make(LabelSet)
134+
ls["monitor"] = "codelab"
135+
ls["foo2"] = "bar"
136+
ls["foo"] = "bar"
137+
ls["abc"] = "prometheus"
138+
ls["foo11"] = "bar11"
139+
for i := 0; i < b.N; i++ {
140+
_ = ls.String()
141+
}
142+
}

0 commit comments

Comments
 (0)