-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
426 lines (339 loc) · 11.5 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//nolint:gochecknoglobals
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/VictoriaMetrics/metrics"
"github.com/go-playground/validator/v10"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.xsfx.dev/logginghandler"
)
var (
version = "dev"
commit = "none"
date = "unknown"
)
// rootCmd is the command line interface.
var rootCmd = &cobra.Command{
Use: "iperf3exporter",
Run: func(cmd *cobra.Command, args []string) {
if versionFlag {
fmt.Printf("iperf3exporter %s, commit %s, %s", version, commit, date) //nolint:forbidigo
return
}
http.Handle("/probe", logginghandler.Handler(http.HandlerFunc(probeHandler)))
log.Info().Str("listen", c.Exporter.Listen).Msg("starting...")
log.Fatal().Err(http.ListenAndServe(c.Exporter.Listen, nil)).Msg("goodbye")
},
}
// config is a struct that a config file can get unmarshaled to.
type config struct {
Exporter struct {
Listen string `validate:"required,hostname_port"`
Timeout time.Duration `validate:"required,gt=0"`
ProcessMetrics bool `mapstructure:"process_metrics" validate:"required"`
}
Log struct {
JSON bool
Colors bool `validate:"required"`
}
Iperf3 struct {
Time int `validate:"required"`
Wait time.Duration `validation:"required,min=1ms"`
}
}
// c is a global config struct instance.
var c config
var (
cfgFile string
versionFlag bool
)
var (
downloadSentBitsPerSecond = metrics.NewFloatCounter("iperf3_download_sent_bits_per_second")
downloadSentSeconds = metrics.NewFloatCounter("iperf3_download_sent_seconds")
downloadSentBytes = metrics.NewFloatCounter("iperf3_download_sent_bytes")
downloadSentRetransmits = metrics.NewFloatCounter("iperf3_download_sent_retransmits")
downloadReceivedBitsPerSecond = metrics.NewFloatCounter("iperf3_download_received_bits_per_second")
downloadReceivedSeconds = metrics.NewFloatCounter("iperf3_download_received_seconds")
downloadReceivedBytes = metrics.NewFloatCounter("iperf3_download_received_bytes")
)
var (
uploadSentBitsPerSecond = metrics.NewFloatCounter("iperf3_upload_sent_bits_per_second")
uploadSentSeconds = metrics.NewFloatCounter("iperf3_upload_sent_seconds")
uploadSentBytes = metrics.NewFloatCounter("iperf3_upload_sent_bytes")
uploadSentRetransmits = metrics.NewFloatCounter("iperf3_upload_sent_retransmits")
uploadReceivedBitsPerSecond = metrics.NewFloatCounter("iperf3_upload_received_bits_per_second")
uploadReceivedSeconds = metrics.NewFloatCounter("iperf3_upload_received_seconds")
uploadReceivedBytes = metrics.NewFloatCounter("iperf3_upload_received_bytes")
)
var scrapeErrors = metrics.NewCounter("iperf3_errors")
//nolint:tagliatelle
type iperfResult struct {
End struct {
SumSent struct {
Seconds float64 `json:"seconds"`
Bytes float64 `json:"bytes"`
BitsPerSecond float64 `json:"bits_per_second"`
Retransmits int `json:"retransmits"`
} `json:"sum_sent"`
SumReceived struct {
Seconds float64 `json:"seconds"`
Bytes float64 `json:"bytes"`
BitsPerSecond float64 `json:"bits_per_second"`
} `json:"sum_received"`
} `json:"end"`
}
type Target struct {
Host string
Port int
}
var (
ErrEmptyTarget = errors.New("empty target")
ErrCouldNotDetermineTarget = errors.New("could not determine target")
)
func NewTarget(t string) (Target, error) {
targetParts := strings.Split(t, ":")
var trg Target
//nolint:gomnd
switch s := len(targetParts); {
case s > 2:
// http.Error(w, "could not determine host and port", http.StatusUnprocessableEntity)
return trg, ErrCouldNotDetermineTarget
case s == 2:
p, err := strconv.Atoi(targetParts[1])
if err != nil {
return trg, fmt.Errorf("could not convert port string to int: %w", err)
}
trg = Target{
Host: targetParts[0],
Port: p,
}
case s == 1:
// Using default port.
trg = Target{
Host: targetParts[0],
Port: 5201,
}
}
// Check for empty struct.
if trg.Host == "" || trg.Port == 0 {
return Target{}, ErrEmptyTarget
}
return trg, nil
}
func runIperf(ctx context.Context, t Target, cmdArgs []string, logger zerolog.Logger) (iperfResult, error) {
args := []string{
"-J",
"-c",
t.Host,
"-p",
fmt.Sprintf("%d", t.Port),
"-t", strconv.Itoa(c.Iperf3.Time),
}
args = append(args, cmdArgs...)
cmd := exec.CommandContext(ctx, "iperf3", args...)
logger.Debug().Str("cmd", cmd.String()).Msg("created command")
// Buffers to store stdout and stderr.
var outb, errb bytes.Buffer
cmd.Stdout = &outb
cmd.Stderr = &errb
if err := cmd.Run(); err != nil {
logger.Debug().
Str("stdout", outb.String()).
Str("stderr", errb.String()).
Msg("output from failed run")
return iperfResult{}, fmt.Errorf("could not run command: %w", err)
}
// Unmarshal the output to the iperf struct.
var p iperfResult
if err := json.Unmarshal(outb.Bytes(), &p); err != nil {
return iperfResult{}, fmt.Errorf("could not unmarshal result: %w", err)
}
return p, nil
}
func download(ctx context.Context, t Target, logger zerolog.Logger) error {
r, err := runIperf(
ctx,
t,
[]string{"-R"},
logger,
)
if err != nil {
return fmt.Errorf("could not get download metrics: %w", err)
}
downloadSentBitsPerSecond.Set(r.End.SumSent.BitsPerSecond)
downloadSentBytes.Set(r.End.SumSent.Bytes)
downloadSentSeconds.Set(r.End.SumSent.Seconds)
downloadSentRetransmits.Set(float64(r.End.SumSent.Retransmits))
downloadReceivedBitsPerSecond.Set(r.End.SumReceived.BitsPerSecond)
downloadReceivedBytes.Set(r.End.SumReceived.Bytes)
downloadReceivedSeconds.Set(r.End.SumReceived.Seconds)
return nil
}
func upload(ctx context.Context, t Target, logger zerolog.Logger) error {
r, err := runIperf(
ctx,
t,
[]string{},
logger,
)
if err != nil {
return fmt.Errorf("could not get upload metrics: %w", err)
}
uploadSentBitsPerSecond.Set(r.End.SumSent.BitsPerSecond)
uploadSentBytes.Set(r.End.SumSent.Bytes)
uploadSentSeconds.Set(r.End.SumSent.Seconds)
uploadSentRetransmits.Set(float64(r.End.SumSent.Retransmits))
uploadReceivedBitsPerSecond.Set(r.End.SumReceived.BitsPerSecond)
uploadReceivedBytes.Set(r.End.SumReceived.Bytes)
uploadReceivedSeconds.Set(r.End.SumReceived.Seconds)
return nil
}
func probeHandler(w http.ResponseWriter, r *http.Request) {
logger := logginghandler.Logger(r)
// Extract target.
trgt := r.URL.Query().Get("target")
if trgt == "" {
logger.Error().Msg("could not find target in url params")
http.Error(w, "could not find target in url params", http.StatusUnprocessableEntity)
return
}
logger.Debug().Str("trgt", trgt).Msg("extracted target from url params")
// Extract port and host for target.
t, err := NewTarget(trgt)
if err != nil {
scrapeErrors.Inc()
logger.Error().Err(err).Msg("could not determine target")
http.Error(w, "could not determine target", http.StatusUnprocessableEntity)
}
ctx, cancel := context.WithTimeout(context.Background(), c.Exporter.Timeout)
defer cancel()
logger.Info().Msg("getting download metrics")
if err := download(ctx, t, logger); err != nil {
scrapeErrors.Inc()
logger.Error().Err(err).Msg("could not create download metrics")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
logger.Debug().Dur("wait", c.Iperf3.Wait).Msg("waiting")
time.Sleep(c.Iperf3.Wait)
logger.Info().Msg("getting upload metrics")
if err := upload(ctx, t, logger); err != nil {
scrapeErrors.Inc()
logger.Error().Err(err).Msg("could not create upload metrics")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
logger.Info().Msg("done scraping")
metrics.WritePrometheus(w, c.Exporter.ProcessMetrics)
}
func init() { //nolint:gochecknoinits,funlen
cobra.OnInitialize(initConfig)
// Version.
rootCmd.PersistentFlags().BoolVarP(&versionFlag, "version", "v", false, "print version")
// Config.
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "config file")
// Exporter.Listen.
rootCmd.PersistentFlags().String("listen", "127.0.0.1:9119", "listen string")
if err := viper.BindPFlag("exporter.listen", rootCmd.PersistentFlags().Lookup("listen")); err != nil {
log.Fatal().Err(err).Msg("could not bind flag")
}
viper.SetDefault("exporter.listen", "127.0.0.1:9119")
// Exporter.Timeout.
rootCmd.PersistentFlags().Duration("timeout", time.Minute, "scraping timeout")
if err := viper.BindPFlag("exporter.timeout", rootCmd.PersistentFlags().Lookup("timeout")); err != nil {
log.Fatal().Err(err).Msg("could not bind flag")
}
viper.SetDefault("exporter.timeout", time.Minute)
// Exporter.ProcessMetrics.
rootCmd.PersistentFlags().Bool("process-metrics", true, "exporter process metrics")
if err := viper.BindPFlag("exporter.processmetrics", rootCmd.PersistentFlags().Lookup("process-metrics")); err != nil {
log.Fatal().Err(err).Msg("could not bind flag")
}
viper.SetDefault("exporter.process_metrics", true)
// Log.JSON.
rootCmd.PersistentFlags().Bool("log-json", false, "JSON log output")
if err := viper.BindPFlag("log.json", rootCmd.PersistentFlags().Lookup("log-json")); err != nil {
log.Fatal().Err(err).Msg("could not bind flag")
}
viper.SetDefault("log.json", false)
// Log.Colors.
rootCmd.PersistentFlags().Bool("log-colors", true, "colorful log output")
if err := viper.BindPFlag("log.colors", rootCmd.PersistentFlags().Lookup("log-colors")); err != nil {
log.Fatal().Err(err).Msg("could not bind flag")
}
viper.SetDefault("log.colors", true)
// Iperf3.Time.
rootCmd.PersistentFlags().Int("time", 5, "time in seconds to transmit for") //nolint:gomnd
if err := viper.BindPFlag("iperf3.time", rootCmd.PersistentFlags().Lookup("time")); err != nil {
log.Fatal().Err(err).Msg("could not bind flag")
}
viper.SetDefault("iperf3.time", 5) //nolint:gomnd
// IPerf3.Wait.
rootCmd.PersistentFlags().Duration("wait", time.Second, "time to wait between download and upload runs")
if err := viper.BindPFlag("iperf3.wait", rootCmd.PersistentFlags().Lookup("wait")); err != nil {
log.Fatal().Err(err).Msg("could not bind flag")
}
}
func initConfig() {
// Load config file.
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
if err := viper.ReadInConfig(); err != nil {
log.Fatal().Err(err).Msg("error on reading config")
}
}
// Environment variable handling.
viper.SetEnvPrefix("IPERF3EXPORTER")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
// Unmarshal config.
if err := viper.Unmarshal(&c); err != nil {
log.Fatal().Err(err).Msg("could not unmarshal config")
}
// Setting up logging.
switch c.Log.JSON {
case false:
if c.Log.Colors {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
} else {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, NoColor: true})
}
case true:
log.Logger = zerolog.New(os.Stderr).With().Timestamp().Logger()
}
log.Logger = log.With().Caller().Logger()
// Valite config.
validate := validator.New()
if err := validate.Struct(c); err != nil {
var validationErrors validator.ValidationErrors
if errors.As(err, &validationErrors) {
for _, e := range validationErrors {
log.Error().
Str("tag", e.Tag()).
Str("name", e.StructNamespace()).
Interface("value", e.Value()).
Str("kind", e.Kind().String()).
Msg("config error")
}
}
log.Fatal().Msg("config validation error")
}
}
func main() {
if err := rootCmd.Execute(); err != nil {
log.Fatal().Err(err).Msg("goodbye")
}
}