Skip to content

Commit

Permalink
Support for multiple samples within same metric (#1181)
Browse files Browse the repository at this point in the history
Signed-off-by: João Vilaça <jvilaca@redhat.com>

Signed-off-by: João Vilaça <jvilaca@redhat.com>
  • Loading branch information
machadovilaca committed Dec 15, 2022
1 parent fae2f63 commit e29ed9f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
5 changes: 5 additions & 0 deletions prometheus/registry.go
Expand Up @@ -21,6 +21,7 @@ import (
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"unicode/utf8"
Expand Down Expand Up @@ -933,6 +934,10 @@ func checkMetricConsistency(
h.WriteString(lp.GetValue())
h.Write(separatorByteSlice)
}
if dtoMetric.TimestampMs != nil {
h.WriteString(strconv.FormatInt(*(dtoMetric.TimestampMs), 10))
h.Write(separatorByteSlice)
}
hSum := h.Sum64()
if _, exists := metricHashes[hSum]; exists {
return fmt.Errorf(
Expand Down
45 changes: 45 additions & 0 deletions prometheus/registry_test.go
Expand Up @@ -1288,3 +1288,48 @@ func ExampleRegistry_grouping() {
}(i)
}
}

type customCollector struct {
collectFunc func(ch chan<- prometheus.Metric)
}

func (co *customCollector) Describe(_ chan<- *prometheus.Desc) {}

func (co *customCollector) Collect(ch chan<- prometheus.Metric) {
co.collectFunc(ch)
}

// TestCheckMetricConsistency
func TestCheckMetricConsistency(t *testing.T) {
reg := prometheus.NewRegistry()
timestamp := time.Now()

desc := prometheus.NewDesc("metric_a", "", nil, nil)
metric := prometheus.MustNewConstMetric(desc, prometheus.CounterValue, 1)

validCollector := &customCollector{
collectFunc: func(ch chan<- prometheus.Metric) {
ch <- prometheus.NewMetricWithTimestamp(timestamp.Add(-1*time.Minute), metric)
ch <- prometheus.NewMetricWithTimestamp(timestamp, metric)
},
}
reg.MustRegister(validCollector)
_, err := reg.Gather()
if err != nil {
t.Error("metric validation should succeed:", err)
}
reg.Unregister(validCollector)

invalidCollector := &customCollector{
collectFunc: func(ch chan<- prometheus.Metric) {
ch <- prometheus.NewMetricWithTimestamp(timestamp, metric)
ch <- prometheus.NewMetricWithTimestamp(timestamp, metric)
},
}
reg.MustRegister(invalidCollector)
_, err = reg.Gather()
if err == nil {
t.Error("metric validation should return an error")
}
reg.Unregister(invalidCollector)
}

0 comments on commit e29ed9f

Please sign in to comment.