-
Notifications
You must be signed in to change notification settings - Fork 3
/
probe_udp.go
78 lines (68 loc) · 1.41 KB
/
probe_udp.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
package poller
import (
"net"
"strconv"
"time"
)
type udpProbe struct {
Timeout time.Duration
}
func NewUdpProbe(timeout time.Duration) Probe {
return &udpProbe{timeout}
}
func (p *udpProbe) Test(c *Check) *Event {
event := NewEvent(c)
timer := time.NewTimer(p.Timeout)
ch := make(chan *Event, 1)
start := time.Now().UnixNano()
go func(e *Event, eventCh chan<- *Event) {
hp := net.JoinHostPort(c.Config.GetString("host"), strconv.Itoa(c.Config.GetInt("port")))
raddr, err := net.ResolveUDPAddr("udp", hp)
if err != nil {
eventCh <- e
return
}
conn, err := net.DialUDP("udp", nil, raddr)
if err != nil {
eventCh <- e
return
}
conn.SetDeadline(time.Now().Add(p.Timeout))
defer conn.Close()
if _, err := conn.Write([]byte(c.Config.GetString("send"))); err != nil {
eventCh <- e
return
}
buf := make([]byte, len([]byte(c.Config.GetString("receive"))))
for {
count, err := conn.Read(buf)
if err != nil {
eventCh <- e
return
}
if count != 0 {
break
}
}
if string(buf) == c.Config.GetString("receive") {
e.Up()
eventCh <- e
return
} else {
e.Down()
eventCh <- e
return
}
}(event, ch)
select {
case <-timer.C:
end := time.Now().UnixNano()
event.Duration = time.Duration(end - start)
event.Down()
return event
case e := <-ch:
end := time.Now().UnixNano()
event.Duration = time.Duration(end - start)
return e
}
}