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:
ayurishchevandClaude Opus 5.5 committed 2026-11-02 22:45:21 +03:00
1 parent 1536723196
commit 5c75ece8b1
15 files changed
+480 -25

No files matched your search

+46 -1
View File
@@ -19,6 +19,7 @@ import (
neturl "net/url"
"os"
"strings"
"sync"
"sync/atomic"
"time"
@@ -402,12 +403,16 @@ func fetchIPEcho(ctx context.Context, url string) (string, error) {
func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
var results []checkResultDTO
var traces sync.WaitGroup
for _, ct := range assignment.CheckConfig {
for _, target := range ct.Targets {
var fn func(context.Context) checkrunner.Result
switch ct.Type {
case "https":
fn = checkrunner.HTTPS(target, time.Duration(a.cfg.Checks.HTTPSTimeoutSeconds)*time.Second)
fn = checkrunner.HTTPSWithRetry(target,
time.Duration(a.cfg.Checks.HTTPSTimeoutSeconds)*time.Second,
a.cfg.Checks.HTTPSAttempts,
time.Duration(a.cfg.Checks.HTTPSRetryDelaySeconds)*time.Second)
case "icmp":
fn = checkrunner.ICMPEcho(hostOnly(target), a.cfg.Checks.ICMPCount, time.Duration(a.cfg.Checks.ICMPTimeoutSeconds)*time.Second)
case "ssh":
@@ -435,13 +440,53 @@ func (a *Agent) runChecks(ctx context.Context, assignment assignmentResp) {
// Report progressively rather than batching until the end, so
// a crash mid-run doesn't lose already-completed check results.
a.postResults(ctx, []checkResultDTO{results[len(results)-1]})
if ct.Type == "https" && !res.Success && a.cfg.Checks.Traceroute.IsEnabled() {
traces.Add(1)
go func(target string) {
defer traces.Done()
a.runTraceroute(ctx, assignment.IPID, target)
}(target)
}
}
}
// Wait for traces before complete: after complete the control-api
// detaches the floating IP and the trace would leave from another address.
traces.Wait()
a.postComplete(ctx, assignment.IPID)
a.lastHandledIPID = assignment.IPID
}
// runTraceroute traces the route to target's host and posts the outcome as a
// traceroute_result event. It never affects the verdict.
func (a *Agent) runTraceroute(ctx context.Context, ipID int64, target string) {
tc := a.cfg.Checks.Traceroute
a.log.Info("traceroute start", "target", target)
r := <-checkrunner.StartTraceroute(ctx, target, checkrunner.TraceConfig{
Timeout: time.Duration(tc.TimeoutSeconds) * time.Second,
MaxHops: tc.MaxHops,
PollInterval: time.Duration(tc.PollIntervalSeconds) * time.Second,
})
a.log.Info("traceroute finish", "target", target, "ip", r.IP, "status", r.Status, "duration_ms", r.DurationMS)
payload, err := json.Marshal(struct {
Target string `json:"target"`
Host string `json:"host"`
IP string `json:"ip"`
Status string `json:"status"`
DurationMS int64 `json:"duration_ms"`
Output string `json:"output"`
Error string `json:"error,omitempty"`
}{r.Target, r.Host, r.IP, r.Status, r.DurationMS, r.Output, r.Error})
if err != nil {
a.log.Error("marshal traceroute event", "err", err)
return
}
a.postEvent(ctx, ipID, "traceroute_result", string(payload))
}
type checkResultDTO struct {
IPID int64 `json:"ip_id"`
CheckType string `json:"check_type"`
+59 -21
View File
@@ -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
}
}
+45
View File
@@ -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)
}
}
}
+165
View File
@@ -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()
}
+33
View File
@@ -265,8 +265,26 @@ type AgentChecks struct {
ICMPTimeoutSeconds int `yaml:"icmp_timeout_seconds"`
ICMPCount int `yaml:"icmp_count"`
SSH SSHCfg `yaml:"ssh"`
// HTTPSAttempts is the number of tries per HTTPS URL (first + retries).
HTTPSAttempts int `yaml:"https_attempts"`
HTTPSRetryDelaySeconds int `yaml:"https_retry_delay_seconds"`
Traceroute TracerouteCfg `yaml:"traceroute"`
}
// TracerouteCfg controls the background traceroute run after a failed HTTPS
// check. Enabled is a pointer so that an absent key means "enabled".
type TracerouteCfg struct {
Enabled *bool `yaml:"enabled"`
TimeoutSeconds int `yaml:"timeout_seconds"`
MaxHops int `yaml:"max_hops"`
PollIntervalSeconds int `yaml:"poll_interval_seconds"`
}
// IsEnabled reports whether traceroute is on (default true).
func (t TracerouteCfg) IsEnabled() bool { return t.Enabled == nil || *t.Enabled }
type SSHCfg struct {
Enabled bool `yaml:"enabled"`
TimeoutSeconds int `yaml:"timeout_seconds"`
@@ -306,6 +324,21 @@ func LoadValidatorAgent(path string) (*ValidatorAgent, error) {
if c.Checks.ICMPCount == 0 {
c.Checks.ICMPCount = 3
}
if c.Checks.HTTPSAttempts <= 0 {
c.Checks.HTTPSAttempts = 3
}
if c.Checks.HTTPSRetryDelaySeconds <= 0 {
c.Checks.HTTPSRetryDelaySeconds = 2
}
if c.Checks.Traceroute.TimeoutSeconds <= 0 {
c.Checks.Traceroute.TimeoutSeconds = 90
}
if c.Checks.Traceroute.MaxHops <= 0 {
c.Checks.Traceroute.MaxHops = 30
}
if c.Checks.Traceroute.PollIntervalSeconds <= 0 {
c.Checks.Traceroute.PollIntervalSeconds = 5
}
if c.Checks.SSH.TimeoutSeconds == 0 {
c.Checks.SSH.TimeoutSeconds = 5
}