runtime icon indicating copy to clipboard operation
runtime copied to clipboard

ObjectDisposedException in SqlClient SNIProxy

Open cahlbin opened this issue 9 years ago • 24 comments

The following is the exception / stacktrace I get in my application:

{ "ExceptionType": "ObjectDisposedException", "Message": "Cannot access a disposed object.\nObject name: 'System.Net.Sockets.UdpClient'.", "ObjectName": "System.Net.Sockets.UdpClient", "Data": null, "StackTrace": " at System.Net.Sockets.UdpClient.EndReceive(IAsyncResult asyncResult, IPEndPoint& remoteEP)\n at System.Net.Sockets.UdpClient.<>c.<ReceiveAsync>b__55_1(IAsyncResult asyncResult)\n at System.Threading.Tasks.TaskFactory1.FromAsyncCoreLogic(IAsyncResult iar, Func2 endFunction, Action1 endAction, Task1 promise, Boolean requiresSynchronization)", "Source": "System.Net.Sockets", "HResult": -2146232798 }

Environment setup:

  • Application running on netcoreapp1.0
  • SQL server 2012, with SQL Server Browser Service (intentionally) disabled.

I've pinpointed it to that if I pass a ConnectionString to the SqlClient that doesn't include an explicit port (i.e. simply on the form "Data Source: "), then the exception occurs and ends up in my TaskScheduler.UnobservedTaskException.

If I do specify an explicit port in the ConnectionString, e.g. "Data Source: ,1433", then no exception is thrown. I assume that is simply because the code paths for doing SNI port lookup is not executed at all.

One relevant code path is https://github.com/dotnet/corefx/blob/6b5ef121ebea45b14f489a177e2e3f27fce86781/src/System.Net.Sockets/src/System/Net/Sockets/UDPClient.cs#L651

It seems like EndReceive is invoked unconditionally in the AsyncCallback, thus also possibly after the UdpClient goes out of scope (the using scope). I'm thinking that UdpClient.ReceiveAsync() must check whether the UdpClient has actually gone out of scope before invoking the EndReceive. And if it has gone out of scope, it should be considered cancelled / timed out, and throw such an exception (instead of now resulting in an ObjectDisposedException

cahlbin avatar Dec 20 '16 14:12 cahlbin

@geleems Can you look into this?

saurabh500 avatar Jan 07 '17 00:01 saurabh500

@cahlbin I am not able to repro this. I am using the DataSource = "mySqlServerMachine" I have turned off the Sql Browser process and I am using connection.Open() to connect to it. The connection succeeds without specifying the port for DataSource.

Can you give me a small repro that I can work with?

saurabh500 avatar Jan 11 '17 02:01 saurabh500

I am closing this due to a lack of repro and any sample apps. Please reopen if this issue persists.

saurabh500 avatar Feb 10 '17 01:02 saurabh500

It can be reproduced and the bug is still there in netcore1.1. Two things you probably forgot when you tried to reproduce:

  • Try it on Linux. I couldn't reproduce on Windows, but with the same code the error came every time on Linux.
  • You have to force GC, because otherwise resources are not disposed at all, and you will only experience the bug after heavy computation, not immediately.

You don't have to issue an SQL command, just opening and closing the SqlConnection is enough to reproduce. Something like this:

string connString = "Server=tcp:<myAzureSqlServer>.database.windows.net,1433;Database=<myDatabase>;User ID=<myUser>;Password=<myPassword>;Encrypt=True;Connection Timeout=600;"

SqlConnection p_conn = new SqlConnection(connString);
p_conn.Open();
p_conn.Dispose();

GC.Collect();
GC.WaitForPendingFinalizers();	// TaskScheduler.UnobservedTaskException() will be called if default SQL port ",1433" is missing from connectionString on Linux

A repo collaborator should reopen the issue, plz.

gyantal avatar Mar 13 '17 17:03 gyantal

@karelz Can you help involve the owners of the System.Net for this issue? This seems to be coming from SqlClient's usage of UDPClient.ReceiveAsync() Also the analysis from @cahlbin points to UdpClient

saurabh500 avatar Mar 24 '17 20:03 saurabh500

@saurabh500 changing the area label is sufficient - owners will get notification form my tool. You can CC owners directly if you want - see owners list.

karelz avatar Mar 24 '17 20:03 karelz

@geoffkizer @davidsh @CIPop @Priya91 any thoughts?

karelz avatar Mar 24 '17 20:03 karelz

@saurabh500 from the description it appears that SqlClient internals are using a disposed UdpClient. In that case, the exception would be by design from the Sockets stand-point. (See https://msdn.microsoft.com/en-us/library/system.net.sockets.udpclient.receiveasync(v=vs.110).aspx#Anchor_1 - ObjectDisposedException is one of the documented exceptions thrown by ReceiveAsync)

CIPop avatar Mar 24 '17 21:03 CIPop

Moving back to SqlClient then - @saurabh500 can you check SqlClient code please?

karelz avatar Mar 24 '17 21:03 karelz

Thanks. Please send it our way

saurabh500 avatar Mar 24 '17 21:03 saurabh500

الحصول على Outlook for Android

po80053 avatar Mar 25 '17 09:03 po80053

I am trying to reproduce the issue in Linux (Ubuntu 14.04). Could you please provide the full stack trace?

geleems avatar Apr 20 '17 23:04 geleems

UdpClient is used for querying TCP port only when instance name is given in connection string. UdpClient is not even used if a port is specified explicitly in connection string.

I am using Ubuntu 14.04 x64 to reproduce the issue.

The connection strings I used to reproduce the issue are:

  • Data Source=GELEE-VM-WIN10B;Integrated Security=True
  • Data Source=GELEE-VM-WIN10B\instance1;Integrated Security=True

And the repro code is:

for (int k = 0; k < 1000; ++k)
{
	SqlConnection connection = new SqlConnection(connectionString);
	connection.Open();
	connection.Dispose();	
}

The SqlClient code version I used was

commit c6a5096077381aae1c2cbc92728dde08188d8b72
Date:   Thu Apr 20 15:55:17 2017 -0700

I could not see any failure in the repro test.

geleems avatar Apr 21 '17 17:04 geleems

Another repro test:

  • Environment: Ubuntu 14.04 x64
  • SqlClient code version:
commit c6a5096077381aae1c2cbc92728dde08188d8b72
Date:   Thu Apr 20 15:55:17 2017 -0700
  • SQL Browser is off intensionally.
  • Connection strings:
    • Data Source=GELEE-VM-WIN10B;Integrated Security=True
    • Data Source=GELEE-VM-WIN10B,1432;Integrated Security=True
  • Repro sample code:
for (int k = 0; k < 1000; ++k)
{
	SqlConnection connection = new SqlConnection(connectionString);
	connection.Open();
	connection.Dispose();
	System.GC.Collect();
	System.GC.WaitForPendingFinalizers();
}

I could not see any failure in this repro test as well.

geleems avatar Apr 21 '17 19:04 geleems

Thanks for spending time on it. The good news I can repro it with a simple code. I am on Ubuntu 14.04 too. Could you try this? It really gives me the error. 100% reproducible. However, interestingly, the error comes only once; at the first wrong connection opening. (e.g. if you select "2" from the menu many times, only the first time will it produce the error. You have to restart the app to reproduce it again.)

(change the ZZZZ in the code according to your database, plz. I am using an Azure SQL server as you see from the domain name, but the problem shouldn't be Azure specific, although you better test it with a remote SQL server, not a locally running SQL server.)

I hope it will help. This is the whole Program.cs. Nothing else is needed to repro.


using System;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace ReproSqlConnectionUnobservedException
{
    class Program
    {
        static void Main(string[] args)
        {
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;     // You have to attach this ! Without it you will not see the Error.
            string connStringGood = "Server=tcp:ZZZZZ.database.windows.net,1433;Database=ZZZZZ;User ID=ZZZZZ@ZZZZZ;Password=ZZZZZ;Encrypt=True;Connection Timeout=600;";
            string connStringBad = "Server=tcp:ZZZZZ.database.windows.net;Database=ZZZZZ;User ID=ZZZZZ@ZZZZZ;Password=ZZZZZ;Encrypt=True;Connection Timeout=600;";

            string userInput = String.Empty;
            do
            {
                Console.WriteLine("--------- Select a number and press ENTER ----------");
                Console.WriteLine("1. Try connection with good ConnStr");
                Console.WriteLine("2. Try connection with bad ConnStr");
                Console.WriteLine("3. Exit");
                userInput = Console.ReadLine();
                if (userInput == "3")
                    break;

                var connString = (userInput == "1") ? connStringGood : connStringBad; 
                var conn = new SqlConnection(connString);
                conn.Open();
                conn.Dispose();
                Console.WriteLine("Connection was openned and closed.");

                GC.Collect();
                GC.WaitForPendingFinalizers();
            } while (true);
        }

        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            Console.WriteLine("Error. TaskScheduler_UnobservedTaskException was called !!! (This only happens on Linux (not Windows) and only when default SQL port number is not given.");
        }
    }
}

gyantal avatar Apr 21 '17 22:04 gyantal

@gyantal Thanks for the details! I performed another test with your code.


  • Env: Ubuntu 14.04.5 LTS
  • .NET Core version: 1.1
  • The code I actually used:
using System;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace hwapp
{
    class Program
    {
        static void Main(string[] args)
        {
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            string connStringGood = "Server=tcp:<hostname>,1433;User ID=<test_user_id>;Password=<test_user_pw>;Connect Timeout=600;";
            string connStringBad = "Server=tcp:<hostname>;User ID=<test_user_id>;Password=<test_user_pw>;Connect Timeout=600;";

            string userInput = String.Empty;
            do
            {
                Console.WriteLine("--------- Select a number and press ENTER ----------");
                Console.WriteLine("1. Try connection with good ConnStr");
                Console.WriteLine("2. Try connection with bad ConnStr");
                Console.WriteLine("3. Exit");
                userInput = Console.ReadLine();
                if (userInput == "3")
                    break;

                var connString = (userInput == "1") ? connStringGood : connStringBad; 

                var conn = new SqlConnection(connString);
                conn.Open();
                conn.Dispose();
                Console.WriteLine("Connection was openned and closed.");

                GC.Collect();
                GC.WaitForPendingFinalizers();
            } while (true);
        }

        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            Console.WriteLine("Error. TaskScheduler_UnobservedTaskException was called !!! (This only happens on Linux (not Windows) and only when default SQL port number is not given.");
        }
    }
}

The only difference from your code is that I took off Encrypt=True; from the connection string, because it triggered authentication exception since I am using local SSL certification.


This is the result:

$ dotnet run
--------- Select a number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
2
Connection was openned and closed.
--------- Select a number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
2
Connection was openned and closed.
--------- Select a number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
2
Connection was openned and closed.
--------- Select a number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
2
Connection was openned and closed.
--------- Select a number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
3
$ 

I ran the code many times again, but the connections were opened and disposed successfully, and I could never observe the exception, unfortunately. The host the SQL Server is running on is Windows VM, and this repro code was running another Ubuntu VM, and they are both running on the same physical machine. Can this affect the result?

geleems avatar Apr 25 '17 21:04 geleems

@gyantal Another attempt to repro:

string connStringGood = "Server=tcp:<remote_hostname>,1432;Database=<database_name>;User ID=<username>;Password=<password>;Connect Timeout=600;";
string connStringBad = "Server=tcp:<remote_hostname>;Database=<database_name>;User ID=<username>;Password=<password>;Connect Timeout=600;";

This <remote_hostname> is remote machine, which is separated physical box from the one Ubuntu is running on. The default port for this SQL Server is 1432.


The result was the same, and I could not face the exception.

$ dotnet run
--------- Select a number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
2
Connection was openned and closed.
--------- Select a number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
2
Connection was openned and closed.
--------- Select a number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
2
Connection was openned and closed.
--------- Select a number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
2
Connection was openned and closed.
--------- Select a number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
3
$

geleems avatar Apr 25 '17 22:04 geleems

Thank you for the investigation. It is getting very interesting...

Making another step to find this elusive thing... I have created a temporary SQL server on Azure. (copied the AdventureWorks database into it.) So, in this case you and me will test it with exactly the same SQL server. (Azure server, default port 1433, etc.) Could you test exactly the same Program.cs with the following modification:

string connStringGood = "Server=tcp:testrepobug.database.windows.net,1433;Database=TestDB;User ID=test256User@testrepobug;Password=t987estBB;Connection Timeout=600;";
string connStringBad = "Server=tcp:testrepobug.database.windows.net;Database=TestDB;User ID=test256User@testrepobug;Password=t987estBB;Connection Timeout=600;";

The username and password are valid and works. I got this in the console with these connection strings:

ubuntu:~/temp/RepoSqlBug/RepoSqlBug$ dotnet run
--------- Select number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
1
Connection was openned and closed.
--------- Select number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
2
Connection was openned and closed.
Error. TaskScheduler_UnobservedTaskException was called !!! (This only happens on Linux (not Windows) and only when default SQL port number is not given.
--------- Select number and press ENTER ----------
1. Try connection with good ConnStr
2. Try connection with bad ConnStr
3. Exit
3

If with those SQL connection string you still Not have the issue, then I don't know... I am going to recreate a new Ubuntu VM and will give you access if it is reproducible. Thanks, George

gyantal avatar Apr 25 '17 23:04 gyantal

Hi,

I have created a temporary brand new Ubuntu 16.04 LTS VM from scratch, and installed DotNetCore fresh as instructed here https://www.microsoft.com/net/core#linuxubuntu And ...can reproduce the bug with the same code with the Test SQL server I created from scratch an hour ago.

You can login to this temporary Ubuntu server and look around. E.g. Use Putty.exe and set these in Putty:

  • Host name: "[email protected]"
  • port 22 (choose SSH)
  • in the Connection/SSH/Auth/ Private key file for auth. Browse and give it the *.ppk file I attach here. (but remove the *.txt extension from the file name of the attached file.)

After that you can login to the Ubuntu server. cd ~/RepoSqlBug/ReproSqlConnectionUnobservedException dotnet restore dotnet run

"Error. TaskScheduler_UnobservedTaskException was called !!!" can be reproduced. What do you think?

HQaTestKeyPairName.ppk.txt

gyantal avatar Apr 26 '17 00:04 gyantal

Probably not the difference, but note my *.csproj

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="System.Data.SqlClient" Version="4.3.0" />
  </ItemGroup>
</Project>

gyantal avatar Apr 26 '17 06:04 gyantal