-
Notifications
You must be signed in to change notification settings - Fork 1
/
netselect.go
223 lines (185 loc) · 4.94 KB
/
netselect.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
package netselect
import (
"fmt"
"net"
"net/url"
"runtime"
"sort"
"time"
"github.com/pgollangi/go-ping"
)
// NetSelector represents the instance of a NetSelector
type NetSelector struct {
Hosts []*Host
Debug bool
Attempts int
Timeout time.Duration
Privileged bool
Threads int
}
// Host represents a input address to NetSelector
type Host struct {
// Unique ID
ID string
// Address of the Host. If URL provided, Host name will be extracted.
Address string
}
// HostStats represents the results of one particular host
type HostStats struct {
Host *Host
Success bool
Error error
// PacketsRecv is the number of packets received.
PacketsRecv int
// PacketsSent is the number of packets sent.
PacketsSent int
// PacketLoss is the percentage of packets lost.
PacketLoss float64
// IPAddr is the address of the host being pinged.
IPAddr *net.IPAddr
// Addr is the string address of the host being pinged.
Addr string
// Rtts is all of the round-trip times sent via this pinger.
Rtts []time.Duration
// MinRtt is the minimum round-trip time sent via this pinger.
MinRtt time.Duration
// MaxRtt is the maximum round-trip time sent via this pinger.
MaxRtt time.Duration
// AvgRtt is the average round-trip time sent via this pinger.
AvgRtt time.Duration
// StdDevRtt is the standard deviation of the round-trip times sent via
// this pinger.
StdDevRtt time.Duration
}
func isWindows() bool {
return runtime.GOOS == "windows"
}
func sanitizeHost(host *Host) error {
_, err := url.ParseRequestURI(host.Address)
if err == nil {
// Its a URL
u, err := url.Parse(host.Address)
if err != nil {
return err
}
if u.Scheme == "" || u.Host == "" {
return fmt.Errorf("invalid host address %s", host.Address)
}
host.Address = u.Hostname()
}
return nil
}
// NewHost creates and returns new Host instance
func NewHost(id string, address string) (host *Host, err error) {
// TODO validate address
host = &Host{
ID: id,
Address: address,
}
err = sanitizeHost(host)
return host, err
}
// NewNetSelector instantiate new instance of NetSelector
func NewNetSelector(hosts []*Host) (*NetSelector, error) {
return &NetSelector{
Hosts: hosts,
Attempts: 3,
Threads: 1,
Timeout: time.Second * 30,
Privileged: isWindows(),
}, nil
}
func (s *NetSelector) executePing(host *Host) *HostStats {
pinger, err := ping.NewPinger(host.Address)
if err != nil {
return &HostStats{
Host: host,
Success: false,
Error: err,
}
}
pinger.Timeout = s.Timeout
pinger.Count = s.Attempts
pinger.Debug = s.Debug
pinger.SetPrivileged(s.Privileged)
if s.Debug {
pinger.OnRecv = func(pkt *ping.Packet) {
fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v ttl=%v \n",
pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt, pkt.Ttl)
}
pinger.OnFinish = func(stats *ping.Statistics) {
fmt.Printf("\n--- %s ping statistics ---\n", stats.Addr)
fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss\n",
stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
}
}
pinger.Run() // blocks until finished
stats := pinger.Statistics() // get send/receive/rtt stats
return &HostStats{
Host: host,
Success: true,
PacketsRecv: stats.PacketsRecv,
PacketsSent: stats.PacketsSent,
PacketLoss: stats.PacketLoss,
IPAddr: stats.IPAddr,
Addr: stats.Addr,
Rtts: stats.Rtts,
MinRtt: stats.MinRtt,
MaxRtt: stats.MaxRtt,
AvgRtt: stats.AvgRtt,
StdDevRtt: stats.StdDevRtt,
}
}
type allResults []*HostStats
func (r allResults) Len() int { return len(r) }
func (r allResults) Less(i, j int) bool { return r[i].AvgRtt < r[j].AvgRtt }
func (r allResults) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
// Select finds the faster hosts among the provided inputs, and sort the resulted host in ASC order
func (s *NetSelector) Select() ([]*HostStats, error) {
return s.performSelection()
}
func (s *NetSelector) performSelection() ([]*HostStats, error) {
hosts := s.Hosts
for _, host := range hosts {
err := sanitizeHost(host)
if err != nil {
return nil, err
}
}
mLen := len(hosts)
jobs := make(chan *Host, mLen)
results := make(chan *HostStats, mLen)
pingResults := []*HostStats{}
threads := s.Threads
if threads < 1 {
threads = 1
}
for t := 0; t < threads; t++ {
go func() {
for host := range jobs {
r := s.executePing(host)
results <- r
}
}()
}
for _, host := range hosts {
jobs <- host
}
close(jobs)
success := []*HostStats{}
failed := []*HostStats{}
for range hosts {
result := <-results
if result.Success {
success = append(success, result)
} else {
failed = append(failed, result)
}
pingResults = append(pingResults, result)
}
sort.Sort(allResults(success))
pingResults = append(success, failed...)
return pingResults, nil
}