-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathpinger.go
233 lines (197 loc) · 4.8 KB
/
pinger.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
package main
import (
"flag"
"fmt"
"math"
"net"
"os"
"runtime"
"strings"
"time"
"github.com/hirose31/ringbuffer"
"github.com/mattn/go-isatty"
termbox "github.com/nsf/termbox-go"
"github.com/tatsushid/go-fastping"
)
const version = "1.3.2"
var (
writeFailedLog = !isatty.IsTerminal(os.Stderr.Fd())
revision = "HEAD"
)
type response struct {
addr *net.IPAddr
rtt time.Duration
}
func keyEventLoop(kch chan termbox.Key) {
for {
switch ev := termbox.PollEvent(); ev.Type {
case termbox.EventKey:
kch <- ev.Key
case termbox.EventResize:
layout.termW, layout.termH = termbox.Size()
drawHeader()
default:
}
}
}
func section(title string) string {
line := "-[ " + title + " ]-"
if w := layout.termW - len(line); w > 0 {
line += strings.Repeat("-", w)
}
return line
}
func drawStr(x, y int, str string) {
drawColorfulStr(x, y, str, termbox.ColorDefault, termbox.ColorDefault)
}
func drawColorfulStr(x, y int, str string, fg, bg termbox.Attribute) {
runes := []rune(str)
for i := 0; i < len(runes); i++ {
termbox.SetCell(x+i, y, runes[i], fg, bg)
}
}
var layout struct {
resultL int
resultH int
hostnameL int
termW int
termH int
failedHistoryY int
}
func drawHeader() {
header := fmt.Sprintf("pinger %s (rev: %s/%s)", version, revision, runtime.Version())
drawStr(0, 0, header)
header = "type ESC or C-c to exit"
drawStr(layout.termW-len(header), 0, header)
drawStr(0, 1, section("current rtt (avg) ms"))
drawStr(0, layout.failedHistoryY, section("failed history"))
}
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage:\n %s [options] hostname [hostname ...]\n\nOptions:\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
hostnames := flag.Args()
if len(hostnames) == 0 {
flag.Usage()
os.Exit(1)
}
p := fastping.NewPinger()
netProto := "ip4:icmp"
p.MaxRTT = time.Second
result := make(map[string]*response)
rtt := make(map[string]*ringbuffer.RingBuffer)
ipaddrOf := make(map[string]string)
for _, hostname := range hostnames {
ra, err := net.ResolveIPAddr(netProto, hostname)
if err != nil {
panic(err)
}
p.AddIPAddr(ra)
ipaddr := ra.String()
ipaddrOf[hostname] = ipaddr
result[ipaddr] = nil
rtt[ipaddr] = ringbuffer.NewRingBuffer(10)
if hl := len(hostname); hl > layout.hostnameL {
layout.hostnameL = hl
}
}
layout.resultL = 2 + layout.hostnameL + 1 + 5 + 2 + 5 + 1
layout.resultH = int(math.Ceil(float64(len(hostnames)) / 2.0))
onRecv := make(chan *response)
p.OnRecv = func(addr *net.IPAddr, t time.Duration) {
onRecv <- &response{addr: addr, rtt: t}
}
onIdle := make(chan bool)
p.OnIdle = func() {
onIdle <- true
}
err := termbox.Init()
if err != nil {
panic(err)
}
defer termbox.Close()
layout.termW, layout.termH = termbox.Size()
layout.failedHistoryY = 1 + layout.resultH + 1 + 1
histSize := layout.termH - layout.failedHistoryY - 2
if histSize <= 0 {
histSize = 10
}
failedHistory := ringbuffer.NewRingBuffer(histSize)
drawHeader()
_ = termbox.Flush()
keyCh := make(chan termbox.Key)
go keyEventLoop(keyCh)
p.RunLoop()
defer p.Stop()
loop:
for {
select {
case res := <-onRecv:
result[res.addr.String()] = res
case <-onIdle:
y := 2
for i, hostname := range hostnames {
ipaddr := ipaddrOf[hostname]
res := result[ipaddr]
var msg string
var fg termbox.Attribute
var st string
if res != nil {
st = "o"
fg = termbox.ColorGreen
_ = rtt[ipaddr].Push(res.rtt)
rttHist, _ := rtt[ipaddr].Fetch()
var rttSum float64
for _, t := range rttHist {
rttSum += t.(time.Duration).Seconds()
}
avg := rttSum / float64(len(rttHist))
msg = fmt.Sprintf("%-[1]*s %5.2f (%5.2f)", layout.hostnameL, hostname, res.rtt.Seconds()*1000, avg*1000)
} else {
st = "x"
fg = termbox.ColorYellow
msg = fmt.Sprintf("%-[1]*s", layout.resultL, hostname)
faillog := fmt.Sprintf("%s %-24s",
time.Now().Format("2006-01-02 15:04:05.000"),
hostname)
_ = failedHistory.Push(faillog)
if writeFailedLog {
fmt.Fprintln(os.Stderr, faillog)
}
}
if i%2 == 0 {
drawColorfulStr(0, y, st, fg, termbox.ColorDefault)
drawStr(2, y, msg)
} else {
drawStr(layout.resultL, y, " | ")
drawColorfulStr(layout.resultL+3, y, st, fg, termbox.ColorDefault)
drawStr(layout.resultL+5, y, msg)
y++
}
result[ipaddr] = nil
}
y = layout.failedHistoryY + 1
history, err := failedHistory.Fetch()
if err != nil {
panic(err)
}
for i := len(history) - 1; i >= 0; i-- {
drawStr(0, y, history[i].(string))
y++
}
_ = termbox.Flush()
case key := <-keyCh:
switch key {
case termbox.KeyEsc, termbox.KeyCtrlC:
break loop
}
case <-p.Done():
if err = p.Err(); err != nil {
panic(err)
}
break loop
}
}
}