dotnet / SqlClient

Microsoft.Data.SqlClient provides database connectivity to SQL Server for .NET applications.
MIT License
851 stars 286 forks source link

Open connection issue on Linux #126

Closed sjc9999 closed 4 years ago

sjc9999 commented 5 years ago

I'm using Microsoft.Data.SqlClient 1.0.19128.1-preview on Linux RHEL 6 to connect to SQLServer running on Windows. This is my connection string: string connetionString Server="SomeComputer\SQLIntegTest,61245;Database=db4;uid=user;pwd=password;Trusted_Connection=No"

with this code:

SqlConnection cnn = new SqlConnection(connetionString); cnn.Open()

I get the following error. The same code works on windows. Any help would be appreciated.

Unhandled Exception: Microsoft.Data.SqlClient.SqlException: Connection Timeout Expired. The timeout period elapsed during the post-login phase. The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=118; handshake=271; [Login] initialization=11; authentication=14; [Post-Login] complete=14041; ---> System.ComponentModel.Win32Exception: Unknown error 258 --- End of inner exception stack trace --- at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken) at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) at Microsoft.Data.SqlClient.SqlConnection.Open() Abort (core dumped)

ErikEJ commented 5 years ago

That is an odd server name in the connection string, maybe change to:

SomeComputer,61245
sjc9999 commented 5 years ago

I tried your suggestion same result works on Windows but not Linux.

ErikEJ commented 5 years ago

Can you resolve the server name from the Linux box?

sjc9999 commented 5 years ago

Yes I use the same connection string with python pyodbc just adding the driver parameter which is not need with c#

sjc9999 commented 5 years ago

Well I was testing with SQL Server 2008 and switched to SQL Server 2016 and that works. Interestingly the Windows version of Microsoft.Data.SqlClient with both but the Linux version only works with 2016.

cheenamalhotra commented 5 years ago

@sjc1832

Have you checked with SQL Server 2012 by any chance? Since SQL Server 2008 and 2008 R2 are Out of Support, we wouldn't fix the driver to support them. If the issue happens with SQL Server 2012 as well (which is the oldest of supported SQL Servers) we can consider taking a deeper look.

sjc9999 commented 5 years ago

I have not checked 2012.

saravananpalanivel commented 5 years ago

I'm facing same issue - i.e. my dotnet core 3 preview8 application is running in Kubernetes cluster (on premise Linux container) which is trying to access remote MSSQL Server 2014 - but hung at connection.Open(). But same works with MSSQL Server 2016.

Connection string : "Data Source=10.150.109.140,1433;Initial Catalog=ReportServer;Connect Timeout=60;User ID=username;Password=password; Persist Security Info=False;Packet Size=4096"

Docker images used : mcr.microsoft.com/dotnet/core/sdk:3.0.100-preview8 & mcr.microsoft.com/dotnet/core/aspnet:3.0.0-preview8

lukebronts commented 5 years ago

Hi, I am running into the same issue. We just upgraded one of our apps to .netcore 3. Connecting to sql works on my windows dev machine, but when we deploy to our staging environment (ECS cluster on AWS - linux machines) it stops working.

The error we get in our logs is: System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

The connection string is: Application Name={appName};Server={host};User ID={id};Password={password};Database={dbname};Persist Security Info=false;Connection Lifetime=60

The machine has access to the sql box, if I role the code back to the .net core 2.2 version everything works fine. Its after upgrade to .netcore 3 it has stopped.

The code that fails is simply using (SqlConnection connection = new SqlConnection(settings.ConnectionString)) { connection.Open(); }

The sql box is an RDS instance provided by AWS. The Engine version is 13.00.2164.0.v1. I dont seem to be able to see what version of sql server it is under the hood, but it looks like its 2016 (https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_SQLServer.html)

The EC2 box inside our ECS cluster is Amazon Linux AMI 2018.03.p x86_64 ECS HVM GP2

Docker Images used: mcr.microsoft.com/dotnet/core/aspnet:3.0 mcr.microsoft.com/dotnet/core/sdk:3.0

cheenamalhotra commented 5 years ago

Hi @lukebronts

System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

Could you tell us the version of Microsoft.Data.SqlClient driver in use? Please try updating to latest Microsoft.Data.SqlClient version "1.0.19269.1" and confirm if the error occurs again.

Also please confirm SQL Server version from RDS cluster, by executing SELECT @@VERSION.

lukebronts commented 5 years ago

Hi @cheenamalhotra

I have tried both 1.0.19269.1 and the current one in preview 1.1.0-preview1.19275.1. Both do not work. The sql version is Microsoft SQL Server 2016 (RTM-CU2) (KB3182270) - 13.0.2164.0 (X64) Sep 9 2016 20:13:26 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows Server 2012 R2 Standard 6.3 (Build 9600: ) (Hypervisor)

lukebronts commented 5 years ago

Hi @cheenamalhotra

Do you have an update on this issue? Have you managed to find anything?

Thanks

mgbee8 commented 5 years ago

Having the same issue Sql Server Version is 2016, running in Docker with netcore 3 using mcr.microsoft.com/dotnet/core/runtime:3.0-buster-slim using System.Data.SqlClient 4.7.0 and tried 4.8.0-preview1.19504.10, same issue

yukiwongky commented 5 years ago

@mgbee8 does it work for you if you use netcore 2.2? Also, can you try to use the latest Microsoft.Data.SqlClient?

mgbee8 commented 5 years ago

yes, I have the same issue using netcore 2.2 and Microsoft.Data.SqlClient

voroninp commented 5 years ago

@mgbee8 Same with us. asp.net core 3 docker container and MS SQL 2016 (13.0.5216.0) on AWS RDS. However, this happens only in Test environment.

An exception occurred while iterating over the results of a query for context type 'IdentityServer4.EntityFramework.DbContexts.PersistedGrantDbContext'. Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (258): Unknown error 258 at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at

Maybe there is some relation to new client.

Jonesie commented 4 years ago

Im having the same issue as @voroninp .

I have a production stack in AWS working fine. My test stack times out connecting to RDS.

Task running in fargate in private subnet of own vpc. SQL Express 14.00.3015.40.v1 in same private subnet. .Net Core 3 in docker mcr.microsoft.com/dotnet/core/aspnet:3.0

I spend 4 hours with AWS support and proved that the network and security setup is correct. We could get powershell to connect to SQL ok.

avboivin commented 4 years ago

I spent hours yesterday trying everything to fix this issue and ended up finding that a TLS version mismatch caused the issue on my debian10 server. This is what brought me to this solution.

Server version (not a container): Linux 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64

Dotnet core version: APP#1 -> 3.1 self-contained aspnetcore webapp APP#2 -> 2.2 self-contained aspnetcore webapp

APP#1 could not connect to SqlServer, same error as others in this thread :

Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached.
at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)\n   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\n   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)\n   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)\n   at Microsoft.Data.SqlClient.SqlConnection.Open()\n   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)\n   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)\n   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)\n   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()\n   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)\n   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)\n   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)\n   at System.Linq.Queryable.First[TSource](IQueryable`1 source)\n

APP#2: Could connect just fine.

I edited the openssl.conf file and rebooted the server, problem solved.

/etc/ssl/openssl.cnf at the very end of the file, I commented ssl_conf and changed MinProtocol (I don't think MinProtocol matters though)

[default_conf]
#ssl_conf = ssl_sect

[ssl_sect]
system_default = system_default_sect

[system_default_sect]
MinProtocol = TLSv1.1
CipherString = DEFAULT@SECLEVEL=2

dotnetcore 3.1 app can now connect to SQL server just fine.

Now to take a look at the settings on my SqlServer instance TLS 1.0 is disabled HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server

TLS 1.1 and 1.2 are both enabled HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server Here is microsoft documentation for sqlserver TLS where I found these registry keys

Can someone explain to me the logic behind this fix ? I'm trying to understand if this is actually the fix or if it might have been something else.

cheenamalhotra commented 4 years ago

Hi @avboivin

The exception you posted doesn't seem related to TLS Version change, but rebooting might have solved it since that would flush all open connections. Could you update Microsoft.Data.SqlClient version to 1.1.0 (with explicit package reference) and then confirm if the issue persists.

If you have TLS 1.2 support enabled on Server, client supporting TLS1.2 protocol should be able to connect without any change needed to SSL Configurations.

To know the TLS version in use, you can capture network traces with Wireshark, where you can see the TLS version in pre-login packets where Client and Server perform handshake.

avboivin commented 4 years ago

Hi @cheenamalhotra, I just tried uncommenting and rebooting and could reproduce the issue.

Uncommented this line from /etc/ssl/openssl.cnf ssl_conf = ssl_sect sudo reboot I get a connection pool error on my dotnetcore 3.1 apps. The 3.1 apps use EFcore 3 and microsoft.data.SqlClient 1.1.0 Dotnetcore 2.2 apps still work great and can connect to the DB

Commented the line from /etc/ssl/openssl.cnf again

ssl_conf = ssl_sect

sudo reboot Both apps work great and can now connect.

I've never used wireshark so if you can point me to a relevant tutorial I'd be inclined to try it but otherwise that's not something I'm willing to test right now.

Thanks for the quick response !

cheenamalhotra commented 4 years ago

You can always find online tutorials to use Wireshark, it's a bit tricky to get hands-on, but if you're not facing issues, you may not need to :)

iarovyi commented 4 years ago

Thanks. It worked for me by adding single line in dockerfile because with dockerfile there is no need for explicit reboot:

RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf

Example dockerfile:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base

WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["MyApp/MyApp.csproj", "MyApp/"]
RUN dotnet restore "MyApp/MyApp.csproj"
COPY . .
WORKDIR "/src/MyApp"
RUN dotnet build "MyApp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MyApp.csproj" -c Release -o /app/publish

FROM base AS final
RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "eVision.MyApp.dll"]
feizeikesi commented 4 years ago

Hi @cheenamalhotra, I could reproduce the issue in mssql 2008 r2, but don't reproduce the issue in mssql 2012

iarovyi commented 4 years ago

Hi @cheenamalhotra, I could reproduce the issue in mssql 2008 r2, but don't reproduce the issue in mssql 2012

I had this problem on RDS instance on AWS. Not sure what version is there.

cheenamalhotra commented 4 years ago

@feizeikesi Your SQL 2008 R2 server instance might not be updated to support TLS 1.2, please check details here: https://support.microsoft.com/en-ca/help/3135244/tls-1-2-support-for-microsoft-sql-server

@iarovyi Please review version of SQL Server in use and whether TLS 1.2 is enabled on server and server machine in order to connect from client.

lucastheisen commented 4 years ago

I am also hitting this very issue. The specifics of my circumstance are:

Client OS: Ubuntu 18.04 (WSL on Windows 10) Client Lib: Microsoft.Data.SqlClient 1.1.0 Server OS: Windows 2008 R2 SQL Server: Standard Edition 10.51.2500.0 (2008)

It fails exactly the same as the original report:

failed: Connection Timeout Expired.  The timeout period elapsed during the post-login phase.  The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections.  The duration spent while attempting to connect to this server was - [Pre-Login] initialization=30; handshake=408; [Login] initialization=2; authentication=11; [Post-Login] complete=14016;

Using a windows build of the exact same source from the exact same server does not hit this error. Using the linux build of this source against a SqlServer 2016 instance also does not hit this error.

Given that this appears to be linux + SqlServer 2008 only, and the driver is not going to get updated for issues with 2008 due to EOL status, we will have to find a different workaround...

koryukov commented 4 years ago

We solved the same issue for SQL Sever 2008 R2 by installing SP3.

alercunha commented 4 years ago

Thanks. It worked for me by adding single line in dockerfile because with dockerfile there is no need for explicit reboot:

RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf

Example dockerfile:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base

WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["MyApp/MyApp.csproj", "MyApp/"]
RUN dotnet restore "MyApp/MyApp.csproj"
COPY . .
WORKDIR "/src/MyApp"
RUN dotnet build "MyApp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MyApp.csproj" -c Release -o /app/publish

FROM base AS final
RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "eVision.MyApp.dll"]

@iarovyi Thanks for this. I just lost several days trying to figure out what I was doing wrong and then took me a while to find this thread.

@cheenamalhotra I had this issue on MS SQL 2012 running exactly same stack as @iarovyi.

If you need more details let me know.

nayanishdamania commented 4 years ago

What is the Connection Timeout given? If the Connection Timeout is 0 then try to change it to 30.

Try to update SQL Server 2008 to SQL Server 2008 R2 (SP3) - 10.50.6000.34 (X64)

connorearl commented 4 years ago

I'm experiencing the same issue using Microsoft.Data.SqlClient 1.1.1 connecting to SQL Server 2016. The sed command fixes it as a workaround for now, but it seems to be affecting newer SQL Server versions as well

albeserra commented 4 years ago

Dear all, I get same error trying to connect to a SQL SERVER 2008. Code works like a charm in windows and mac (with dotnet for mac). But I get an error on the ubuntu docker container.

Do you have any advice? thanks

Connecting to SQL Server ... Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: TCP Provider, error: 0 - Success) at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose) at Microsoft.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error) at Microsoft.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync() at Microsoft.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket() at Microsoft.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer() at Microsoft.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value) at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool, SqlAuthenticationProviderManager sqlAuthProviderManager) at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) at Microsoft.Data.SqlClient.SqlConnection.Open() at WebApplication4.Controllers.WeatherForecastController.Get() in /src/WebApplication4/Controllers/WeatherForecastController.cs:line 66 ClientConnectionId:c57a691e-9396-4b55-9983-ab20679e9a26

jean-lourenco commented 4 years ago

I have the same "hanging sql server connection" problem with this setup:

Before applying the SP3 , the error was about failures around TLS handshake. After SP3 was installed this error ceased, but now the connections just hangs foverer.

I've tried changing the base images, but all of the dotnet 3.1 images have the same problem. Also I tried the SECLEVEL and MinTLSSupportedVersion scripts on the Docker imagem construction, no luck either.

This same app can connect normally on Windows, and the container can connect normally on SQL Server 2014 (SP3).

cheenamalhotra commented 4 years ago

@jean-lourenco

Could you try removing the SECLEVEL scripts and let driver connect with TLS 1.2 if your server has all the updates?

jean-lourenco commented 4 years ago

@jean-lourenco

Could you try removing the SECLEVEL scripts and let driver connect with TLS 1.2 if your server has all the updates?

@cheenamalhotra I've tried that too, didn't work.

rdagumampan commented 4 years ago

@albeserra have you managed to resolved this case? We also had this issue on service running on container.

RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf

May i what does this line means? What does it do? TIA

rdagumampan commented 4 years ago

Hi all,

Updating the CA certificates in the base image of container have solve this for our case. See docker file below. I tried many options including @albeserra suggestions and I have remove many things and trimmed to this only command and it seems to what have resolved our case.

FROM mcr.microsoft.com/dotnet/core/runtime:3.1

...
...

RUN update-ca-certificates

...
...

Background:

jean-lourenco commented 4 years ago

I've tried changing the base images, but all of the dotnet 3.1 images have the same problem. Also I tried the SECLEVEL and MinTLSSupportedVersion scripts on the Docker imagem construction, no luck either.

After some days I tried this again and managed to get the container working with the @iarovyi sugestion. Idk what I was doing wrong previously, probably not building the container image correctly.

RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf

May i what does this line means? What does it do? TIA

@rdagumampan It comments out the ssl_conf = ssl_sect line of the open ssl config file.

albeserra commented 4 years ago

I've tried changing the base images, but all of the dotnet 3.1 images have the same problem. Also I tried the SECLEVEL and MinTLSSupportedVersion scripts on the Docker imagem construction, no luck either.

After some days I tried this again and managed to get the container working with the @albeserra sugestion. Idk what I was doing wrong previously, probably not build the container image correctly.

@albeserra have you managed to resolved this case? We also had this issue on service running on container.

RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf

May i what does this line means? What does it do? TIA

@rdagumampan It comments out the ssl_conf = ssl_sect line of the open ssl config file.

Hi, no I didn't solve it. We abandoned the idea to build a .NET image for a linux container :( how did you solve it?

kolesso-programist commented 4 years ago

I'm using Microsoft.Data.SqlClient 1.0.19128.1-preview on Linux RHEL 6 to connect to SQLServer running on Windows. This is my connection string: string connetionString Server="SomeComputer\SQLIntegTest,61245;Database=db4;uid=user;pwd=password;Trusted_Connection=No"

with this code:

SqlConnection cnn = new SqlConnection(connetionString); cnn.Open()

I get the following error. The same code works on windows. Any help would be appreciated.

Unhandled Exception: Microsoft.Data.SqlClient.SqlException: Connection Timeout Expired. The timeout period elapsed during the post-login phase. The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=118; handshake=271; [Login] initialization=11; authentication=14; [Post-Login] complete=14041; ---> System.ComponentModel.Win32Exception: Unknown error 258 --- End of inner exception stack trace --- at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken) at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) at Microsoft.Data.SqlClient.SqlConnection.Open() Abort (core dumped)

@sjc1832 did you solve this issue ? could you provide details please

kolesso-programist commented 4 years ago

@mgbee8 Same with us. asp.net core 3 docker container and MS SQL 2016 (13.0.5216.0) on AWS RDS. However, this happens only in Test environment.

An exception occurred while iterating over the results of a query for context type 'IdentityServer4.EntityFramework.DbContexts.PersistedGrantDbContext'. Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception (258): Unknown error 258 at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) at

Maybe there is some relation to new client.

@voroninp did you solve this issue ? could you provide details please

voroninp commented 4 years ago

@kolesso-programist Alas, I quit that company, so cannot add more details on whether issue was resolved or not.

emanuelmaha commented 4 years ago

Thanks. It worked for me by adding single line in dockerfile because with dockerfile there is no need for explicit reboot:

RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf

Example dockerfile:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base

WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["MyApp/MyApp.csproj", "MyApp/"]
RUN dotnet restore "MyApp/MyApp.csproj"
COPY . .
WORKDIR "/src/MyApp"
RUN dotnet build "MyApp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MyApp.csproj" -c Release -o /app/publish

FROM base AS final
RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "eVision.MyApp.dll"]

you made my day happier

cheenamalhotra commented 4 years ago

Hi everyone, since #577 fixes the hang issue and will be released with Microsoft.Data.SqlClient v2.0.0, we will close the issue. This fix will also be backported to System.Data.SqlClient soon.

The recommended solution for anyone facing "End of Stream reached" exception in future is to verify target SQL Server supports TLS 1.2+ and server certificates are encrypted with SHA256+.

There are workarounds to switch back to lower TLS version if needed, as discussed above, but starting next release (v2.0), applications will also receive a warning as implemented in #591 if a lower insecure TLS version was negotiated with server, since these versions are not recommended for client applications. It includes raising warning for TLS v1.0 and TLS 1.1 protocols.

pandu-malik commented 1 year ago

Thanks. It worked for me by adding single line in dockerfile because with dockerfile there is no need for explicit reboot:

RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf

Example dockerfile:

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base

WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["MyApp/MyApp.csproj", "MyApp/"]
RUN dotnet restore "MyApp/MyApp.csproj"
COPY . .
WORKDIR "/src/MyApp"
RUN dotnet build "MyApp.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MyApp.csproj" -c Release -o /app/publish

FROM base AS final
RUN sed -i '/^ssl_conf = ssl_sect$/s/^/#/' /etc/ssl/openssl.cnf
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "eVision.MyApp.dll"]

Thanks a lot man, you save alot of my 3 days of struggling