File: gauge.go

package info (click to toggle)
golang-github-containerd-nydus-snapshotter 0.13.4-2.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,824 kB
  • sloc: sh: 470; makefile: 129
file content (85 lines) | stat: -rw-r--r-- 1,739 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
 * Copyright (c) 2021. Ant Group. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 */

package ttl

import (
	"strings"
	"sync"
	"time"

	"github.com/prometheus/client_golang/prometheus"
)

var (
	defaultCleanUpPeriod = 10 * time.Minute
	DefaultTTL           = 3 * time.Minute
)

type LabelWithValue struct {
	name  string
	value string
}

type GaugeVec struct {
	labelName     []string
	ttl           time.Duration
	labelValueMap map[LabelWithValue]time.Time
	mu            sync.Mutex
	*prometheus.GaugeVec
}

type GaugeWithTTL struct {
	labelValue []string
	vec        *GaugeVec
	gauge      prometheus.Gauge
}

func NewGaugeVecWithTTL(opts prometheus.GaugeOpts, labelNames []string, ttl time.Duration) *GaugeVec {
	gaugeVec := prometheus.NewGaugeVec(opts, labelNames)
	res := &GaugeVec{
		labelName:     labelNames,
		ttl:           ttl,
		GaugeVec:      gaugeVec,
		labelValueMap: make(map[LabelWithValue]time.Time),
	}
	go res.cleanUpExpired()
	return res
}

func (gv *GaugeVec) cleanUpExpired() {
	timer := time.NewTicker(defaultCleanUpPeriod)

	for range timer.C {
		gv.mu.Lock()
		for k, v := range gv.labelValueMap {
			if time.Now().After(v) {
				gv.DeleteLabelValues(k.value)
				delete(gv.labelValueMap, k)
			}
		}
		gv.mu.Unlock()
	}
}

func (gv *GaugeVec) WithLabelValues(val ...string) *GaugeWithTTL {
	gauge := gv.GaugeVec.WithLabelValues(val...)
	return &GaugeWithTTL{
		vec:        gv,
		labelValue: val,
		gauge:      gauge,
	}
}

func (gwt *GaugeWithTTL) Set(val float64) {
	gwt.vec.mu.Lock()
	gwt.vec.labelValueMap[LabelWithValue{
		name:  strings.Join(gwt.vec.labelName, ","),
		value: strings.Join(gwt.labelValue, ","),
	}] = time.Now().Add(gwt.vec.ttl)
	gwt.vec.mu.Unlock()
	gwt.gauge.Set(val)
}