From 2db94d3d291a2e8800cdf803e47277e4437c8edb Mon Sep 17 00:00:00 2001 From: halfa Date: Mon, 31 Oct 2016 20:20:03 +0900 Subject: [PATCH] Add ping probe Support packet loss and RTT warning --- probe/ping.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 probe/ping.go diff --git a/probe/ping.go b/probe/ping.go new file mode 100644 index 0000000..d44fd01 --- /dev/null +++ b/probe/ping.go @@ -0,0 +1,48 @@ +package probe + +import ( + "time" + + ping "github.com/sparrc/go-ping" +) + +const packetCount = 3 + +// Ping probe, check network avaibility +type Ping struct { + addr string + warning time.Duration + fail time.Duration +} + +// NewPing returns a ping probe +func NewPing(addr string, warning, fail time.Duration) *Ping { + return &Ping{ + addr: addr, + warning: warning, + fail: fail, + } +} + +// Probe send 3 ICMP packets and wait for replies +// Warning is issued when a reply is missing or if rtt exeed `warning` +// Failure occure when target is unreachable +func (p *Ping) Probe() (status Status, message string) { + pinger := &ping.Pinger{ + Timeout: p.fail, + Count: packetCount, + } + pinger.SetAddr(p.addr) + + pinger.Run() + stats := pinger.Statistics() + + if stats.PacketsRecv == 0 { + return StatusError, "Unreacheable" + } + + if stats.PacketsRecv < packetCount { + return StatusWarning, "Packet loss" + } + return EvaluateDuration(stats.AvgRtt, p.warning) +}