cubefs

Форк
0
/
gauge.go 
150 строк · 3.1 Кб
1
// Copyright 2018 The CubeFS Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12
// implied. See the License for the specific language governing
13
// permissions and limitations under the License.
14

15
package exporter
16

17
import (
18
	"fmt"
19
	"sync"
20

21
	"github.com/cubefs/cubefs/util/log"
22
	"github.com/prometheus/client_golang/prometheus"
23
)
24

25
var (
26
	GaugeGroup sync.Map
27
	GaugeCh    chan *Gauge
28
)
29

30
func collectGauge() {
31
	GaugeCh = make(chan *Gauge, ChSize)
32
	for {
33
		m := <-GaugeCh
34
		metric := m.Metric()
35
		metric.Set(m.val)
36
		// log.LogDebugf("collect metric %v", m)
37
	}
38
}
39

40
type Gauge struct {
41
	name   string
42
	labels map[string]string
43
	val    float64
44
}
45

46
func NewGauge(name string) (g *Gauge) {
47
	g = new(Gauge)
48
	g.name = metricsName(name)
49
	return
50
}
51

52
func (c *Gauge) Key() (key string) {
53
	return stringMD5(c.Name())
54
}
55

56
func (g *Gauge) Name() string {
57
	return fmt.Sprintf("{%s: %s}", g.name, stringMapToString(g.labels))
58
}
59

60
func (g *Gauge) String() string {
61
	return fmt.Sprintf("{name: %s, labels: %s, val: %v}", g.name, stringMapToString(g.labels), g.val)
62
}
63

64
func (c *Gauge) Metric() prometheus.Gauge {
65
	metric := prometheus.NewGauge(
66
		prometheus.GaugeOpts{
67
			Name:        c.name,
68
			ConstLabels: c.labels,
69
		})
70
	key := c.Key()
71
	actualMetric, load := GaugeGroup.LoadOrStore(key, metric)
72
	if load {
73
		return actualMetric.(prometheus.Gauge)
74
	}
75

76
	if enablePush {
77
		registry.MustRegister(actualMetric.(prometheus.Collector))
78
		return actualMetric.(prometheus.Gauge)
79
	}
80

81
	err := prometheus.Register(actualMetric.(prometheus.Collector))
82
	if err == nil {
83
		log.LogInfof("register metric %v", c.Name())
84
	} else {
85
		log.LogErrorf("register metric %v, %v", c.Name(), err)
86
	}
87

88
	return actualMetric.(prometheus.Gauge)
89
}
90

91
func (g *Gauge) Set(val float64) {
92
	if !enabledPrometheus {
93
		return
94
	}
95
	g.val = val
96
	g.publish()
97
}
98

99
func (c *Gauge) publish() {
100
	select {
101
	case GaugeCh <- c:
102
	default:
103
	}
104
}
105

106
func (g *Gauge) SetWithLabels(val float64, labels map[string]string) {
107
	if !enabledPrometheus {
108
		return
109
	}
110
	g.labels = labels
111
	g.Set(val)
112
}
113

114
type GaugeVec struct {
115
	*prometheus.GaugeVec
116
}
117

118
func NewGaugeVec(name, help string, labels []string) *GaugeVec {
119
	if !enabledPrometheus {
120
		return nil
121
	}
122
	v := prometheus.NewGaugeVec(
123
		prometheus.GaugeOpts{
124
			Name: metricsName(name),
125
			Help: help,
126
		},
127
		labels,
128
	)
129

130
	if err := prometheus.Register(v); err != nil {
131
		log.LogErrorf("prometheus register gaugevec name:%v, labels:{%v} error: %v", name, labels, err)
132
		return nil
133
	}
134

135
	return &GaugeVec{GaugeVec: v}
136
}
137

138
func (v *GaugeVec) SetWithLabelValues(val float64, lvs ...string) {
139
	if m, err := v.GetMetricWithLabelValues(lvs...); err == nil {
140
		m.Set(val)
141
	}
142
}
143

144
func (v *GaugeVec) SetBoolWithLabelValues(val bool, lvs ...string) {
145
	if val {
146
		v.SetWithLabelValues(float64(1), lvs...)
147
	} else {
148
		v.SetWithLabelValues(0, lvs...)
149
	}
150
}
151

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.