-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (81 loc) · 2.33 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
package main
import (
"flag"
"fmt"
"log"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/showwin/speedtest-go/speedtest"
)
var (
latency = time.Duration(0)
downspeed = 0.0
upspeed = 0.0
interval int
port int
)
func init() {
flag.IntVar(&interval, "interval", 30, "Duration, in minutes, between speedtest runs")
flag.IntVar(&port, "port", 9091, "The port to listen on")
flag.Parse()
}
func main() {
go (func() {
for {
checkSpeed()
time.Sleep(time.Minute * time.Duration(interval))
}
})()
collector := newSpeedCollector()
prometheus.MustRegister(collector)
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}
func checkSpeed() {
log.Println("Performing speedtest")
user, _ := speedtest.FetchUserInfo()
serverList, _ := speedtest.FetchServers(user)
targets, _ := serverList.FindServer([]int{})
target := targets[0]
log.Printf("Testing against server: %s - %s\n", target.Name, target.Sponsor)
target.PingTest()
target.DownloadTest(false)
target.UploadTest(false)
latency = target.Latency
downspeed = target.DLSpeed
upspeed = target.ULSpeed
log.Printf("Finished speedtest. DL=%f UL=%f Ping=%v\n", downspeed, upspeed, latency)
}
type speedCollector struct {
downMetric *prometheus.Desc
upMetric *prometheus.Desc
latencyMetric *prometheus.Desc
}
func newSpeedCollector() *speedCollector {
return &speedCollector{
downMetric: prometheus.NewDesc("speedtest_download_speed",
"Download speed in Mbit/s",
nil, nil,
),
upMetric: prometheus.NewDesc("speedtest_upload_speed",
"Upload speed in Mbit/s",
nil, nil,
),
latencyMetric: prometheus.NewDesc("speedtest_latency",
"Latency in ms",
nil, nil,
),
}
}
func (collector *speedCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- collector.downMetric
ch <- collector.upMetric
ch <- collector.latencyMetric
}
func (collector *speedCollector) Collect(ch chan<- prometheus.Metric) {
ch <- prometheus.MustNewConstMetric(collector.downMetric, prometheus.CounterValue, downspeed)
ch <- prometheus.MustNewConstMetric(collector.upMetric, prometheus.CounterValue, upspeed)
ch <- prometheus.MustNewConstMetric(collector.latencyMetric, prometheus.CounterValue, float64(latency.Milliseconds()))
}