Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/crow/samples.go
4094 views
1
package crow
2
3
import (
4
"fmt"
5
"math/rand"
6
"time"
7
8
"github.com/prometheus/client_golang/prometheus"
9
)
10
11
type sample struct {
12
ScrapeTime time.Time
13
Labels prometheus.Labels
14
Value float64
15
16
// How many times this sample has attempted to be validated. Starts at 0.
17
ValidationAttempt int
18
}
19
20
// Ready checks if this sample is ready to be validated.
21
func (s *sample) Ready(now time.Time) bool {
22
backoff := sampleBackoff(s.ValidationAttempt)
23
return now.After(s.ScrapeTime.Add(backoff))
24
}
25
26
func sampleBackoff(attempt int) time.Duration {
27
// Exponential backoff from 1s up to 1s + (250ms * 2^attempt).
28
return time.Second + (250 * time.Millisecond * 1 << attempt)
29
}
30
31
type sampleGenerator struct {
32
numSamples int
33
sendCh chan<- []*sample
34
r *rand.Rand
35
}
36
37
const validationSampleName = "crow_validation_sample"
38
39
func (sg *sampleGenerator) Describe(ch chan<- *prometheus.Desc) {
40
ch <- prometheus.NewDesc(
41
validationSampleName, "Sample to validate",
42
[]string{"sample_num"},
43
prometheus.Labels{},
44
)
45
}
46
47
func (sg *sampleGenerator) Collect(ch chan<- prometheus.Metric) {
48
var (
49
scrapeTime = time.Now()
50
51
sampleLabel = "sample_num"
52
desc = prometheus.NewDesc(
53
validationSampleName, "Sample to validate",
54
[]string{sampleLabel},
55
prometheus.Labels{},
56
)
57
58
usedLabels = map[string]struct{}{}
59
samples = make([]*sample, sg.numSamples)
60
)
61
62
for s := 0; s < sg.numSamples; s++ {
63
GenLabel:
64
labelSuffix := make([]byte, 1)
65
_, _ = sg.r.Read(labelSuffix)
66
label := fmt.Sprintf("sample_%x", labelSuffix)
67
if _, exist := usedLabels[label]; exist {
68
goto GenLabel
69
}
70
usedLabels[label] = struct{}{}
71
72
samples[s] = &sample{
73
ScrapeTime: scrapeTime,
74
Labels: prometheus.Labels{sampleLabel: label},
75
Value: float64(sg.r.Int63n(1_000_000)),
76
}
77
ch <- prometheus.MustNewConstMetric(
78
desc,
79
prometheus.GaugeValue,
80
samples[s].Value, samples[s].Labels[sampleLabel],
81
)
82
}
83
84
sg.sendCh <- samples
85
}
86
87