Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 21 additions & 9 deletions prometheus/counter.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,12 @@ func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec {

// NewCounterVec creates a new CounterVec based on the provided CounterVecOpts.
func (v2) NewCounterVec(opts CounterVecOpts) *CounterVec {
return newCounterVecWithTTL(opts, 0)
}

// newCounterVecWithTTL creates a CounterVec. ttl must be >= 0; ttl == 0 disables
// TTL behavior (identical to NewMetricVec).
func newCounterVecWithTTL(opts CounterVecOpts, ttl time.Duration) *CounterVec {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we sure this is what we want? How this will scale when we will have another option, newCounterVecWithTTLWithX?

If we have opts, why not using it with TTL for this purpose? Would it make sense to add ttl for those cases?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Dropped the *WithTTL helpers.

TTL now lives on CounterVecOpts / GaugeVecOpts / HistogramVecOpts / SummaryVecOpts / MetricVecOpts, e.g.:

  prometheus.V2.NewCounterVec(prometheus.CounterVecOpts{
      CounterOpts:    ...,
      VariableLabels: ...,
      TTL:            time.Minute,
  })

See 8d33a81 (and SummaryVec in 649400b).

desc := V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
Expand All @@ -211,16 +217,22 @@ func (v2) NewCounterVec(opts CounterVecOpts) *CounterVec {
if opts.now == nil {
opts.now = time.Now
}
newMetric := func(lvs ...string) Metric {
if len(lvs) != len(desc.variableLabels.names) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, lvs))
}
result := &counter{desc: desc, labelPairs: MakeLabelPairs(desc, lvs), now: opts.now}
result.init(result) // Init self-collection.
result.createdTs = timestamppb.New(opts.now())
return result
}
if ttl > 0 {
return &CounterVec{
MetricVec: NewMetricVecWithTTL(desc, newMetric, ttl),
}
}
return &CounterVec{
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
if len(lvs) != len(desc.variableLabels.names) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, lvs))
}
result := &counter{desc: desc, labelPairs: MakeLabelPairs(desc, lvs), now: opts.now}
result.init(result) // Init self-collection.
result.createdTs = timestamppb.New(opts.now())
return result
}),
MetricVec: NewMetricVec(desc, newMetric),
}
}

Expand Down
26 changes: 18 additions & 8 deletions prometheus/gauge.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,22 +159,32 @@ func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec {

// NewGaugeVec creates a new GaugeVec based on the provided GaugeVecOpts.
func (v2) NewGaugeVec(opts GaugeVecOpts) *GaugeVec {
return newGaugeVecWithTTL(opts, 0)
}

func newGaugeVecWithTTL(opts GaugeVecOpts, ttl time.Duration) *GaugeVec {
desc := V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
opts.VariableLabels,
opts.ConstLabels,
WithUnit(opts.Unit),
)
newMetric := func(lvs ...string) Metric {
if len(lvs) != len(desc.variableLabels.names) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, lvs))
}
result := &gauge{desc: desc, labelPairs: MakeLabelPairs(desc, lvs)}
result.init(result) // Init self-collection.
return result
}
if ttl > 0 {
return &GaugeVec{
MetricVec: NewMetricVecWithTTL(desc, newMetric, ttl),
}
}
return &GaugeVec{
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
if len(lvs) != len(desc.variableLabels.names) {
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, lvs))
}
result := &gauge{desc: desc, labelPairs: MakeLabelPairs(desc, lvs)}
result.init(result) // Init self-collection.
return result
}),
MetricVec: NewMetricVec(desc, newMetric),
}
}

Expand Down
16 changes: 13 additions & 3 deletions prometheus/histogram.go
Original file line number Diff line number Diff line change
Expand Up @@ -1189,17 +1189,27 @@ func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec {

// NewHistogramVec creates a new HistogramVec based on the provided HistogramVecOpts.
func (v2) NewHistogramVec(opts HistogramVecOpts) *HistogramVec {
return newHistogramVecWithTTL(opts, 0)
}

func newHistogramVecWithTTL(opts HistogramVecOpts, ttl time.Duration) *HistogramVec {
desc := V2.NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
opts.VariableLabels,
opts.ConstLabels,
WithUnit(opts.Unit),
)
newMetric := func(lvs ...string) Metric {
return newHistogram(desc, opts.HistogramOpts, lvs...)
}
if ttl > 0 {
return &HistogramVec{
MetricVec: NewMetricVecWithTTL(desc, newMetric, ttl),
}
}
return &HistogramVec{
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
return newHistogram(desc, opts.HistogramOpts, lvs...)
}),
MetricVec: NewMetricVec(desc, newMetric),
}
}

Expand Down
124 changes: 124 additions & 0 deletions prometheus/ttl_registry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Copyright 2014 The Prometheus Authors

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2014?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops, bad copy paste. The new ttl.go uses the proper copyright header 👍

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package prometheus

import (
"sync"
"time"

dto "github.com/prometheus/client_model/go"
)

// TTLRegistry is a dedicated Prometheus registry for metrics that need
// time-to-live behavior on *Vec children. It embeds a plain *Registry and adds:
// - Vec constructors that enable per-child TTL (same semantics as MetricVec
// built with NewMetricVecWithTTL).
// - Automatic CleanupExpired on all Vecs created through this registry before
// each Gather, so memory can be reclaimed even when scrapes are infrequent
// (see discussion in https://github.com/prometheus/client_golang/issues/1983).
//
// Default prometheus.NewRegistry, NewCounterVec, and Opts are unchanged; use
// TTLRegistry only when you explicitly opt in to Vec TTL.
type TTLRegistry struct {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registry is for registering metrics and then gathering registered ones. This API breaks this by having a registry with tons of New* constructors. Are we sure this will not confuse users?

LLM review also captures this well in this point: https://gist.github.com/bwplotka/694d6c4a9be64e629d5c7b2f3541319b#a-coupling-constructors-to-registry

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's indeed also false impression that MustRegister would suddenly start TTL tracking: https://gist.github.com/bwplotka/694d6c4a9be64e629d5c7b2f3541319b#b-incomplete--error-prone-registration-surface

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Removed TTLRegistry entirely.

Construction stays on V2.New*Vec(...Opts{TTL: ...}); registration/gathering stay on a normal Registry.

See 49d10c3.

*Registry

ttl time.Duration

mu sync.Mutex
vecs []*MetricVec
}

// NewTTLRegistry returns a registry backed by a new empty *Registry. ttl must
// be greater than zero; it applies to every Vec created via this registry's
// constructor methods.
func NewTTLRegistry(ttl time.Duration) *TTLRegistry {
if ttl <= 0 {
panic("NewTTLRegistry: ttl must be > 0")
}
return &TTLRegistry{
Registry: NewRegistry(),
ttl: ttl,
}
}

func (r *TTLRegistry) track(mv *MetricVec) {
r.mu.Lock()
defer r.mu.Unlock()
r.vecs = append(r.vecs, mv)
}
Comment thread
kakkoyun marked this conversation as resolved.
Outdated

func (r *TTLRegistry) runCleanup() {
r.mu.Lock()
vecs := append([]*MetricVec(nil), r.vecs...)
r.mu.Unlock()
for _, mv := range vecs {
mv.CleanupExpired()
}
}

// Gather implements Gatherer. It runs CleanupExpired on all Vecs created
// through this TTLRegistry, then delegates to the embedded Registry.
func (r *TTLRegistry) Gather() ([]*dto.MetricFamily, error) {
r.runCleanup()
return r.Registry.Gather()
}

// NewCounterVec is like prometheus.NewCounterVec but enables Vec TTL using this
// registry's ttl, registers the Vec, and tracks it for Gather-time cleanup.
func (r *TTLRegistry) NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec {
return r.NewCounterVecOpts(CounterVecOpts{
CounterOpts: opts,
VariableLabels: UnconstrainedLabels(labelNames),
})
}

// NewCounterVecOpts is like V2.NewCounterVec with TTL and automatic registration.
func (r *TTLRegistry) NewCounterVecOpts(opts CounterVecOpts) *CounterVec {
cv := newCounterVecWithTTL(opts, r.ttl)
r.MustRegister(cv)
r.track(cv.MetricVec)
return cv
}

// NewGaugeVec is like prometheus.NewGaugeVec with TTL, registration, and tracking.
func (r *TTLRegistry) NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec {
return r.NewGaugeVecOpts(GaugeVecOpts{
GaugeOpts: opts,
VariableLabels: UnconstrainedLabels(labelNames),
})
}

// NewGaugeVecOpts is like V2.NewGaugeVec with TTL and automatic registration.
func (r *TTLRegistry) NewGaugeVecOpts(opts GaugeVecOpts) *GaugeVec {
gv := newGaugeVecWithTTL(opts, r.ttl)
r.MustRegister(gv)
r.track(gv.MetricVec)
return gv
}

// NewHistogramVec is like prometheus.NewHistogramVec with TTL, registration, and tracking.
func (r *TTLRegistry) NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec {
return r.NewHistogramVecOpts(HistogramVecOpts{
HistogramOpts: opts,
VariableLabels: UnconstrainedLabels(labelNames),
})
}

// NewHistogramVecOpts is like V2.NewHistogramVec with TTL and automatic registration.
func (r *TTLRegistry) NewHistogramVecOpts(opts HistogramVecOpts) *HistogramVec {
hv := newHistogramVecWithTTL(opts, r.ttl)
r.MustRegister(hv)
r.track(hv.MetricVec)
return hv
}
55 changes: 55 additions & 0 deletions prometheus/ttl_registry_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2014 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package prometheus

import (
"testing"
"testing/synctest"
"time"
)

func TestNewTTLRegistryPanicsOnNonPositiveTTL(t *testing.T) {
defer func() {
if recover() == nil {
t.Fatal("expected panic for ttl <= 0")
}
}()
NewTTLRegistry(0)
}

func TestTTLRegistryGatherRunsCleanup(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ttl := 80 * time.Millisecond
reg := NewTTLRegistry(ttl)
vec := reg.NewCounterVec(CounterOpts{
Name: "ttl_reg_gather",
Help: "test",
}, []string{"code"})

vec.WithLabelValues("200").Add(1)
if n := collectCount(vec); n != 1 {
t.Fatalf("expected 1 metric before sleep, got %d", n)
}

time.Sleep(ttl + 40*time.Millisecond)

if _, err := reg.Gather(); err != nil {
t.Fatal(err)
}

if n := collectCount(vec); n != 0 {
t.Fatalf("expected 0 metrics after Gather cleanup, got %d", n)
}
})
}
Loading
Loading