forked from bosun-monitor/bosun
/
icmp.go
51 lines (46 loc) · 1.15 KB
/
icmp.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
package collectors
import (
"fmt"
"net"
"time"
"bosun.org/metadata"
"bosun.org/opentsdb"
"github.com/tatsushid/go-fastping"
)
type response struct {
addr *net.IPAddr
rtt time.Duration
}
// ICMP registers an ICMP collector a given host.
func ICMP(host string) error {
if host == "" {
return fmt.Errorf("empty ICMP hostname")
}
collectors = append(collectors, &IntervalCollector{
F: func() (opentsdb.MultiDataPoint, error) {
return c_icmp(host)
},
name: fmt.Sprintf("icmp-%s", host),
})
return nil
}
func c_icmp(host string) (opentsdb.MultiDataPoint, error) {
var md opentsdb.MultiDataPoint
p := fastping.NewPinger()
ra, err := net.ResolveIPAddr("ip4:icmp", host)
if err != nil {
return nil, err
}
p.AddIPAddr(ra)
p.MaxRTT = time.Second * 5
timeout := 1
p.OnRecv = func(addr *net.IPAddr, t time.Duration) {
Add(&md, "ping.rtt", float64(t)/float64(time.Millisecond), opentsdb.TagSet{"dst_host": host}, metadata.Unknown, metadata.None, "")
timeout = 0
}
if err := p.Run(); err != nil {
return nil, err
}
Add(&md, "ping.timeout", timeout, opentsdb.TagSet{"dst_host": host}, metadata.Unknown, metadata.None, "")
return md, nil
}