-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
192 lines (157 loc) · 6.1 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// SPDX-License-Identifier: MIT
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"github.com/czerwonk/ovirt_api/api"
"github.com/czerwonk/ovirt_exporter/pkg/collector"
"github.com/czerwonk/ovirt_exporter/pkg/host"
"github.com/czerwonk/ovirt_exporter/pkg/storagedomain"
"github.com/czerwonk/ovirt_exporter/pkg/vm"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
)
const version string = "0.10.1"
var (
showVersion = flag.Bool("version", false, "Print version information.")
listenAddress = flag.String("web.listen-address", ":9325", "Address on which to expose metrics and web interface.")
metricsPath = flag.String("web.telemetry-path", "/metrics", "Path under which to expose metrics.")
apiURL = flag.String("api.url", "https://localhost/ovirt-engine/api/", "API REST Endpoint")
apiUser = flag.String("api.username", "user@internal", "API username")
apiPass = flag.String("api.password", "", "API password")
apiPassFile = flag.String("api.password-file", "", "File containing the API password")
apiInsecureCert = flag.Bool("api.insecure-cert", false, "Skip verification for untrusted SSL/TLS certificates")
withSnapshots = flag.Bool("with-snapshots", true, "Collect snapshot metrics (can be time consuming in some cases)")
withNetwork = flag.Bool("with-network", true, "Collect network metrics (can be time consuming in some cases)")
withDisks = flag.Bool("with-disks", true, "Collect disk metrics (can be time consuming in some cases)")
debug = flag.Bool("debug", false, "Show verbose output (e.g. body of each response received from API)")
tlsEnabled = flag.Bool("tls.enabled", false, "Enables TLS")
tlsCertChainPath = flag.String("tls.cert-file", "", "Path to TLS cert file")
tlsKeyPath = flag.String("tls.key-file", "", "Path to TLS key file")
tracingEnabled = flag.Bool("tracing.enabled", false, "Enables tracing using OpenTelemetry")
tracingProvider = flag.String("tracing.provider", "", "Sets the tracing provider (stdout or collector)")
tracingCollectorEndpoint = flag.String("tracing.collector.grpc-endpoint", "", "Sets the tracing provider (stdout or collector)")
collectorDuration = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "ovirt_collectors_duration",
Help: "Histogram of latencies for metric collectors.",
Buckets: []float64{.1, .2, .4, 1, 3, 8, 20, 60},
},
[]string{"collector"},
)
)
func init() {
flag.Usage = func() {
fmt.Println("Usage: ovirt_exporter [ ... ]\n\nParameters:")
fmt.Println()
flag.PrintDefaults()
}
}
func main() {
flag.Parse()
if *showVersion {
printVersion()
os.Exit(0)
}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
shutdownTracing, err := initTracing(ctx)
if err != nil {
log.Fatalf("could not initialize tracing: %v", err)
}
defer shutdownTracing()
startServer()
}
func printVersion() {
fmt.Println("ovirt_exporter")
fmt.Printf("Version: %s\n", version)
fmt.Println("Author(s): Daniel Czerwonk")
fmt.Println("Metric exporter for oVirt engine")
}
func startServer() {
log.Infof("Starting oVirt exporter (Version: %s)", version)
http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte(`<html>
<head><title>oVirt Exporter (Version ` + version + `)</title></head>
<body>
<h1>oVirt Exporter</h1>
<p><a href="` + *metricsPath + `">Metrics</a></p>
<h2>More information:</h2>
<p><a href="https://github.com/czerwonk/ovirt_exporter">github.com/czerwonk/ovirt_exporter</a></p>
</body>
</html>`))
})
client, err := connectAPI()
if err != nil {
log.Fatal(err)
}
defer client.Close()
reg := prometheus.NewRegistry()
reg.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
reg.MustRegister(collectors.NewGoCollector())
reg.MustRegister(collectorDuration)
http.HandleFunc(*metricsPath, func(w http.ResponseWriter, r *http.Request) {
handleMetricsRequest(w, r, client, reg)
})
log.Infof("Listening for %s on %s (TLS: %v)", *metricsPath, *listenAddress, *tlsEnabled)
if *tlsEnabled {
log.Fatal(http.ListenAndServeTLS(*listenAddress, *tlsCertChainPath, *tlsKeyPath, nil))
return
}
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
func connectAPI() (*api.Client, error) {
opts := []api.ClientOption{api.WithLogger(log.StandardLogger())}
if *debug {
opts = append(opts, api.WithDebug())
}
if *apiInsecureCert {
opts = append(opts, api.WithInsecure())
}
pass, err := apiPassword()
if err != nil {
return nil, errors.Wrap(err, "error while reading password file")
}
client, err := api.NewClient(*apiURL, *apiUser, pass, opts...)
if err != nil {
return nil, err
}
return client, err
}
func apiPassword() (string, error) {
if *apiPassFile == "" {
return *apiPass, nil
}
b, err := os.ReadFile(*apiPassFile)
if err != nil {
return "", err
}
return strings.Trim(string(b), "\n"), nil
}
func handleMetricsRequest(w http.ResponseWriter, r *http.Request, client *api.Client, appReg *prometheus.Registry) {
ctx, span := tracer.Start(r.Context(), "HandleMetricsRequest")
defer span.End()
reg := prometheus.NewRegistry()
cc := collector.NewContext(tracer, client)
reg.MustRegister(vm.NewCollector(ctx, cc.Clone(), *withSnapshots, *withNetwork, *withDisks, collectorDuration.WithLabelValues("vm")))
reg.MustRegister(host.NewCollector(ctx, cc.Clone(), *withNetwork, collectorDuration.WithLabelValues("host")))
reg.MustRegister(storagedomain.NewCollector(ctx, cc.Clone(), collectorDuration.WithLabelValues("storage")))
multiRegs := prometheus.Gatherers{
reg,
appReg,
}
l := log.New()
l.Level = log.ErrorLevel
promhttp.HandlerFor(multiRegs, promhttp.HandlerOpts{
ErrorLog: l,
ErrorHandling: promhttp.ContinueOnError,
Registry: appReg}).ServeHTTP(w, r)
}