Created
May 24, 2019 18:10
-
-
Save mathyourlife/aed81c08ba5603d893b3fbe77fac9f87 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"log" | |
"net" | |
"net/http" | |
"strings" | |
"time" | |
"github.com/prometheus/client_golang/prometheus" | |
"github.com/prometheus/client_golang/prometheus/promhttp" | |
"github.com/tatsushid/go-fastping" | |
) | |
var pings *prometheus.HistogramVec | |
func init() { | |
pings = prometheus.NewHistogramVec(prometheus.HistogramOpts{ | |
Name: "ping_seconds", | |
Help: "Ping RTT in seconds", | |
// Buckets: prometheus.LinearBuckets(*normMean-5**normDomain, .5**normDomain, 20), | |
}, []string{"hostname"}) | |
prometheus.MustRegister(pings) | |
} | |
func ping(hostname string) error { | |
p := fastping.NewPinger() | |
defer p.Stop() | |
netProto := "ip4:icmp" | |
if strings.Index(hostname, ":") != -1 { | |
netProto = "ip6:ipv6-icmp" | |
} | |
ra, err := net.ResolveIPAddr(netProto, hostname) | |
if err != nil { | |
return err | |
} | |
p.AddIPAddr(ra) | |
p.OnRecv = func(addr *net.IPAddr, t time.Duration) { | |
pings.With(prometheus.Labels{"hostname": hostname}).Observe(t.Seconds()) | |
} | |
p.MaxRTT = 10 * time.Second | |
t := time.NewTicker(10 * time.Second) | |
for _ = range t.C { | |
err := p.Run() | |
if err != nil { | |
return err | |
} | |
} | |
return nil | |
} | |
func main() { | |
var hosts, addr string | |
flag.StringVar(&addr, "http.addr", ":6060", "http address") | |
flag.StringVar(&hosts, "hosts", "1.1.1.1", "host to ping") | |
flag.Parse() | |
for _, hostname := range strings.Split(hosts, ",") { | |
hostname := hostname | |
go func() { | |
err := ping(hostname) | |
if err != nil { | |
log.Fatal(err) | |
} | |
}() | |
} | |
// Expose the registered metrics via HTTP. | |
http.Handle("/metrics", promhttp.Handler()) | |
log.Fatal(http.ListenAndServe(addr, nil)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment