Skip to content

Commit

Permalink
LabelSet: Fix alphabetical sorting for prometheus LabelSet (#575)
Browse files Browse the repository at this point in the history
* custom sorting for LabelSet. See: #543

Signed-off-by: Syed Nihal <syed.nihal@nokia.com>

* implement custom sorting for prometheus labelset. see: #543

Signed-off-by: Syed Nihal <syed.nihal@nokia.com>

* implement custom sorting for prometheus labelset. see: #543

Signed-off-by: Syed Nihal <syed.nihal@nokia.com>

* fix sorting issue of prometheus labelset. see: #543

Signed-off-by: Syed Nihal <syed.nihal@nokia.com>

---------

Signed-off-by: Syed Nihal <syed.nihal@nokia.com>
  • Loading branch information
wasim-nihal committed Feb 29, 2024
1 parent 52e512c commit e8be06d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
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()
}
}

0 comments on commit e8be06d

Please sign in to comment.