bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/cmd/bosun/ping/ping.go (about)

     1  package ping // import "bosun.org/cmd/bosun/ping"
     2  
     3  import (
     4  	"net"
     5  	"time"
     6  
     7  	fastping "github.com/tatsushid/go-fastping"
     8  
     9  	"bosun.org/cmd/bosun/search"
    10  	"bosun.org/collect"
    11  	"bosun.org/metadata"
    12  	"bosun.org/opentsdb"
    13  	"bosun.org/slog"
    14  )
    15  
    16  func init() {
    17  	metadata.AddMetricMeta("bosun.ping.resolved", metadata.Gauge, metadata.Bool,
    18  		"1=Ping resolved to an IP Address. 0=Ping failed to resolve to an IP Address.")
    19  	metadata.AddMetricMeta("bosun.ping.rtt", metadata.Gauge, metadata.MilliSecond,
    20  		"The number of milliseconds for the echo reply to be received. Also known as Round Trip Time.")
    21  	metadata.AddMetricMeta("bosun.ping.timeout", metadata.Gauge, metadata.Ok,
    22  		"0=Ping responded before timeout. 1=Ping did not respond before 5 second timeout.")
    23  }
    24  
    25  const pingFreq = time.Second * 15
    26  
    27  // PingHosts pings all hosts that bosun has indexed as recently as the PingDuration
    28  // provided via the systemConf
    29  func PingHosts(search *search.Search, duration time.Duration) {
    30  	for range time.Tick(pingFreq) {
    31  		hosts, err := search.TagValuesByTagKey("host", duration)
    32  		if err != nil {
    33  			slog.Error(err)
    34  			continue
    35  		}
    36  		for _, host := range hosts {
    37  			go pingHost(host)
    38  		}
    39  	}
    40  }
    41  
    42  func pingHost(host string) {
    43  	p := fastping.NewPinger()
    44  	tags := opentsdb.TagSet{"dst_host": host}
    45  	resolved := 0
    46  	defer func() {
    47  		collect.Put("ping.resolved", tags, resolved)
    48  	}()
    49  	ra, err := net.ResolveIPAddr("ip4:icmp", host)
    50  	if err != nil {
    51  		return
    52  	}
    53  	resolved = 1
    54  	p.AddIPAddr(ra)
    55  	p.MaxRTT = time.Second * 5
    56  	timeout := 1
    57  	p.OnRecv = func(addr *net.IPAddr, t time.Duration) {
    58  		collect.Put("ping.rtt", tags, float64(t)/float64(time.Millisecond))
    59  		timeout = 0
    60  	}
    61  	if err := p.Run(); err != nil {
    62  		slog.Errorln(err)
    63  	}
    64  	collect.Put("ping.timeout", tags, timeout)
    65  }