-
Notifications
You must be signed in to change notification settings - Fork 71
/
ping_handler.go
70 lines (61 loc) · 1.5 KB
/
ping_handler.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package handlers
import (
"errors"
"fmt"
"net"
"net/http"
"os"
"os/exec"
"strings"
"time"
)
type PingHandler struct {
}
func ipv4Address(ips []net.IP) (net.Addr, error) {
for _, ip := range ips {
if ip.To4() != nil {
return &net.UDPAddr{IP: ip}, nil
}
}
return nil, errors.New("No IPv4 found")
}
func handleError(err error, destination string, resp http.ResponseWriter) {
msg := fmt.Sprintf("Ping failed to destination: %s: %s", destination, err)
fmt.Fprintf(os.Stderr, msg)
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(msg))
}
func (h *PingHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
destination := strings.TrimPrefix(req.URL.Path, "/ping/")
destination = strings.Split(destination, ":")[0]
pingPath := "/bin/ping"
_, err := os.Stat(pingPath)
if err != nil {
pingPath = "/sbin/ping"
}
cmd := exec.Command(pingPath, "-c", "1", destination)
err = cmd.Start()
if err != nil {
handleError(err, destination, resp)
return
}
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(10 * time.Second):
if err := cmd.Process.Kill(); err != nil {
handleError(fmt.Errorf("error killing hung ping: %s", err), destination, resp)
return
}
handleError(errors.New("killing ping after timed out"), destination, resp)
return
case err := <-done:
if err != nil {
handleError(err, destination, resp)
return
}
}
resp.Write([]byte(fmt.Sprintf("Ping succeeded to destination: %s", destination)))
}