Skip to content

Commit

Permalink
Merge pull request #406 from alibresco/main
Browse files Browse the repository at this point in the history
Sort prometheus labels in accordance with the prometheus spec
  • Loading branch information
karimra authored Apr 16, 2024
2 parents 5905af1 + 0ace10d commit 71d4685
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pkg/outputs/prometheus_output/prometheus_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
package prometheus_output

import (
"cmp"
"errors"
"math"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -152,6 +154,13 @@ func (m *MetricBuilder) TimeSeriesFromEvent(ev *formatters.EventMsg) []*NamedTim
Name: labels.MetricName,
Value: tsName,
})

// The prometheus spec requires label names to be sorted
// https://prometheus.io/docs/concepts/remote_write_spec/
slices.SortFunc(tsLabelsWithName, func(a prompb.Label, b prompb.Label) int {
return cmp.Compare(a.Name, b.Name)
})

nts := &NamedTimeSeries{
Name: tsName,
TS: &prompb.TimeSeries{
Expand Down
29 changes: 29 additions & 0 deletions pkg/outputs/prometheus_output/prometheus_common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@
package prometheus_output

import (
"cmp"
"slices"
"testing"

"github.com/openconfig/gnmic/pkg/formatters"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/prompb"
)

var metricNameSet = map[string]struct {
Expand Down Expand Up @@ -97,6 +100,32 @@ func TestTimeSeriesFromEvent(t *testing.T) {
}
}

func TestTimeSeriesLabelsSorted(t *testing.T) {
metricBuilder := &MetricBuilder{StringsAsLabels: true}
event := &formatters.EventMsg{
Name: "eventName",
Timestamp: 12345,
Tags: map[string]string{
"tagName": "tagVal",
},
Values: map[string]interface{}{
"strName1": "strVal1",
"strName2": "strVal2",
"intName1": 1,
"intName2": 2,
},
Deletes: []string{},
}
for _, nts := range metricBuilder.TimeSeriesFromEvent(event) {
areLabelsSorted := slices.IsSortedFunc(nts.TS.Labels, func(a prompb.Label, b prompb.Label) int {
return cmp.Compare(a.Name, b.Name)
})
if !areLabelsSorted {
t.Errorf("labels names are not sorted, got '%v'", nts.TS.Labels)
}
}
}

func TestMetricName(t *testing.T) {
for name, tc := range metricNameSet {
t.Run(name, func(t *testing.T) {
Expand Down

0 comments on commit 71d4685

Please sign in to comment.