Skip to content

Address "System.Net.Sockets.SocketException: Address already in use" on K8S/Linux using HttpClient/TCP #29327

Closed
dotnet/corefx
#38499

Description

@yuezengms

Assumption: Duplicate of #27274 which was fixed by dotnet/corefx#32046 - goal: Port it (once confirmed it is truly duplicate).
This is HttpClient/TCP spin off. UdpClient is covered fully by #27274.

Issue Title

"System.Net.Sockets.SocketException: Address already in use" on Linux

General

Our .net core(v 2.2.0) services are running on Azure Kubernettes Linux environment. Recently we experimenced a lot of error "System.Net.Http.HttpRequestException: Address already in use" while calling dependencies, e.g. Active Directory, CosmosDB and other services. Once the issue started, we kept getting the same errors and had to restart the service to get rid of it. Our http clients are using DNS address, not specific ip and port. The following is the call stack on one example. What can cause such issues and how to fix it?

System.Net.Http.HttpRequestException: Address already in use ---> 
System.Net.Sockets.SocketException: Address already in use#N#   
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)#N#   --- 
End of inner exception stack trace ---#N#   

at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)#N#   
at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)#N#   
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)#N#   
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)#N#   
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)#N#   
at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)#N#   
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)#N#   
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Http.HttpClientWrapper.GetResponseAsync()#N#   
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Http.AdalHttpClient.GetResponseAsync[T](Boolean respondToDeviceAuthChallenge)#N#   
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Http.AdalHttpClient.GetResponseAsync[T]()#N#   
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.SendHttpMessageAsync(IRequestParameters requestParameters)#N#   
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.SendTokenRequestAsync()#N#   
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.CheckAndAcquireTokenUsingBrokerAsync()#N#   
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.RunAsync()#N#   
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenForClientCommonAsync(String resource, ClientKey clientKey)#N#   
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.AcquireTokenAsync(String resource, ClientCredential clientCredential)#N#   

Activity

  1. changed the title [-]"System.Net.Sockets.SocketException: Address already" in use on Linux[/-] [+]"System.Net.Sockets.SocketException: Address already in use" on Linux[/+] on Jan 25, 2019
  2. leecow commented on Jan 25, 2019

    @leecow
    Member

    @karelz , @davidsh - can you have a look?

  3. karelz commented on Jan 25, 2019

    @karelz
  4. karelz commented on Jan 25, 2019

    @karelz
    Member

    Can you please try .NET Core 3.0? It was fixed there ...

  5. yuezengms commented on Jan 26, 2019

    @yuezengms
    Author

    I'll try upgrading. Thanks!

  6. yanrez commented on Jan 26, 2019

    @yanrez

    @karelz do you plan to backport this fix to 2.2 ?

  7. karelz commented on Jan 26, 2019

    @karelz
    Member

    @yanrez not unless there is some good business justification - higher number of affected customers. Is that the case? (this is 2nd ask "only" so far)
    Also, it would help to validate this is truly the root cause, e.g. by trying 3.0 preview/daily build.

  8. yanrez commented on Jan 26, 2019

    @yanrez

    It is happening in some of the clusters. It doesn't seem to consistently repro, but some pods go into this state and stay in it until being terminated. I understand 3.0 is still few months away (I don't know actual timeline though), so my question about 2.2 was based on assumption that hotfix for 2.2 could come earlier than 3.0 release.
    We will look into trying to upgrade and see if it solves the issue.

  9. karelz commented on Jan 26, 2019

    @karelz
    Member

    BTW: It might be good for you to register as MS employees - at least by linking your accounts: https://github.com/dotnet/core/blob/master/Documentation/microsoft-team.md ... that allows other FTEs to see you are MSFT ;)

  10. karelz commented on Jan 26, 2019

    @karelz
    Member

    @yanrez what is the service? How large is it roughly? How often it happens? ... That may support the business justification (even if you were not MSFT ;)).
    If you can verify on 3.0 that would be great. Either way, we may need to verify on early 2.1/2.2 build as part of "test signoff" to make sure we are fixing the real root cause here.

  11. yanrez commented on Jan 26, 2019

    @yanrez

    I will follow up offline, but in some of the regions we see it happening more often - taking down several pods in our k8s cluster per day. It's very annoying at the moment, causing us few dev-hours a day to act on it and mitigate.
    We are also looking into automated mitigation using liveness probe wired into check if we start getting these exceptions and signalling k8s to kill the pod. Unfortunately, it's also non-trivial amount of dev work to build and deploy. Considering we can't exactly predict frequency of the issue, risk is that liveness pod might still impact our availability and cause us missing SLA.

  12. arsenhovhannisyan7713 commented on Feb 4, 2019

    @arsenhovhannisyan7713

    I have same exception on AKS (ver. 1.11.4) , and container microsoft/dotnet:2.2-aspnetcore-runtime
    , Region West Europe .

  13. antoinne85 commented on Feb 7, 2019

    @antoinne85

    Just chiming in to say that my business is also experiencing this issue:
    AKS (v1.9.6)
    Region: Central US
    Image: microsoft/dotnet:2.2-aspnetcore-runtime

  14. yanrez commented on Feb 7, 2019

    @yanrez

    We applied automated mitigation to count number of these exceptions and report negative signal to k8s liveness check. It helped us mitigate the impact. We didn't verify yet if latest builds of net core 3 would resolve the issue

  15. antoinne85 commented on Feb 7, 2019

    @antoinne85

    FWIW, we implemented the same liveness check but then subsequently manage to fix the issue altogether in our deployment.

    For us, we had a service client that was using HttpClient internally. The class was getting instantiated for each incoming request by the DI container (resulting in a new HttpClient for each incoming request). We changed the way the client was registered such that it is only instantiated once for the entire application and the issue was resolved.

  16. 123 remaining items

  17. stephentoub commented on Sep 5, 2019

    @stephentoub
    Member

    does not dispose even though it fits your example of where it should be disposed

    Yes, the client in the GetPage method in that sample should be disposed. Thanks for pointing that out.
    cc: @glennc, @rynowak

  18. MrZoidberg commented on Oct 1, 2019

    @MrZoidberg

    @karelz I experience this problem with .net core 2.2. Is it possible to get private libs to test the backport?

  19. karelz commented on Oct 1, 2019

    @karelz
    Member

    @wfurt can you please create a private build against 2.2 for @MrZoidberg to test?

  20. rockstardev commented on Oct 22, 2019

    @rockstardev

    UPDATE: Disregard this comment... the System.Net.Sockets.SocketException: Address already in use bug kept happening in both cases until. I've only solved it by moving my class from services.AddScoped into services.AddSingleton

    PREVIOUS COMMENT (again, disregard):
    I'm getting this error a lot now in situation where I've switched from:

    httpResponse = await _client.GetAsync(method);

    to:

    using (var req = create(HttpMethod.Get, finalUrl)) {
    	httpResponse = await _client.SendAsync(req);
    }
    
    protected virtual HttpRequestMessage create(HttpMethod method, string url, string postBody = null) {
    	var req = new HttpRequestMessage(method, url);
    	return req;
    }

    I'm disposing of httpResponse after deserializing response in both cases. Any opinion on the code @karelz @stephentoub? I'm on .NET Core 2.2 and would prefer not upgrading to .NET Core 3.0, unless it would help you further debug and solve the problem.

  21. antonioortizpola commented on Oct 22, 2019

    @antonioortizpola

    The problem with the socket comes from the HttpClient, not HttpRequestMessage, how are you generating the HttpClient? are you using DI, HttpClientFactory?

  22. adelhelal commented on Oct 23, 2019

    @adelhelal

    Have you registered your HttpClient at bootstrap ? i.e. something like this:

    services.AddHttpClient<IMyService, MyService>(c =>
    {
        c.BaseAddress = new Uri("https://base_uri");
        c.Timeout = TimeSpan.FromSeconds(30);
    }).SetHandlerLifetime(TimeSpan.FromSeconds(30));

    Then from your MyService inject it in:

    private readonly HttpClient _client;
    
    public MyService(HttpClient client)
    {
        _client = client;
    }

    Implementation should be as simple as:

    using (var response = await _client.GetAsync(url))
    {
        return await response.Content?.ReadAsStringAsync();
    }

    Since you're using the GET method the GetAsync(url) function should be sufficient.

    This lets .NET Core handle all your connection pooling for you so you don't have to worry about managing it yourself.

  23. rockstardev commented on Oct 25, 2019

    @rockstardev

    I'm creating HttpClient by myself in both cases. However if I use it HttpRequestMessage and SendAsync - problems with System.Net.Sockets.SocketException: Address already in use start.

    If I just use GetAsync - no problems.

    @karelz @stephentoub can you please review this and provide any feedback? I'm hoping if you investigate in this direction that you can potentially solve the problem for others as well.

  24. stephentoub commented on Oct 25, 2019

    @stephentoub
    Member

    However if I use it HttpRequestMessage and SendAsync - problems with System.Net.Sockets.SocketException: Address already in use start.

    Can you share the code you use with SendAsync? Are you calling it with ResponseHeadersRead?

  25. draco111 commented on Dec 25, 2019

    @draco111

    i got same error in production too(.netcore 2.2 ubuntu k8s)
    we follow the sample code with aspnet suggest doc and here is the demo code:

    in Startup.cs

            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();
    
                // clients
                services.AddHttpClient<IAddressClient, AddressClient>()
                    .AddHttpMessageHandler(handler => new TimingOutDelegatingHandler())
                    .AddHttpMessageHandler(handler => new RetryPolicyDelegatingHandler());

    here is the AddressClient.cs

    public AddressClient(
                HttpClient httpClient,
                IOptions<UsersApiDomainConfig> usersApiConfig,
                ILogger<AddressClient> logger)
                : base(usersApiConfig)
            {
                _httpClient = httpClient;
                _logger = logger;
            }

    here is the use of httpclient:

            public async Task SyncAddressAsync(AddressModel address)
            {
                var url = GetUrl(Path);
                var response = await _httpClient.PutAsync(
                    url,
                    new StringContent(JsonConvert.SerializeObject(address),
                        Encoding.UTF8,
                        HttpClientConstants.ApplicationJson));

    i think we do as the doc suggest to

  26. rockstardev commented on Jan 2, 2020

    @rockstardev

    However if I use it HttpRequestMessage and SendAsync - problems with System.Net.Sockets.SocketException: Address already in use start.

    Can you share the code you use with SendAsync? Are you calling it with ResponseHeadersRead?

    Thanks for your help @stephentoub and @OpenSourceAries ... in the end I solved my problem in different fashion since I was still getting errors... updated original post: https://github.com/dotnet/corefx/issues/37044#issuecomment-545038295

  27. transferred this issue fromdotnet/corefxon Feb 1, 2020
  28. added this to the 3.0 milestone on Feb 1, 2020
  29. chrisdrobison commented on Apr 1, 2020

    @chrisdrobison

    I'm also seeing this exception with MongoDB driver in K8s, which isn't using the HttpClient. So is this fix this a thing or is the scope larger than originally anticipated?

  30. ghost locked as resolved and limited conversation to collaborators on Dec 14, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugtenet-compatibilitytenet-reliability

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions