Validator agent: retry outbound HTTPS up to 3 times, traceroute on failure
A failed HTTPS check is retried (3 attempts, 2 s apart). If all attempts fail, the agent runs traceroute -4 -n to the target's IPv4 address in a separate process, polls it every 5 s (90 s limit) and posts the full output as a traceroute_result event for the address. The agent waits for traces before reporting completion, while the floating IP is attached. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1536723196
commit
5c75ece8b1
15 files changed
+480
-25
No files matched your search
@@ -9,28 +9,66 @@ import (
|
||||
|
||||
// HTTPS performs a GET against target (expected to be a full URL, e.g.
|
||||
// https://github.com) and reports success for any response with status
|
||||
// < 400. It never follows the check to a different host on a check-type
|
||||
// boundary — redirects within the same request are followed by the
|
||||
// standard http.Client default policy, which is what we want for
|
||||
// reachability checks.
|
||||
// < 400. Redirects are followed by the default http.Client policy.
|
||||
// It makes a single attempt; use HTTPSWithRetry for retries.
|
||||
func HTTPS(target string, timeout time.Duration) func(ctx context.Context) Result {
|
||||
return run("https", target, func(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
client := &http.Client{Timeout: timeout}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("unexpected status %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
return httpsOnce(ctx, &http.Client{Timeout: timeout}, target, timeout)
|
||||
})
|
||||
}
|
||||
|
||||
func httpsOnce(ctx context.Context, client *http.Client, target string, timeout time.Duration) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("unexpected status %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// HTTPSWithRetry makes up to attempts tries, pausing delay between them, and
|
||||
// stops at the first success. The result is a single Result: Detail carries
|
||||
// the attempt number, LatencyMS is that of the last attempt.
|
||||
func HTTPSWithRetry(target string, timeout time.Duration, attempts int, delay time.Duration) func(ctx context.Context) Result {
|
||||
return httpsWithRetry(&http.Client{Timeout: timeout}, target, timeout, attempts, delay)
|
||||
}
|
||||
|
||||
func httpsWithRetry(client *http.Client, target string, timeout time.Duration, attempts int, delay time.Duration) func(ctx context.Context) Result {
|
||||
if attempts < 1 {
|
||||
attempts = 1
|
||||
}
|
||||
return func(ctx context.Context) Result {
|
||||
var res Result
|
||||
for n := 1; n <= attempts; n++ {
|
||||
res = run("https", target, func(ctx context.Context) error {
|
||||
return httpsOnce(ctx, client, target, timeout)
|
||||
})(ctx)
|
||||
if res.Success {
|
||||
res.Detail = fmt.Sprintf("ok (attempt %d/%d)", n, attempts)
|
||||
return res
|
||||
}
|
||||
if n == attempts || ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(delay):
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
res.Detail = fmt.Sprintf("%s (%d/%d attempts failed)", res.Detail, attempts, attempts)
|
||||
return res
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package checkrunner
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHTTPSRetrySucceedsOnSecondAttempt(t *testing.T) {
|
||||
var n atomic.Int32
|
||||
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if n.Add(1) == 1 {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
res := httpsWithRetry(srv.Client(), srv.URL, 2*time.Second, 3, 10*time.Millisecond)(context.Background())
|
||||
if !res.Success || res.Detail != "ok (attempt 2/3)" {
|
||||
t.Fatalf("got success=%v detail=%q", res.Success, res.Detail)
|
||||
}
|
||||
if n.Load() != 2 {
|
||||
t.Fatalf("expected 2 requests, got %d", n.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostFromTarget(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"https://github.com": "github.com",
|
||||
"https://github.com:8443/x": "github.com",
|
||||
"http://1.2.3.4/path?q=1": "1.2.3.4",
|
||||
"example.org": "example.org",
|
||||
"example.org:443": "example.org",
|
||||
}
|
||||
for in, want := range cases {
|
||||
if got := HostFromTarget(in); got != want {
|
||||
t.Errorf("HostFromTarget(%q)=%q want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
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()
|
||||
}
|
||||
Reference in new issue
Block a user