diff --git a/network/transports.go b/network/transports.go index d147d8b7dd..183f9f3a8f 100644 --- a/network/transports.go +++ b/network/transports.go @@ -46,6 +46,20 @@ func newAutoTransport(v1, v2 http.RoundTripper) http.RoundTripper { }) } +type singleAttemptKey struct{} + +// WithSingleAttemptDial makes a request using ctx dial at most once, bounded by +// ctx's deadline. net/http detaches dials from request cancellation, so a +// timed-out request otherwise leaves dialBackOffHelper retrying. Without a +// deadline ctx is returned unchanged. +func WithSingleAttemptDial(ctx context.Context) context.Context { + deadline, ok := ctx.Deadline() + if !ok { + return ctx + } + return context.WithValue(ctx, singleAttemptKey{}, deadline) +} + const sleep = 30 * time.Millisecond var backOffTemplate = wait.Backoff{ @@ -111,18 +125,22 @@ func dialBackOffHelper(ctx context.Context, network, address string, bo wait.Bac Timeout: bo.Duration, // Initial duration. KeepAlive: 5 * time.Second, } - start := time.Now() - for { - var ( - c net.Conn - err error - ) + dial := func(ctx context.Context) (net.Conn, error) { if tlsConf == nil { - c, err = dialer.DialContext(ctx, network, address) - } else { - d := tls.Dialer{NetDialer: dialer, Config: tlsConf} - c, err = d.DialContext(ctx, network, address) + return dialer.DialContext(ctx, network, address) } + d := tls.Dialer{NetDialer: dialer, Config: tlsConf} + return d.DialContext(ctx, network, address) + } + if deadline, ok := ctx.Value(singleAttemptKey{}).(time.Time); ok { + ctx, cancel := context.WithDeadline(ctx, deadline) + defer cancel() + dialer.Timeout = 0 + return dial(ctx) + } + start := time.Now() + for { + c, err := dial(ctx) if err != nil { var errNet net.Error if errors.As(err, &errNet) && errNet.Timeout() { diff --git a/network/transports_test.go b/network/transports_test.go index d0b4e9b51f..32eff5357f 100644 --- a/network/transports_test.go +++ b/network/transports_test.go @@ -26,7 +26,9 @@ import ( "net" "net/http" "net/http/httptest" + "net/http/httptrace" "strings" + "sync/atomic" "syscall" "testing" "time" @@ -280,3 +282,120 @@ type testingT interface { Fatal(args ...interface{}) Fatalf(format string, args ...interface{}) } + +// A request marked WithSingleAttemptDial dials once and stops at its deadline, +// although net/http detaches the dial from the request (#3449). +func TestSingleAttemptDialStopsAtDeadline(t *testing.T) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal("Unable to create listener:", err) + } + defer l.Close() + var attempts atomic.Int32 + closed := make(chan struct{}, 10) + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + attempts.Add(1) + go func() { + io.Copy(io.Discard, c) // Never answers the TLS handshake; returns when the client hangs up. + c.Close() + closed <- struct{}{} + }() + } + }() + + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + rt := NewProxyAutoTLSTransport(10, 10, backoffTLSContext(nil)) + if err := roundTrip(WithSingleAttemptDial(ctx), rt, "https://"+l.Addr().String(), 1); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("RoundTrip() = %v, want %v", err, context.DeadlineExceeded) + } + select { + case <-closed: + case <-time.After(time.Second): + t.Fatal("dial still open after the deadline") + } + time.Sleep(500 * time.Millisecond) // An unmarked dial keeps retrying here. + if got := attempts.Load(); got != 1 { + t.Errorf("dial attempts = %d, want 1", got) + } +} + +// A probe failing while its single-attempt dial hangs must not fail a request +// that wants a connection to the same address, over HTTP/1.1 or h2. +func TestSingleAttemptDialSparesConcurrentRequest(t *testing.T) { + for _, proto := range []int{1, 2} { + t.Run(map[int]string{1: "http1", 2: "h2"}[proto], func(t *testing.T) { + stalled, release, probeDone := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var handshakes atomic.Int32 + s := httptest.NewUnstartedServer(okHandler(t, proto)) + s.EnableHTTP2 = proto == 2 + s.TLS = &tls.Config{MinVersion: tls.VersionTLS12, GetConfigForClient: func(*tls.ClientHelloInfo) (*tls.Config, error) { + if handshakes.Add(1) == 1 { + close(stalled) + <-release // The probe's dial hangs. + } else { + <-probeDone // The request connects only after the probe failed. + } + return nil, nil + }} + s.StartTLS() + defer s.Close() + defer close(release) + pool := x509.NewCertPool() + pool.AddCert(s.Certificate()) + rt := NewProxyAutoTLSTransport(10, 10, backoffTLSContext(pool)) + + probeCtx, cancelProbe := context.WithTimeout(context.Background(), 5*time.Second) + defer cancelProbe() + probeErr := make(chan error, 1) + go func() { probeErr <- roundTrip(WithSingleAttemptDial(probeCtx), rt, s.URL, proto) }() + select { + case <-stalled: + case err := <-probeErr: + t.Fatal("probe finished before dialing:", err) + case <-time.After(5 * time.Second): + t.Fatal("probe never dialed") + } + + wantConn := make(chan struct{}) + reqCtx, cancelReq := context.WithTimeout(context.Background(), 5*time.Second) + defer cancelReq() + reqCtx = httptrace.WithClientTrace(reqCtx, &httptrace.ClientTrace{GetConn: func(string) { close(wantConn) }}) + reqErr := make(chan error, 1) + go func() { reqErr <- roundTrip(reqCtx, rt, s.URL, proto) }() + <-wantConn + cancelProbe() + err := <-probeErr + close(probeDone) + if !errors.Is(err, context.Canceled) { + t.Fatalf("probe RoundTrip() = %v, want %v", err, context.Canceled) + } + if err := <-reqErr; err != nil { + t.Fatal("RoundTrip() =", err) + } + }) + } +} + +// roundTrip sends a GET over rt and checks the response used HTTP/proto. +func roundTrip(ctx context.Context, rt http.RoundTripper, url string, proto int) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return err + } + req.ProtoMajor = proto + resp, err := rt.RoundTrip(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.ProtoMajor != proto { + return fmt.Errorf("resp.ProtoMajor = %d, want %d", resp.ProtoMajor, proto) + } + return nil +}