-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcollector.go
121 lines (96 loc) · 2.41 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// SPDX-FileCopyrightText: (c) Mauve Mailorder Software GmbH & Co. KG, 2020. Licensed under [Apache 2.0](LICENSE) license.
//
// SPDX-License-Identifier: MIT
package main
import (
"bufio"
"bytes"
"io/ioutil"
"os"
"regexp"
"time"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
)
const (
ns = "lynis_"
)
var (
regex *regexp.Regexp
ageDesc *prometheus.Desc
)
func init() {
regex = regexp.MustCompile(`^([^=]+)=(.*)$`)
ageDesc = prometheus.NewDesc(ns+"report_age_seconds", "Report age in seconds", nil, nil)
}
type collector struct {
cfg *Config
descs []*prometheus.Desc
metrics []prometheus.Metric
}
func newCollector(cfg *Config) *collector {
return &collector{
cfg: cfg,
descs: []*prometheus.Desc{ageDesc},
}
}
func (c *collector) collect() error {
info, err := os.Stat(c.cfg.ReportFilePath)
if err != nil {
return errors.Wrap(err, "could not get file info for report file")
}
age := float64(time.Since(info.ModTime()).Seconds())
c.metrics = append(c.metrics, prometheus.MustNewConstMetric(ageDesc, prometheus.GaugeValue, age))
b, err := ioutil.ReadFile(c.cfg.ReportFilePath)
if err != nil {
return errors.Wrap(err, "could not read report file")
}
r := bytes.NewReader(b)
s := bufio.NewScanner(r)
for s.Scan() {
m := regex.FindStringSubmatch(s.Text())
if len(m) == 0 {
continue
}
err = c.parseForMetric(m[1], m[2])
if err != nil {
return err
}
}
return nil
}
func (c *collector) parseForMetric(field, value string) error {
def, found := c.cfg.Metrics[field]
if !found {
return nil
}
name := field
if def.MetricName != "" {
name = def.MetricName
}
desc := prometheus.NewDesc(ns+name, def.Description, nil, nil)
c.descs = append(c.descs, desc)
conv := converterByName(def.Converter)
v, err := conv(value)
if err != nil {
return errors.Wrapf(err, "could not parse value (%s) from field %s", value, field)
}
m, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, v)
if err != nil {
return errors.Wrapf(err, "invalid metric definition for field %s", field)
}
c.metrics = append(c.metrics, m)
return nil
}
// Describe implements prometheus.Collector interface
func (c *collector) Describe(ch chan<- *prometheus.Desc) {
for _, d := range c.descs {
ch <- d
}
}
// Collect implements prometheus.Collector interface
func (c *collector) Collect(ch chan<- prometheus.Metric) {
for _, m := range c.metrics {
ch <- m
}
}