/
fast.go
95 lines (82 loc) · 2.21 KB
/
fast.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
package collector
import (
"sync"
"time"
"github.com/caarlos0/fastcom-exporter/fast"
"github.com/patrickmn/go-cache"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/zerolog/log"
)
type fastCollector struct {
mutex sync.Mutex
cache *cache.Cache
up *prometheus.Desc
scrapeDuration *prometheus.Desc
downloadBytes *prometheus.Desc
}
// NewFastCollector returns a fast.com collector
func NewFastCollector(cache *cache.Cache) prometheus.Collector {
const namespace = "fastcom"
return &fastCollector{
cache: cache,
up: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "up"),
"Exporter is up",
nil,
nil,
),
scrapeDuration: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "", "scrape_duration_seconds"),
"Returns how long the probe took to complete in seconds",
nil,
nil,
),
downloadBytes: prometheus.NewDesc(
prometheus.BuildFQName(namespace, "download", "bytes_second"),
"Download speed in B/s",
nil,
nil,
),
}
}
// Describe all metrics
func (c *fastCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.up
ch <- c.scrapeDuration
ch <- c.downloadBytes
}
// Collect all metrics
func (c *fastCollector) Collect(ch chan<- prometheus.Metric) {
c.mutex.Lock()
defer c.mutex.Unlock()
start := time.Now()
success := 1
defer func() {
ch <- prometheus.MustNewConstMetric(c.scrapeDuration, prometheus.GaugeValue, time.Since(start).Seconds())
ch <- prometheus.MustNewConstMetric(c.up, prometheus.GaugeValue, float64(success))
}()
result, err := c.cachedOrCollect()
if err != nil {
success = 0
log.Error().Err(err).Msg("fast.com collector failed")
}
ch <- prometheus.MustNewConstMetric(c.downloadBytes, prometheus.GaugeValue, result)
}
func (c *fastCollector) cachedOrCollect() (float64, error) {
cold, ok := c.cache.Get("result")
if ok {
log.Debug().Msg("returning results from cache")
return cold.(float64), nil
}
hot, err := c.collect()
if err != nil {
return hot, err
}
log.Debug().Msg("returning results from api")
c.cache.Set("result", hot, cache.DefaultExpiration)
return hot, nil
}
func (c *fastCollector) collect() (float64, error) {
log.Debug().Msg("collecting fast.com metrics")
return fast.Measure()
}