165 lines
3.8 KiB
Go
165 lines
3.8 KiB
Go
package checkrunner
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"context"
|
||
|
|
"fmt"
|
||
|
|
"net"
|
||
|
|
neturl "net/url"
|
||
|
|
"os/exec"
|
||
|
|
"strconv"
|
||
|
|
"sync"
|
||
|
|
"time"
|
||
|
|
)
|
||
|
|
|
||
|
|
// Traceroute statuses.
|
||
|
|
const (
|
||
|
|
TraceCompleted = "completed"
|
||
|
|
TraceTimeout = "timeout"
|
||
|
|
TraceError = "error"
|
||
|
|
)
|
||
|
|
|
||
|
|
// TraceResult is the outcome of one traceroute run.
|
||
|
|
type TraceResult struct {
|
||
|
|
Target string
|
||
|
|
Host string
|
||
|
|
IP string
|
||
|
|
Status string
|
||
|
|
DurationMS int64
|
||
|
|
Output string
|
||
|
|
Error string
|
||
|
|
}
|
||
|
|
|
||
|
|
// TraceConfig holds traceroute run parameters.
|
||
|
|
type TraceConfig struct {
|
||
|
|
Timeout time.Duration
|
||
|
|
MaxHops int
|
||
|
|
PollInterval time.Duration
|
||
|
|
}
|
||
|
|
|
||
|
|
// HostFromTarget extracts the host from a URL; if the target has no scheme
|
||
|
|
// (or does not parse) the raw value is used with any port/path stripped.
|
||
|
|
func HostFromTarget(target string) string {
|
||
|
|
if u, err := neturl.Parse(target); err == nil && u.Hostname() != "" {
|
||
|
|
return u.Hostname()
|
||
|
|
}
|
||
|
|
if u, err := neturl.Parse("//" + target); err == nil && u.Hostname() != "" {
|
||
|
|
return u.Hostname()
|
||
|
|
}
|
||
|
|
return target
|
||
|
|
}
|
||
|
|
|
||
|
|
// StartTraceroute runs the trace in the background and returns a channel
|
||
|
|
// that yields exactly one result.
|
||
|
|
func StartTraceroute(ctx context.Context, target string, cfg TraceConfig) <-chan TraceResult {
|
||
|
|
ch := make(chan TraceResult, 1)
|
||
|
|
go func() { ch <- Traceroute(ctx, target, cfg) }()
|
||
|
|
return ch
|
||
|
|
}
|
||
|
|
|
||
|
|
// Traceroute resolves the host of target to IPv4 and runs the traceroute
|
||
|
|
// binary, polling its status every cfg.PollInterval until it exits or
|
||
|
|
// cfg.Timeout elapses (then the process is killed and partial output kept).
|
||
|
|
func Traceroute(ctx context.Context, target string, cfg TraceConfig) TraceResult {
|
||
|
|
start := time.Now()
|
||
|
|
res := TraceResult{Target: target, Host: HostFromTarget(target)}
|
||
|
|
finish := func() TraceResult {
|
||
|
|
res.DurationMS = time.Since(start).Milliseconds()
|
||
|
|
return res
|
||
|
|
}
|
||
|
|
|
||
|
|
if cfg.PollInterval <= 0 {
|
||
|
|
cfg.PollInterval = 5 * time.Second
|
||
|
|
}
|
||
|
|
if cfg.Timeout <= 0 {
|
||
|
|
cfg.Timeout = 90 * time.Second
|
||
|
|
}
|
||
|
|
if cfg.MaxHops <= 0 {
|
||
|
|
cfg.MaxHops = 30
|
||
|
|
}
|
||
|
|
|
||
|
|
if ip := net.ParseIP(res.Host); ip != nil && ip.To4() != nil {
|
||
|
|
res.IP = ip.To4().String()
|
||
|
|
} else {
|
||
|
|
rctx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||
|
|
ips, err := net.DefaultResolver.LookupIP(rctx, "ip4", res.Host)
|
||
|
|
cancel()
|
||
|
|
if err != nil || len(ips) == 0 {
|
||
|
|
res.Status = TraceError
|
||
|
|
if err == nil {
|
||
|
|
err = fmt.Errorf("no A records")
|
||
|
|
}
|
||
|
|
res.Error = "dns: " + err.Error()
|
||
|
|
return finish()
|
||
|
|
}
|
||
|
|
res.IP = ips[0].String()
|
||
|
|
}
|
||
|
|
|
||
|
|
var buf lockedBuffer
|
||
|
|
cmd := exec.Command("traceroute", "-4", "-n", "-q", "1", "-w", "2", "-m", strconv.Itoa(cfg.MaxHops), res.IP)
|
||
|
|
cmd.Stdout = &buf
|
||
|
|
cmd.Stderr = &buf
|
||
|
|
if err := cmd.Start(); err != nil {
|
||
|
|
res.Status = TraceError
|
||
|
|
res.Error = "start traceroute: " + err.Error()
|
||
|
|
return finish()
|
||
|
|
}
|
||
|
|
done := make(chan error, 1)
|
||
|
|
go func() { done <- cmd.Wait() }()
|
||
|
|
|
||
|
|
ticker := time.NewTicker(cfg.PollInterval)
|
||
|
|
defer ticker.Stop()
|
||
|
|
deadline := time.NewTimer(cfg.Timeout)
|
||
|
|
defer deadline.Stop()
|
||
|
|
|
||
|
|
kill := func(status, msg string) {
|
||
|
|
_ = cmd.Process.Kill()
|
||
|
|
<-done
|
||
|
|
res.Status = status
|
||
|
|
res.Error = msg
|
||
|
|
}
|
||
|
|
|
||
|
|
loop:
|
||
|
|
for {
|
||
|
|
select {
|
||
|
|
case <-ticker.C:
|
||
|
|
// Status poll: the process state is checked only on a tick.
|
||
|
|
select {
|
||
|
|
case err := <-done:
|
||
|
|
if err != nil {
|
||
|
|
res.Status = TraceError
|
||
|
|
res.Error = err.Error()
|
||
|
|
} else {
|
||
|
|
res.Status = TraceCompleted
|
||
|
|
}
|
||
|
|
break loop
|
||
|
|
default:
|
||
|
|
}
|
||
|
|
case <-deadline.C:
|
||
|
|
kill(TraceTimeout, fmt.Sprintf("traceroute exceeded %s", cfg.Timeout))
|
||
|
|
break loop
|
||
|
|
case <-ctx.Done():
|
||
|
|
kill(TraceError, "cancelled: "+ctx.Err().Error())
|
||
|
|
break loop
|
||
|
|
}
|
||
|
|
}
|
||
|
|
res.Output = buf.String()
|
||
|
|
return finish()
|
||
|
|
}
|
||
|
|
|
||
|
|
type lockedBuffer struct {
|
||
|
|
mu sync.Mutex
|
||
|
|
b bytes.Buffer
|
||
|
|
}
|
||
|
|
|
||
|
|
func (l *lockedBuffer) Write(p []byte) (int, error) {
|
||
|
|
l.mu.Lock()
|
||
|
|
defer l.mu.Unlock()
|
||
|
|
return l.b.Write(p)
|
||
|
|
}
|
||
|
|
|
||
|
|
func (l *lockedBuffer) String() string {
|
||
|
|
l.mu.Lock()
|
||
|
|
defer l.mu.Unlock()
|
||
|
|
return l.b.String()
|
||
|
|
}
|