forked from hansmi/prometheus-lvm-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collector.go
98 lines (75 loc) · 1.94 KB
/
collector.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
package main
import (
"context"
"log"
"time"
"github.com/hansmi/prometheus-lvm-exporter/lvmreport"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/singleflight"
)
type collector struct {
timeout time.Duration
load func(context.Context) (*lvmreport.ReportData, error)
upDesc *prometheus.Desc
gc []*groupCollector
}
func newEmptyCollector() *collector {
return &collector{
timeout: time.Minute,
upDesc: prometheus.NewDesc("up", "Whether scrape was successful", []string{"status"}, nil),
}
}
func newCollector() *collector {
c := newEmptyCollector()
for _, i := range allGroups {
c.gc = append(c.gc, newGroupCollector(i))
}
return c
}
func newCommandCollector(args []string) *collector {
cmd := lvmreport.NewCommand(args)
var sfg singleflight.Group
c := newCollector()
c.load = func(ctx context.Context) (*lvmreport.ReportData, error) {
// Avoid concurrent invocations
data, err, _ := sfg.Do("", func() (interface{}, error) {
return cmd.Run(ctx)
})
return data.(*lvmreport.ReportData), err
}
log.Printf("LVM command: %s", cmd.String())
return c
}
func (c *collector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.upDesc
for _, i := range c.gc {
i.describe(ch)
}
}
func (c *collector) collect(ctx context.Context, ch chan<- prometheus.Metric) error {
data, err := c.load(ctx)
if err != nil {
return err
}
g, _ := errgroup.WithContext(ctx)
for _, i := range c.gc {
i := i
g.Go(func() error {
return i.collect(ch, data)
})
}
return g.Wait()
}
func (c *collector) Collect(ch chan<- prometheus.Metric) {
ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
defer cancel()
status := float64(1)
statusMsg := ""
if err := c.collect(ctx, ch); err != nil {
log.Printf("Scrape failed: %v", err)
status = 0
statusMsg = err.Error()
}
ch <- prometheus.MustNewConstMetric(c.upDesc, prometheus.GaugeValue, status, statusMsg)
}