forked from mcelep/opa-scorecard
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
99 lines (82 loc) · 2.31 KB
/
main.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
package main
import (
"flag"
"log"
"net/http"
"time"
"github.com/mcelep/opa_scorecard_exporter/pkg/opa"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
listenAddress = flag.String("web.listen-address", ":9141",
"Address to listen on for telemetry")
metricsPath = flag.String("web.telemetry-path", "/metrics",
"Path under which to expose metrics")
inCluster = flag.Bool("incluster", false,
"Does the exporter run within a K8S cluster, when true it will try to look for K8S service account details in the usual location.")
ticker *time.Ticker
done = make(chan bool)
metrics = opa.MetricSet{Metrics: make(map[string]prometheus.Metric)}
)
type Exporter struct {
}
func NewExporter() *Exporter {
return &Exporter{}
}
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
ch <- opa.Up
ch <- opa.ConstraintViolation
ch <- opa.ConstraintInformation
}
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
ch <- prometheus.MustNewConstMetric(
opa.Up, prometheus.GaugeValue, 1,
)
metrics.RLock()
for _, m := range metrics.Metrics {
ch <- m
}
metrics.RUnlock()
}
func (e *Exporter) startScheduled(t time.Duration) {
ticker = time.NewTicker(t)
go func() {
for {
select {
case <-done:
return
case t := <-ticker.C:
log.Println("Tick at", t)
constraints, err := opa.GetConstraints(inCluster)
if err != nil {
log.Printf("%+v\n", err)
}
allMetrics := make(map[string]prometheus.Metric)
opa.ExportViolations(constraints, allMetrics)
opa.ExportConstraintInformation(constraints, allMetrics)
metrics.Lock()
metrics.Metrics = allMetrics
metrics.Unlock()
}
}
}()
}
func main() {
flag.Parse()
exporter := NewExporter()
exporter.startScheduled(10 * time.Second)
prometheus.Unregister(prometheus.NewGoCollector())
prometheus.MustRegister(exporter)
http.Handle(*metricsPath, promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>OPA ScoreCard Exporter</title></head>
<body>
<h1>OPA ScoreCard Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}