bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/cmd/scollector/collectors/icmp.go (about) 1 package collectors 2 3 import ( 4 "fmt" 5 "net" 6 "time" 7 8 "bosun.org/metadata" 9 "bosun.org/opentsdb" 10 "github.com/tatsushid/go-fastping" 11 ) 12 13 type response struct { 14 addr *net.IPAddr 15 rtt time.Duration 16 } 17 18 // ICMP registers an ICMP collector a given host. 19 func ICMP(host string) error { 20 if host == "" { 21 return fmt.Errorf("empty ICMP hostname") 22 } 23 collectors = append(collectors, &IntervalCollector{ 24 F: func() (opentsdb.MultiDataPoint, error) { 25 return c_icmp(host) 26 }, 27 name: fmt.Sprintf("icmp-%s", host), 28 }) 29 return nil 30 } 31 32 func c_icmp(host string) (opentsdb.MultiDataPoint, error) { 33 var md opentsdb.MultiDataPoint 34 p := fastping.NewPinger() 35 ra, err := net.ResolveIPAddr("ip4:icmp", host) 36 if err != nil { 37 return nil, err 38 } 39 p.AddIPAddr(ra) 40 p.MaxRTT = time.Second * 5 41 timeout := 1 42 p.OnRecv = func(addr *net.IPAddr, t time.Duration) { 43 Add(&md, "ping.rtt", float64(t)/float64(time.Millisecond), opentsdb.TagSet{"dst_host": host}, metadata.Unknown, metadata.None, "") 44 timeout = 0 45 } 46 if err := p.Run(); err != nil { 47 return nil, err 48 } 49 Add(&md, "ping.timeout", timeout, opentsdb.TagSet{"dst_host": host}, metadata.Unknown, metadata.None, "") 50 return md, nil 51 }