-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
111 lines (97 loc) · 2.65 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
package main
import (
"fmt"
"net"
"time"
"net/http"
"github.com/go-ping/ping"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
fqdn = []string{"ipv4.google.com", "ipv6.google.com"}
)
func main() {
pingSuccess := make(map[string]prometheus.Gauge)
pingDuration := make(map[string]prometheus.Gauge)
for _, fqdn := range fqdn {
pingSuccess[fqdn] = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "ping_success",
Help: "Indicates if the ping was successful or not",
ConstLabels: prometheus.Labels{"fqdn": fqdn},
},
)
pingDuration[fqdn] = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "ping_duration_seconds",
Help: "Duration of the ping in seconds",
ConstLabels: prometheus.Labels{"fqdn": fqdn},
},
)
prometheus.MustRegister(pingSuccess[fqdn])
prometheus.MustRegister(pingDuration[fqdn])
}
go func() {
http.Handle("/metrics", promhttp.Handler())
err := http.ListenAndServe(":8081", nil)
if err != nil {
panic(err)
}
}()
for {
for _, fqdn := range fqdn {
ipv4Addr, err := net.ResolveIPAddr("ip4", fqdn)
if err == nil {
pinger, err := ping.NewPinger(ipv4Addr.String())
if err != nil {
pingSuccess[fqdn].Set(0)
pingDuration[fqdn].Set(0)
fmt.Printf("Error creating IPv4 pinger for %s: %v\n", fqdn, err)
continue
}
pinger.SetPrivileged(true)
pinger.OnRecv = func(pkt *ping.Packet) {
pingSuccess[fqdn].Set(1)
pingDuration[fqdn].Set(pkt.Rtt.Seconds())
}
pinger.OnFinish = func(stats *ping.Statistics) {
if stats.PacketsRecv == 0 {
pingSuccess[fqdn].Set(0)
pingDuration[fqdn].Set(0)
fmt.Printf("Error pinging IPv4 %s: Request timed out\n", fqdn)
}
}
pinger.Count = 1
pinger.Timeout = time.Second * 5
go pinger.Run()
}
ipv6Addr, err := net.ResolveIPAddr("ip6", fqdn)
if err == nil {
pinger, err := ping.NewPinger(ipv6Addr.String())
if err != nil {
pingSuccess[fqdn].Set(0)
pingDuration[fqdn].Set(0)
fmt.Printf("Error creating IPv6 pinger for %s: %v\n", fqdn, err)
continue
}
pinger.SetPrivileged(true)
pinger.OnRecv = func(pkt *ping.Packet) {
pingSuccess[fqdn].Set(1)
pingDuration[fqdn].Set(pkt.Rtt.Seconds())
}
pinger.OnFinish = func(stats *ping.Statistics) {
if stats.PacketsRecv == 0 {
pingSuccess[fqdn].Set(0)
pingDuration[fqdn].Set(0)
fmt.Printf("Error pinging IPv6 %s: Request timed out\n", fqdn)
}
}
pinger.Count = 1
pinger.Timeout = time.Second * 5
go pinger.Run()
}
}
time.Sleep(time.Second * 30)
}
}