runtime icon indicating copy to clipboard operation
runtime copied to clipboard

HTTP2 connection hangs and causes TaskCanceledException in System.Net.Http.HttpConnectionPool

Open baal2000 opened this issue 2 years ago • 29 comments

Description

In our forked version of YARP we are encountering an issue where an HTTP/2 connection request to just one of many destination endpoints fails consistently, resulting in a TaskCanceledException after just under 1 second into attempting to send a request to a remote end point. The connection seems to be stuck waiting for a settings frame that is never received, which is similar to the situation discussed in this issue. Once the process enters this state, the only solution to the issue is to restart it. We are contemplating recycling of the SocketsHttpHandler instance as an alternative, but until the issue is not understood that would be a premature thing to do.

This issue typically arises after the process that owns the proxy destination endpoint restarts while the proxy itself remains running.

The HttpClient instance in our proxy server uses a static SocketsHttpHandler instance with a 4-minute timeout for the pooled HTTP connections inside the SocketsHttpHandler. However, the timeout does not seem to matter because we are unable to establish an HTTP/2 connection in the first place.

We are currently running the latest release of .NET 8.

We’re unsure if this issue is a bug in the framework or something in our code.

Could you help us identify where we should begin investigating to understand the root cause of this error? For example, could it be related to the inability to resolve DNS on the first connection attempt due to DNS caching?

Thank you!

Reproduction Steps

None

Expected behavior

A clear error that unambiguously describes why a request can not be sent or the connection can not be established.

Actual behavior

The following exception:

System.Threading.Tasks.TaskCanceledException: A task was canceled.
 ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
   at System.Threading.Tasks.TaskCompletionSourceWithCancellation`1.WaitWithCancellationAsync(CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.HttpClient.HandleFailure(Exception e, Boolean telemetryStarted, HttpResponseMessage response, CancellationTokenSource cts, CancellationToken cancellationToken, CancellationTokenSource pendingRequestsCts)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at ... some method of ours ....

Regression?

Potentially: this started with .NET 8 upgrade (from .NET 7)

Known Workarounds

None

Configuration

  • Ubuntu 20.04
  • .NET 8
  • A docker container running in a load balancer VM instance.

Other information

No response

baal2000 avatar Aug 15 '24 21:08 baal2000

@Tratcher

baal2000 avatar Aug 15 '24 21:08 baal2000

So we have managed to get a dump from one of the proxies that had this issue. What we found was that for a specific endpoint (the at the proxy could connect to before the issue) the HttpConnectionPool was unable to make a Http2Connection to service requests.

The pool had _pendingHttp2Connection set to true and _associatedHttp2ConnectionCount set to 1 but _availableHttp2Connections was still null. This means that the pool had started the fire and forget task to create a connection but the connection had not been created yet.

Eventually I found the tasks for the connection creation:

Awaiting: System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable<System.Int32>+ConfiguredValueTaskAwaiter >>
System.Net.Security.SslStream+<ReceiveHandshakeFrameAsync>d__151<System.Net.Security.AsyncReadWriteAdapter>
System.Net.Security.SslStream+<ForceAuthenticationAsync>d__150<System.Net.Security.AsyncReadWriteAdapter>
System.Net.Security.SslStream+<ProcessAuthenticationWithTelemetryAsync>d__147
System.Net.Http.ConnectHelper+<EstablishSslConnectionAsync>d__2
System.Net.Http.HttpConnectionPool+<ConnectAsync>d__103
System.Net.Http.HttpConnectionPool+<AddHttp2ConnectionAsync>d__83

Inspecting the state as best I can I have a theory that we are somehow stuck in the while loop inside ForceAuthenticationAsync:

while (!handshakeCompleted)
{
    int frameSize = await ReceiveHandshakeFrameAsync<TIOAdapter>(cancellationToken).ConfigureAwait(false);
    ProcessTlsFrame(frameSize, out message);

    ReadOnlyMemory<byte> payload = default;
    if (message.Size > 0)
    {
        payload = new ReadOnlyMemory<byte>(message.Payload, 0, message.Size);
    }
    else if (message.Failed && (_lastFrame.Header.Type == TlsContentType.Handshake || _lastFrame.Header.Type == TlsContentType.ChangeCipherSpec))
    {
        // If we failed without OS sending out alert, inject one here to be consistent across platforms.
        payload = TlsFrameHelper.CreateAlertFrame(_lastFrame.Header.Version, TlsAlertDescription.ProtocolVersion);
    }

    if (!payload.IsEmpty)
    {
        // If there is message send it out even if call failed. It may contain TLS Alert.
        await TIOAdapter.WriteAsync(InnerStream, payload, cancellationToken).ConfigureAwait(false);
        await TIOAdapter.FlushAsync(InnerStream, cancellationToken).ConfigureAwait(false);

        if (NetEventSource.Log.IsEnabled())
            NetEventSource.Log.SentFrame(this, payload.Span);
    }

    if (message.Failed)
    {
        if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, message.Status);

        if (_lastFrame.Header.Type == TlsContentType.Alert && _lastFrame.AlertDescription != TlsAlertDescription.CloseNotify &&
                    message.Status.ErrorCode == SecurityStatusPalErrorCode.IllegalMessage)
        {
            // Improve generic message and show details if we failed because of TLS Alert.
            throw new AuthenticationException(SR.Format(SR.net_auth_tls_alert, _lastFrame.AlertDescription.ToString()), message.GetException());
        }

        throw new AuthenticationException(SR.net_auth_SSPI, message.GetException());
    }
    else if (message.Status.ErrorCode == SecurityStatusPalErrorCode.OK)
    {
        // We can finish renegotiation without doing any read.
        handshakeCompleted = true;
    }
}

handshakeCompleted is still set to false, the buffer size of the stream is twice the size of InitialHandshakeBufferSize, payload is not the default, and message is not the default. The above make me think we have already gone around this loop once and since the proxy was unable to connect to the endpoint for over 30 min I think we are just stuck in this loop.

The proxy only gets into this state when the endpoint that it had previously been connected to is restarted.

We have confirmed that we have only seen this issue on dotnet 8. On both dotnet 7 and 6 we do not have this issue.

Looking at the changes to SslStream the following issues look like they could have potentially contributed to this (at least to me):

  • #86163
  • #87563
  • #88511

Any advice on how to proceed would be great. We are still working on a local reproduction.

nathanmascitelli avatar Aug 16 '24 20:08 nathanmascitelli

cc @wfurt

ManickaP avatar Aug 19 '24 07:08 ManickaP

You can try to get packet captures @nathanmascitelli. The core loop really did not changed that much. It reads TLS frames and feeds to hem to OpenSSL. And it waits for OpenSSL to tell us the handshake completed. Since you mentioned restart, you can try to set DOTNET_SYSTEM_NET_SECURITY_DISABLETLSRESUME environment or System.Net.Security.DisableTlsResume AppContext.

wfurt avatar Aug 19 '24 17:08 wfurt

@wfurt thanks for getting back to me. I'll look into DOTNET_SYSTEM_NET_SECURITY_DISABLETLSRESUME as I'm not familiar with it. One other thing to mention, we are deploying a build this week that will create a new HttpClientHandler on a timer (using the HttpClientFactory). The assumption is that this would create a whole new SslStream and connection but from quickly searching the environment varialbe is this not the case?

Regarding packet captures, we have not has success duplicating this yet so if we have to capture it has to be done in production which means that a high volume of data will be captured. I'm not sure if this is generally lightweight like the dotnet tracing or is it more resource intensive?

nathanmascitelli avatar Aug 19 '24 18:08 nathanmascitelli

yes, creating new handler will force new connection. However, you can also achieve this by setting SocketsHttpHandler.PooledConnectionLifetime

You mentioned that you see that after peer is restarted and that made me wonder about TLS resume. If the problem is with TLS handshake new handler will probably not fix it. Bit it seems like this is also good experiment to run.

BTW if you can, another experiment you can try is to disable Tls 1.3 (by forcing 1.2 (or lower)). And 9.0 RC1 is need by and it will be already supported. Both options require some level of reproducibility.

wfurt avatar Aug 19 '24 18:08 wfurt

@wfurt so we are already setting PooledConnectionLifetime, doesn't seem to help since the pool thinks its already creating a connection (_pendingHttp2Connection set to true and _associatedHttp2ConnectionCount set to 1 but _availableHttp2Connections was still null). So it looks like that might not help us based on what you've said.

The SSL session caching was introduced in dotnet 7, is that correct? Is it just a performance boost or does it have security implications.

For TLS 1.2, I'm not sure if we will be allowed to run that in prod but I'll look into it. I'm sorry but I didn't follow this line: "And 9.0 RC1 is need by and it will be already supported"

We can reproduce in prod, we have at least one instance a day, we just havn't been able to reproduce in a support environment yet.

nathanmascitelli avatar Aug 19 '24 18:08 nathanmascitelli

While understanding that TlsResume may cause an application into a corrupt state is important and may (or may not) be confirmed through DOTNET_SYSTEM_NET_SECURITY_DISABLETLSRESUME as a workaround, we should not loose our focus on 2 things:

  • if it is TlsResume then what would make the framework to stop infinite session resume attempts and clear the state?
  • could the sequence of events that leads to an obscure TaskCanceledException with no underlying cause be handled differently to provide a clear cause for the failure? This is what the team had done for another underlying issue in https://github.com/dotnet/runtime/issues/80056 and there is no reason to expect less here.

baal2000 avatar Aug 19 '24 20:08 baal2000

everything is speculation at this point @baal2000 and we need more evidence. I see no evidence there is infinite loop. The handshake will either succeed or fail. The failure can be cryptographic, cancellation or IO problem. And if it is not completing, is it because it waits for more data? @nathanmascitelli mentioned entering twice: that is certainly possible if server asks for renegotiation .... like client certificate after the handshake. And the handshake game somewhat changes with TLS 1.3. So it may be good to dig deeper and figure out what is happening in normal case, even if that does not reproduce the observed behavior.

wfurt avatar Aug 19 '24 21:08 wfurt

@wfurt, sorry for the delayed response we were just working to get some of your suggestions into place. We have applied DOTNET_SYSTEM_NET_SECURITY_DISABLETLSRESUME and are still seeing the exact same error with the same async stack that I posted above.

We have also managed to reproduce on test infrastrcuture, however it can take a very long time (16 hours) to hit the issue. We are working on getting the time to reproduce down so we can get results faster but in the meantime you had asked for packet captures, do you have a prefered method to do this?

One other thing I have found out and wanted to mention is that the cancellation token that is passed through this callstack is one thats created in AddHttp2ConnectionAsync.GetConnectTimeoutCancellationTokenSource and can only be triggerd by taking logner then the ConnectTimeout. However our application has this timeout set to infinate, which I guess in theory means that if the client got into a state where it was waiting on the server it may potentially wait forever. Does that make sense? Is having ConnectTimeout set to infinate bad practice?

nathanmascitelli avatar Aug 21 '24 15:08 nathanmascitelli

I think the infinite timeout does not matter for plain HTTP - the OS would have some timeout for TCP connect anyway. It is more complicated IMHO for HTTPS. The TCP is established and SslStream does not have any timeouts on it's own. In general case when connection is idle for long time the server would close it and that would trigger cleanup and abort. However, we have seen cases when some infrastructiure in the middle (like firewall or load balancer) decides to cut the connection and simply blocks the communincation without notifying peers. In such case the client can wait VERY long time. I see no reason to have the timeout more than 10-20s.

It is good to know that the simplifid handshake with resume is not the culprit. That really suggest that the client is not getting the expected TLS frames to complete the handshake. But I don't know why that would be different than 7.0.

wfurt avatar Aug 21 '24 17:08 wfurt

Thanks @wfurt, we are deploying a build that uses HttpClientFactory which will create a new handler every 2 min. This will effectily act as a 2 min connection timout so we are hopefull it will mitigate the issue. That said we will look at getting the connection time set (looks like YARP set's it to 15s) as that would lead to a faster recovery.

With regards to getting to root cause, like I said we can duplicate the issue though it is slow. We are working to try and simplify and speed up the reproduction but if it is something related to our infrastructure there might be a limit on how simple we can make it.

For packet capture do you just want like wireshark logs?

nathanmascitelli avatar Aug 21 '24 20:08 nathanmascitelli

yes, Wireshark would be good start. However with the long time it will be LOT of data. So it would be be great to combine it with some logging Perhaps use SocketsHttpHandler.ConnectCallback and log the TCP/IP info so it its easier to find matching trace.

wfurt avatar Aug 21 '24 21:08 wfurt

@wfurt just FYI the use of HttpClientFactory has worked in limiting the time of the issue to just 2 minutes. So we have the issue the same as before but recreating the handler allows for a successful SSL handshake.

Still working on getting a smaller reproduction.

nathanmascitelli avatar Aug 23 '24 19:08 nathanmascitelli

@wfurt one other update is that we can confirm we do not see this issue with TLS 1.2, we only see it with 1.3.

nathanmascitelli avatar Aug 23 '24 20:08 nathanmascitelli

is there chance that the server is asking for certificate using PHA? In TLS 1.2 it would trigger renegotiation but with TLS 1.3 there is whole new mechanism. I have no direct explanation but there is some trickery obi both sides. The rest should be pretty much similar between TLS 1.2 and 1.3

wfurt avatar Aug 26 '24 18:08 wfurt

@wfurt how can I check for that? The server downstream from the YARP based proxy is a Kestrel webserver, some quick searching doesn't look like we are setting anything related to PHA (post handshake authentication right?) but I might be wrong.

nathanmascitelli avatar Aug 26 '24 19:08 nathanmascitelli

there would be some setting about client certificates.... If you flip to TLS 1.2 you would see renegotiation request after handshake. For TLS 1.3 everything is encrypted so much more difficult to diagnose. Still, if you get packet captures one can guess based on packet sequence.

wfurt avatar Aug 26 '24 19:08 wfurt

everything is speculation at this point @baal2000 and we need more evidence... The failure can be cryptographic, cancellation or IO problem.

I would like to understand if there is a way to resolve the wider problem as described in the case description: TaskCanceledException and not the inner details are available to the consumer, making the underlying issue troubleshooting so difficult.

The library code that internally cancels the request has been already touched by https://github.com/dotnet/runtime/issues/80056 that allowed some Http2 connection errors becoming propagated but not others.

Could that be done generally and not on an exception by exception basis?

baal2000 avatar Sep 16 '24 16:09 baal2000

@wfurt I'm a colleague of @baal2000 and @nathanmascitelli 's and have been working with them during the past few weeks to find an easier/faster way to reproduce this issue.

We were able to create a small setup using a slightly tweaked version of the API template from Visual Studio, along with a client that uses a similar configuration to the one we use in production. The only exception here is that this client is setup to not throw TaskCanceledException once it gets "stuck" so that we can capture dotnet/process dumps.

I have pushed the source code and instructions to repro the issue under the GitHub repo below, please let us know if this is good enough to test on your end or if you have any questions:

https://github.com/brucremo/dotnetruntime106507

This is using a Linux environment along with Docker to simulate the environment locally. To capture the container communication this also spins up an Edgeshark instance.

brucremo avatar Sep 23 '24 15:09 brucremo