From 8e4f899c49a95332ba9b0c534d92558dbe8e3e25 Mon Sep 17 00:00:00 2001 From: Arthur Silva Sens Date: Tue, 1 Aug 2023 17:57:26 -0300 Subject: [PATCH] Initialize counter created timestamp during metric initialization Signed-off-by: Arthur Silva Sens --- prometheus/counter.go | 12 +++++------- prometheus/counter_test.go | 27 ++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/prometheus/counter.go b/prometheus/counter.go index 258aefb10..ebcf6f2f5 100644 --- a/prometheus/counter.go +++ b/prometheus/counter.go @@ -93,6 +93,7 @@ func NewCounter(opts CounterOpts) Counter { ) result := &counter{desc: desc, labelPairs: desc.constLabelPairs, now: time.Now} result.init(result) // Init self-collection. + result.initCreated() return result } @@ -114,6 +115,10 @@ type counter struct { now func() time.Time // To mock out time.Now() for testing. } +func (c *counter) initCreated() { + c.createdTs = timestamppb.New(c.now()) +} + func (c *counter) Desc() *Desc { return c.desc } @@ -123,10 +128,6 @@ func (c *counter) Add(v float64) { panic(errors.New("counter cannot decrease in value")) } - if c.createdTs == nil { - c.createdTs = timestamppb.New(c.now()) - } - ival := uint64(v) if float64(ival) == v { atomic.AddUint64(&c.valInt, ival) @@ -149,9 +150,6 @@ func (c *counter) AddWithExemplar(v float64, e Labels) { func (c *counter) Inc() { atomic.AddUint64(&c.valInt, 1) - if c.createdTs == nil { - c.createdTs = timestamppb.New(c.now()) - } } func (c *counter) get() float64 { diff --git a/prometheus/counter_test.go b/prometheus/counter_test.go index 16e4854b4..168dcea9b 100644 --- a/prometheus/counter_test.go +++ b/prometheus/counter_test.go @@ -282,6 +282,32 @@ func TestCounterCreatedTimestamp(t *testing.T) { Help: "test help", }).(*counter) counter.now = func() time.Time { return now } + counter.initCreated() + + ts := timestamppb.New(now) + if err := ts.CheckValid(); err != nil { + t.Fatal(err) + } + + expectedCounter := &dto.Counter{ + CreatedTimestamp: ts, + } + + if counter.createdTs.AsTime() != expectedCounter.CreatedTimestamp.AsTime() { + t.Errorf("expected created timestamp %s, got %s", expectedCounter.CreatedTimestamp, counter.createdTs) + } +} + +func TestCounterVecCreatedTimestamp(t *testing.T) { + now := time.Now() + + counterVec := NewCounterVec(CounterOpts{ + Name: "test", + Help: "test help", + }, []string{"label"}) + counter := counterVec.WithLabelValues("value").(*counter) + counter.now = func() time.Time { return now } + counter.initCreated() ts := timestamppb.New(now) if err := ts.CheckValid(); err != nil { @@ -292,7 +318,6 @@ func TestCounterCreatedTimestamp(t *testing.T) { CreatedTimestamp: ts, } - counter.Inc() if counter.createdTs.AsTime() != expectedCounter.CreatedTimestamp.AsTime() { t.Errorf("expected created timestamp %s, got %s", expectedCounter.CreatedTimestamp, counter.createdTs) }