Skip to content

Commit

Permalink
Dynamically register cache provider metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
tjamet committed Aug 14, 2024
1 parent ef0dd29 commit 6c5faaf
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
8 changes: 4 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,10 @@ func main() {
}

if cfg.ProviderCacheTime > 0 {
p = &provider.CachedProvider{
Provider: p,
RefreshDelay: cfg.ProviderCacheTime,
}
p = provider.NewCachedProvider(
p,
cfg.ProviderCacheTime,
)
}

var r registry.Registry
Expand Down
17 changes: 13 additions & 4 deletions provider/cached_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package provider

import (
"context"
"sync"
"time"

"github.com/prometheus/client_golang/prometheus"
Expand Down Expand Up @@ -46,6 +47,8 @@ var (
Help: "Number of calls to the provider cache ApplyChanges.",
},
)

registerCacheProviderMetrics = sync.Once{}
)

type CachedProvider struct {
Expand All @@ -55,6 +58,16 @@ type CachedProvider struct {
cache []*endpoint.Endpoint
}

func NewCachedProvider(provider Provider, refreshDelay time.Duration) *CachedProvider {
registerMetrics.Do(func() {
prometheus.MustRegister(cachedRecordsCallsTotal)
})
return &CachedProvider{
Provider: provider,
RefreshDelay: refreshDelay,
}
}

func (c *CachedProvider) Records(ctx context.Context) ([]*endpoint.Endpoint, error) {
if c.needRefresh() {
log.Info("Records cache provider: refreshing records list cache")
Expand Down Expand Up @@ -95,7 +108,3 @@ func (c *CachedProvider) needRefresh() bool {
log.Debug("Records cache last Read: ", c.lastRead, "expiration: ", c.RefreshDelay, " provider expiration:", c.lastRead.Add(c.RefreshDelay), "expired: ", time.Now().After(c.lastRead.Add(c.RefreshDelay)))
return time.Now().After(c.lastRead.Add(c.RefreshDelay))
}

func init() {
prometheus.MustRegister(cachedRecordsCallsTotal)
}

0 comments on commit 6c5faaf

Please sign in to comment.