"Port" leaking in C# WebDriver.dll
Meta -
OS:
Windows 10, Windows Server 2008 R2
Selenium Version:
WebDriver 3.4.0
Browser:
Firefox and Chrome
Browser Version:
Firefox: 53.0.3 (32 bits)
Chrome: Version 59.0.3071.86 (Official Build) (64-bit)
Expected Behavior -
WebDriver suppose to close the ports after each commands sent to ChromeDriver or GeckoDriver
Actual Behavior -
WebDriver keeps the ports open until the WebDriver quit(). This caused the ports run out from the OS when I had 8 parallel tests running together without open and close ChromeDriver or FirefoxDriver.
Steps to reproduce -
Run the Selenium Tests with ChromeDriver or FirefoxDriver with any simple action, e.g. Navigate to a website. Repeat this step for 1000 time.
Open a Windows Command Prompt, type: netstat -a -b
You will find the ChromeDriver/GeckoDriver holds up about 1000 ports without releasing.
I have amended the code in OpenQA.Selenium.Remote.DriverServiceCommandExecutor.cs, line 37 old code: this(driverService, commandTimeout, true) new code: this(driverService, commandTimeout, false)
and
OpenQA.Selenium.Remote.HttpCommandExecutor.cs, line 46: old code: : this(addressOfRemoteServer, timeout, true) new code: : this(addressOfRemoteServer, timeout, false)
Retest again with the above step, we can see the ChromeDriver / Gecko Driver doesn't hold up the port any more.
It seems for HttpWebRequest object, even it is out of scope, if its' KeepAlive property is true, the .net runtime holds it until the WebDriver is quit and closed.
In theory, I can't think of HttpCommandExecutor should have HttpWebRequest should have KeepAlive = true as it looks like HttpCommandExecutor is running stateless commands. Maybe you can consider to remove the passing in of the attribute to avoid future problem.
Kind regards
Ken Han
Self Service Tech Lead Fairfax Media Australia
Right now none of drivers except to standalone support keep-alive connections (e.g. ChromeDriver doesn't support it) so I don't think there is anything we can do to improve the behavior.
I'll leave that open for @jimevans to have a look, maybe I misunderstood the problem.
Alex,
I mainly testing on Chrome and Firefox, therefore, I mentioned these two. Just checked the code base, this problem seems happen to all the C# Drivers within the WebDriver dll: Chrome, Edge, Firefox, IE, Opera, Safar, and RemoteWebDriver.
I encountered the problem when I ran my test classes in parallel mode, it crashed the Selenium WebDriver.
I have 20 test classes, and each of them consists of 8 to 15 test cases. The login to the test sites takes quite a while, so I decided login using NUnit's OneTimeSetup and OneTimeTearDown.
Then I realised my test crashed from time to time, no matter I ran them in VS 2017, or Windows Powser Shell. When it happens, all the test browsers were freeze, no more movement, but I knew they haven't finished yet. All I can do is terminate the job and restart the test and hope the next run won't crash.
After eliminated all other possibilities: OS, test frameworks...etc, I narrowed down to the FirefoxDriver and ChromeDriver C# class. And found that for HttpCommandExecutor, the KeepAlive option = true did actually keep the port open after the response received, and HttpWebRequest object out of the scope of the function and ready for GC collection. The ports that being held only got released when ChromeDrive.Quite() called. HttpCommandExecutor is being used for all Selenium C# class webdriver to send commands to the native OS browser driver.
After realized the cause of the bug, my immediate work around was to open and quit ChromeDriver/FirefoxDriver (I tested both) at each case, although it doubles the over all testing time, but the tests didn't crash any more, they all finished to the end, test report was collected.
I then took the WebDriver source code and recompiled with HttpCommandExcecutor.KeepAlive option = false, all of sudden, the weird situation is gone and my tests not hung any more.
Analysis:
- Each action to the C# WebDriver caused one web request sent to geckodriver.exe or chromedriver.exe or other native driver. One port is being held per request.
- My test cases have about 30 actions. At the end of one test case, 30 ports are being held.
- When I have 15 tests, around 400 to 500 ports are being held.
- The above situation is fine if I run the test in single thread. When I run the test classes in 8 threads with two browsers each thread (one for consumer site, and one for admin site). This becomes 16 x 500 = 8000 ports.
- The number maybe varies, but surely my Windows 10 can't afford that much ports open. When its limit reached, it just can't allocate more port. Then the tests hung and dies.
To reproduce in a simple scenario, the following should work:
Open ChromeDriver from C# code, set up a while loop, within the while loop, navigate to one site, say google.com.au and repeat the navigation say 100,000 times. I expect the each navigation request to chromedriver.exe hold up one port. The program should hang at the middle of running.
The fix is simple, simply remove that KeepAlive option for external call, and within the send request method, change it to false. Another option, is to make sure all call to the constructor public HttpCommandExecutor(Uri addressOfRemoteServer, TimeSpan timeout, bool enableKeepAlive), the enableKeepAlive is set to false.
I am not sure whether this is really bug in the .Net runtime though. At least, we found the work around.
Kind regards
Ken
Ok, I think I understand the problem, but it's going deep into internals of .NET bindings, so let's wait for Jim to respond.
Any news about this issue ? It is planned to solve it soon ? Because I'm also having the same issue since one week and currently finding a workaround...
For the workaround, I had to recompile the dotnet project with the option set to off.
On 17 Oct 2017 5:52 pm, "Lauriane Savary" [email protected] wrote:
Any news about this issue ? It is planned to solve it soon ? Because I'm also having the same issue since one week and currently finding a workaround...
— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/SeleniumHQ/selenium/issues/4162#issuecomment-337135252, or mute the thread https://github.com/notifications/unsubscribe-auth/ALkRUN5H-bxtLPZ2Hg1OI6lz1er0mvKhks5stE7EgaJpZM4N2uBj .
Latest chromedriver (2.35) contains a workaround for the keep-alive problem, it allows to actually reuse connections. But it's not a fix, it's a workaround. In order to make it work client must send Connection: keep-alive header with each request.
The problem is that when using HTTP 1.1 HttpWebRequest assumes that keep-alive is on by default and doesn't send the header. I haven't found the proper way (without reflection) to forcibly add a header so far but can confirm adding it works. Any ideas?
Also, +1 to deinternalizing enableKeepAlive parameter.
if you are running into port exhaustion, you should check your TCP/IP settings and tune your network stack accordingly. The default ephemeral port range in some desktop operating systems (like Windows) is not nearly sufficient for applications doing high socket throughput.
@cgoldberg in my current case it's more complicated than that. I can only say that the average test creates about 3000 connections, now imagine a test suite and think about time those connections are in TIME_WAIT and some new tests are starting at this moment. No tuning will help, especially when we will run this in parallel
Hi all,
In our case, we had to turn the flag off and recompile the driver to fix the issue.
On 22 Feb 2018 8:38 am, "Vasya Aksyonov" [email protected] wrote:
@cgoldberg https://github.com/cgoldberg in my current case it's more complicated than that. I can only say that the average test creates about 3000 connections, now imagine a test suite and think about time those connections are in TIME_WAIT and some new tests are starting at this moment. No tuning will help, especially when we will run this in parallel
— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/SeleniumHQ/selenium/issues/4162#issuecomment-367481630, or mute the thread https://github.com/notifications/unsubscribe-auth/ALkRUBCwf8AtJslpupFfYP1xQbFBOrMVks5tXIy-gaJpZM4N2uBj .
Hey everyone,
I've tried everything that I can find and am still having these issues. I'm using the most recent version of chromedriver (v2.40) and have forced HttpCommandExecutor.enableKeepAlive to false at all times and still end up with ports in TIME_WAIT. Just as a test, I've forced the header Connection: close to be sent with the request and that also doesn't work.
Is there something I'm missing when it comes to the mentioned workaround? I'm trying to do browser automation on a relatively large scale and can't get around this roadblock.
Hi Bryce,
In my case, I have made changes to two files. HttpCommandExecutor.cs internal class HttpCommandExecutor : ICommandExecutor { private const string JsonMimeType = "application/json"; private const string ContentTypeHeader = JsonMimeType + ";charset=utf-8"; private const string RequestAcceptHeader = JsonMimeType + ", image/png"; private Uri remoteServerUri; private TimeSpan serverResponseTimeout; private bool enableKeepAlive; private CommandInfoRepository commandInfoRepository = new WebDriverWireProtocolCommandInfoRepository();
/// <summary>
/// Initializes a new instance of the <see
cref="HttpCommandExecutor"/> class /// /// Address of the WebDriver Server /// The timeout within which the server must respond. public HttpCommandExecutor(Uri addressOfRemoteServer, TimeSpan timeout) : this(addressOfRemoteServer, timeout, true) { }
DriverServiceCommandExecutor.cs : internal class DriverServiceCommandExecutor : ICommandExecutor { private DriverService service; private HttpCommandExecutor internalExecutor;
/// <summary>
/// Initializes a new instance of the <see
cref="DriverServiceCommandExecutor"/> class.
///
/// The
After recompiled the solution, you may want to use ILSpy to inspect the generated dlls to ensure the changes are actually inside.
Ken Han
On Sat, 16 Jun 2018 at 06:33, Bryce Barbara [email protected] wrote:
Hey everyone,
I've tried everything that I can find and am still having these issues. I'm using the most recent version of chromedriver (v2.40) and have forced HttpCommandExecutor.enableKeepAlive to false at all times and still end up with ports in TIME_WAIT. Just as a test, I've forced the header Connection: close to be sent with the request and that also doesn't work.
Is there something I'm missing when it comes to the mentioned workaround? I'm trying to do browser automation on a relatively large scale and can't get around this roadblock.
— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/SeleniumHQ/selenium/issues/4162#issuecomment-397734172, or mute the thread https://github.com/notifications/unsubscribe-auth/ALkRUCpAgau6NYA4iXsX_3rrZk_uy6pGks5t9BoNgaJpZM4N2uBj .
Hi @BryceBarbara ,
Please find the patches for the change.
- first patch: changed the cs files for the flag.
- second to fourth patches: workaround to avoid a full build of the solution. So that WebDriver.dll get built only.
accidentally closed the issue. Reopening...
@BryceBarbara
and still end up with ports in TIME_WAIT
having sockets in TIME_WAIT state is totally normal.. that's the way TCP works. Are you experiencing actual port exhaustion or simply seeing some sockets in TIME_WAIT state?
@kenhan168 if your patch fixes something, why not submit a Pull Request?
Hi all,
Pull request is up: https://github.com/SeleniumHQ/selenium/pull/6162
How can disabling keep-alive resolve port exhaustion issue? If you close connection after a request you'll have to engage a new port for the next request.
Quite contrary, keep-alive options should help us if all parties implement it properly.
The keep-alive setting didn't work when I reported the issue initially.
The intention was good, however, the existing connection was not able to be recycled. This ended with port exhaustion. In addition, the keep-alive setting is stateful design, which restricts scaling.
To test the port exhaustion, open a chromedriver from WebDriver, then issue the command open a website within a while loop of true, then you should be able to reproduce the port exhaustion issue.
Ken Han Mobile: +61 (0) 466 675 144 +61 (0) 430 817 085 Email: [email protected]
On Mon, 16 Jul 2018 at 17:34, Alexei Barantsev [email protected] wrote:
How can disabling keep-alive resolve port exhaustion issue? If you close connection after a request you'll have to engage a new port for the next request.
Quite contrary, keep-alive options should help us if all parties implement it properly.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/SeleniumHQ/selenium/issues/4162#issuecomment-405168199, or mute the thread https://github.com/notifications/unsubscribe-auth/ALkRUE-jgVYmlfUIFQ7fzVzqsre6NhwFks5uHEHygaJpZM4N2uBj .
As stated by @outring earlier on this thread WebRequest under HTTP 1.1. assumes keep-alive by default and so doesn't send it when KeepAlive is true on the actual WebRequest object. ChromeDriver.exe 2.35 and up does not make the same assumption and so you MUST actually pass the header. What worked for me is the forcing of keep-alive in the WebRequest. Though as was said reflection is required to do so but it works fine. Here's the code I used:
private static void ForceExecutorToSupplyKeepAlive(ChromeDriver driver)
{
var commandExecutor = GetPropertyValue<ICommandExecutor>(driver, "CommandExecutor");
var httpCommandExecutor = GetPropertyValue<HttpCommandExecutor>(commandExecutor, "HttpExecutor");
httpCommandExecutor.SendingRemoteHttpRequest += (sender, args) =>
{
var sp = args.Request.ServicePoint;
var prop = sp.GetType().GetProperty("HttpBehaviour", BindingFlags.Instance | BindingFlags.NonPublic);
Debug.Assert(prop != null, nameof(prop) + " != null");
prop.SetValue(sp, (byte) 0, null);
};
}
private static PropertyInfo GetProperty(object obj, string property)
{
return obj.GetType().GetProperty(property, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
}
private static T GetPropertyValue<T>(object obj, string property)
{
return (T)GetProperty(obj, property)?.GetValue(obj);
}
This version is for Selenium Web Driver 3.14. It's slightly different under 3.13.x but the principle is the same. https://chromium.googlesource.com/chromium/src/+/736efbc1c284f9b85d7dcda22771e23786def5d5%5E%21/#F0 https://bugs.chromium.org/p/chromedriver/issues/detail?id=1529
@cgoldberg Sorry for the delay! I do actually experience port exhaustion and had to lower the OS timeout duration to 30 seconds (default is 3 minutes) to avoid the system periodically throwing exceptions.
I'm running at least 80 instances of headless chrome on some jumbo machine so my use case might be a pretty rare edge-case. I've yet to get the time to investigate Selenium Grid which might serve me better in the long-run.
@kenhan168 When will the https://github.com/SeleniumHQ/selenium/pull/6162 be merged. We use Selenium C# bindings with Nunit to run 10 parallel test sessions in Saucelabs cloud. We use selenium version 3.11.0 Each session uses a thread safe Webdriver instance. Each session uses the same webdriver instance till the end of that session. We have been getting this error for random tests at random times, for a long time now. It has become a hassle as it gives false negatives. OpenQA.Selenium.WebDriverException : A exception with a null response was thrown sending an HTTP request to the remote WebDriver server for URLhttp://ondemand.saucelabs.com/wd/hub/session/4121bd78c22940e9a6deaf615b7c143f/execute_async. The status of the exception was KeepAliveFailure, and the message was: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. ----> System.Net.WebException : The underlying connection was closed: A connection that was expected to be kept alive was closed by the server.
Also please let me know if upgrading to v3.14.0 will solve anything related to the keepalive failure ? https://github.com/SeleniumHQ/selenium/blob/master/dotnet/CHANGELOG
It says - Additionally, this change exposes the IsKeepAliveEnabled property to make it easier to set whether or not the "keep alive" header is sent when communicating between the language bindings and the remote end WebDriver implementation.