-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathping.go
120 lines (106 loc) · 2.51 KB
/
ping.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
package main
import (
"crypto/tls"
"fmt"
"math/rand"
"net"
"strings"
"time"
"github.com/mehrdadrad/ping"
probing "github.com/prometheus-community/pro-bing"
"github.com/valyala/fasthttp"
)
func endpointPing(endpoint string) (time.Duration, error) {
if strings.HasPrefix(endpoint, "http") {
return httpPing(endpoint)
} else if strings.HasPrefix(endpoint, "tcp") {
address := strings.TrimPrefix(endpoint, "tcp://")
return tcpPing(address)
}
if args.AltPing {
return icmpAltPing(endpoint)
}
return icmpPing(endpoint)
}
func icmpPing(endpoint string) (time.Duration, error) {
pinger, err := probing.NewPinger(endpoint)
if err != nil {
return 0, err
}
defer pinger.Stop()
pinger.Count = args.Count
pinger.Timeout = args.Timeout
resolve_count := 0
for {
err = pinger.Resolve()
if err == nil || resolve_count > 3 {
break
}
resolve_count++
time.Sleep(time.Millisecond * time.Duration(rand.Intn(200)))
}
err = pinger.Run()
if err != nil {
return 0, err
}
return pinger.Statistics().AvgRtt, nil
}
func icmpAltPing(endpoint string) (time.Duration, error) {
pinger, err := ping.New(endpoint)
if err != nil {
return 0, err
}
pinger.SetCount(args.Count)
pinger.SetTimeout(args.Timeout.String())
r, err := pinger.Run()
if err != nil {
return 0, err
}
var rtt float64
var count_success int
for pr := range r {
if pr.Err == nil && pr.RTT > 0 {
rtt += pr.RTT
count_success++
}
}
return time.Duration((rtt / float64(count_success)) * float64(time.Millisecond)), nil
}
func httpPing(url string) (time.Duration, error) {
var rtt time.Duration
client := fasthttp.Client{
ReadTimeout: args.Timeout,
TLSConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
req := fasthttp.AcquireRequest()
req.Header.SetMethod(fasthttp.MethodGet)
defer fasthttp.ReleaseRequest(req)
for i := 0; i < args.Count; i++ {
stampedURL := fmt.Sprintf("%s?%d", url, time.Now().UnixNano()/int64(time.Millisecond))
req.SetRequestURI(stampedURL)
start := time.Now()
resp := fasthttp.AcquireResponse()
err := client.Do(req, resp)
fasthttp.ReleaseResponse(resp)
if err != nil {
return 0, err
}
rtt += time.Since(start)
}
return rtt / time.Duration(args.Count), nil
}
func tcpPing(endpoint string) (time.Duration, error) {
var rtt time.Duration
for i := 0; i < args.Count; i++ {
start := time.Now()
conn, err := net.DialTimeout("tcp", endpoint, args.Timeout)
if err != nil {
return 0, err
}
conn.Close()
rtt += time.Since(start)
}
return rtt / time.Duration(args.Count), nil
}