/
serve.go
178 lines (158 loc) · 5.33 KB
/
serve.go
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
// Copyright 2022 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 metrics
import (
"fmt"
"math/rand"
"net/http"
"strings"
"sync"
"time"
health "github.com/nelkinda/health-go"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
promRegistry = prometheus.NewRegistry() // local Registry so we don't get Go metrics, etc.
valGenerator = rand.New(rand.NewSource(time.Now().UnixNano()))
metrics = make([]*prometheus.GaugeVec, 0)
metricsMux = &sync.Mutex{}
)
func registerMetrics(metricCount, metricLength, metricCycle int, labelKeys []string) {
metrics = make([]*prometheus.GaugeVec, metricCount)
for idx := 0; idx < metricCount; idx++ {
gauge := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: fmt.Sprintf("avalanche_metric_%s_%v_%v", strings.Repeat("m", metricLength), metricCycle, idx),
Help: "A tasty metric morsel",
}, append([]string{"series_id", "cycle_id"}, labelKeys...))
promRegistry.MustRegister(gauge)
metrics[idx] = gauge
}
}
func unregisterMetrics() {
for _, metric := range metrics {
promRegistry.Unregister(metric)
}
}
func seriesLabels(seriesID, cycleID int, labelKeys, labelValues []string) prometheus.Labels {
labels := prometheus.Labels{
"series_id": fmt.Sprintf("%v", seriesID),
"cycle_id": fmt.Sprintf("%v", cycleID),
}
for idx, key := range labelKeys {
labels[key] = labelValues[idx]
}
return labels
}
func deleteValues(labelKeys, labelValues []string, seriesCount, seriesCycle int) {
for _, metric := range metrics {
for idx := 0; idx < seriesCount; idx++ {
labels := seriesLabels(idx, seriesCycle, labelKeys, labelValues)
metric.Delete(labels)
}
}
}
func cycleValues(labelKeys, labelValues []string, seriesCount, seriesCycle int) {
for _, metric := range metrics {
for idx := 0; idx < seriesCount; idx++ {
labels := seriesLabels(idx, seriesCycle, labelKeys, labelValues)
metric.With(labels).Set(float64(valGenerator.Intn(100)))
}
}
}
// RunMetrics creates a set of Prometheus test series that update over time
func RunMetrics(metricCount, labelCount, seriesCount, metricLength, labelLength, valueInterval, seriesInterval, metricInterval int, constLabels []string, stop chan struct{}) (chan struct{}, error) {
labelKeys := make([]string, labelCount)
for idx := 0; idx < labelCount; idx++ {
labelKeys[idx] = fmt.Sprintf("label_key_%s_%v", strings.Repeat("k", labelLength), idx)
}
labelValues := make([]string, labelCount)
for idx := 0; idx < labelCount; idx++ {
labelValues[idx] = fmt.Sprintf("label_val_%s_%v", strings.Repeat("v", labelLength), idx)
}
for _, cLabel := range constLabels {
split := strings.Split(cLabel, "=")
if len(split) != 2 {
return make(chan struct{}, 1), fmt.Errorf("Constant label argument must have format labelName=labelValue but got %s", cLabel)
}
labelKeys = append(labelKeys, split[0])
labelValues = append(labelValues, split[1])
}
metricCycle := 0
seriesCycle := 0
registerMetrics(metricCount, metricLength, metricCycle, labelKeys)
cycleValues(labelKeys, labelValues, seriesCount, seriesCycle)
valueTick := time.NewTicker(time.Duration(valueInterval) * time.Second)
seriesTick := time.NewTicker(time.Duration(seriesInterval) * time.Second)
metricTick := time.NewTicker(time.Duration(metricInterval) * time.Second)
updateNotify := make(chan struct{}, 1)
go func() {
for tick := range valueTick.C {
fmt.Printf("%v: refreshing metric values\n", tick)
metricsMux.Lock()
cycleValues(labelKeys, labelValues, seriesCount, seriesCycle)
metricsMux.Unlock()
select {
case updateNotify <- struct{}{}:
default:
}
}
}()
go func() {
for tick := range seriesTick.C {
fmt.Printf("%v: refreshing series cycle\n", tick)
metricsMux.Lock()
deleteValues(labelKeys, labelValues, seriesCount, seriesCycle)
seriesCycle++
cycleValues(labelKeys, labelValues, seriesCount, seriesCycle)
metricsMux.Unlock()
select {
case updateNotify <- struct{}{}:
default:
}
}
}()
go func() {
for tick := range metricTick.C {
fmt.Printf("%v: refreshing metric cycle\n", tick)
metricsMux.Lock()
metricCycle++
unregisterMetrics()
registerMetrics(metricCount, metricLength, metricCycle, labelKeys)
cycleValues(labelKeys, labelValues, seriesCount, seriesCycle)
metricsMux.Unlock()
select {
case updateNotify <- struct{}{}:
default:
}
}
}()
go func() {
<-stop
valueTick.Stop()
seriesTick.Stop()
metricTick.Stop()
}()
return updateNotify, nil
}
// ServeMetrics serves a prometheus metrics endpoint with test series
func ServeMetrics(port int) error {
http.Handle("/metrics", promhttp.HandlerFor(promRegistry, promhttp.HandlerOpts{}))
h := health.New(health.Health{})
http.HandleFunc("/health", h.Handler)
err := http.ListenAndServe(fmt.Sprintf(":%v", port), nil)
if err != nil {
return err
}
return nil
}