runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Socket.Select() method doesn't work correctly in linux.

Open sirentek opened this issue 11 years ago • 35 comments

I use linux mint mate 17.2 which is ubuntu and debian based. I cannot connect to Ngpsql database from Linux client. But I can connect from Windows client.

Because: After the following line is called =>Socket.Select(null, write, error, perIpTimeout);

In Linux: The list write doesn't have any elements. As a result it enters the if (!write.Any()) block and creates "Timeout exception" there.

In Windows: The list write has the element. It works.

Here is a sample code to produce it. It is a console application that works on CoreClr.

// Program.cs
using System;
// using Npgsql;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;

namespace Sample
{
    public class Program
    {
        public void Main()
        {
            Console.WriteLine("App started..");

            string Host = "192.168.1.72";
            int Port = 5432;

            int perIpTimeout = -1;
            var ips = Dns.GetHostAddressesAsync(Host).Result;
            var ep = new IPEndPoint(ips[0], Port);
            var socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            {
                Blocking = false
            };


            try
            {
                try
                {
                    socket.Connect(ep);
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode != SocketError.WouldBlock)
                    {
                        throw;
                    }
                }
                var write = new List<Socket> { socket };
                var error = new List<Socket> { socket };
                Socket.Select(null, write, error, perIpTimeout);
                var errorCode = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error);
                if (errorCode != 0)
                {
                    throw new SocketException((int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error));
                }
                if (!write.Any())
                {
            // When it is Linux, it will enter this block here!
                    Console.WriteLine(
                        $"Timeout after {new TimeSpan(perIpTimeout * 10).TotalSeconds} seconds when connecting to {ips[0]}");
                    try { socket.Dispose(); }
                    catch
                    {
                        // ignored
                    }

                    // if i == 0
                    Console.WriteLine("i==0 exception");
                    throw new TimeoutException();

                    // continue;
                }
                socket.Blocking = true;

                return;
            }
            catch (TimeoutException) { throw; }
            catch
            {
                try { socket.Dispose(); }
                catch
                {
                    // ignored
                }

                Console.WriteLine("Failed to connect to " + ips[0]);

                // if (i == 0)

                Console.WriteLine("i==0 exception 2");
                throw;

            }
        }
    }

    // TODO: Remove. Will be fixed in the next release of EF.
    public class Startup
    {
        public void Configure() { }
    }
}

sirentek avatar Nov 22 '15 01:11 sirentek

@stephentoub @pgavlin PTAL

davidsh avatar Nov 22 '15 01:11 davidsh

Here is an other application which makes the stack trace more clear:

           try
            {
                try
                {
                    socket.Connect(ep);
                }
                catch (SocketException e)
                {
                    => The socket exception is catched here!

                    Console.WriteLine("Excpetion Message=" + e.Message);
                    Console.WriteLine("Excpetion Stack=" + e.StackTrace);

                    Console.WriteLine("Socket Error Code=" + e.SocketErrorCode.ToString());

                    if (e.SocketErrorCode != SocketError.WouldBlock)
                    {
                        throw;
                    }
                }
                var write = new List<Socket> { socket };
                var error = new List<Socket> { socket };
                Socket.Select(null, write, error, perIpTimeout);
                var errorCode = (int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error);
                if (errorCode != 0)
                {
                    Console.WriteLine("error code is not zero!");
                    throw new SocketException((int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error));
                }
                if (!write.Any())
                {
                    Console.WriteLine(
                        $"Timeout after {new TimeSpan(perIpTimeout * 10).TotalSeconds} seconds when connecting to {ips[0]}");
                    try { socket.Dispose(); }
                    catch
                    {
                        // ignored
                    }

                    // if i == 0
                    Console.WriteLine("i==0 exception");
                    throw new TimeoutException();

                    // continue;
                }
                socket.Blocking = true;

                return;
            }
            catch (TimeoutException) { throw; }
            catch
            {
                try { socket.Dispose(); }
                catch
                {
                    // ignored
                }

                Console.WriteLine("Failed to connect to " + ips[0]);

                // if (i == 0)

                Console.WriteLine("i==0 exception 2");
                throw;

            }

Here is my output from the above program:

Excpetion Message=Unknown error 10035 Excpetion Stack= at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.Connect(EndPoint remoteEP) at SirenTek.Program.Main(String[] args) Socket Error Code=WouldBlock Timeout after -1E-06 seconds when connecting to 192.168.1.72 i==0 exception System.TimeoutException: The operation has timed out.

sirentek avatar Nov 23 '15 19:11 sirentek

Socket.DoConnect method creates an exception. That is why Socket.Select() method behaves differently in linux.

sirentek avatar Nov 23 '15 19:11 sirentek

A fix is in progress. FWIW, the exception above is expected and is not related to the later failure. The later failure is due to broken code that translates between CoreFX data structures and platform data structures.

pgavlin avatar Nov 23 '15 19:11 pgavlin

@pgavlin Thank you for the detailed information. Do you think it will take much time to fix it ? (much time is equal to 1 month for me.) I am excited to see a fix is going on!

sirentek avatar Nov 23 '15 20:11 sirentek

There should be a fix in our master branch today or tomorrow. I am not sure exactly how long it will take to propagate to the NuGet feeds once it's checked in--perhaps @joshfree can comment on that.

pgavlin avatar Nov 23 '15 20:11 pgavlin

I am not sure exactly how long it will take to propagate to the NuGet feeds once it's checked in

Nightly builds out of master should show up at https://www.myget.org/gallery/dotnet-core the next morning.

stephentoub avatar Nov 23 '15 20:11 stephentoub

RC2 daily builds are at https://myget.org/gallery/dotnet-core as @stephentoub said above. We'll only be pushing new bits to nuget.org for an RC1-servicing event (think really bad blocking bug for RC1 adopters) or when RC2 ships early next year.

joshfree avatar Nov 23 '15 20:11 joshfree

These are quite good news. Postgresql is the only db that has provider for ef and which works under linux. This makes the fix very important for me and probably for others. Many thanks and kind regards!

sirentek avatar Nov 23 '15 21:11 sirentek

I have tested System.Net.Sockets -Version 4.1.0-rc2-23523 from https://www.myget.org/gallery/dotnet-core in linux. I got the same errors again. I think this version doesn't include the fix. I am looking forward to see the newer version.

sirentek avatar Nov 24 '15 11:11 sirentek

@sirentek, Pat's fix hasn't gone in yet. This issue will be updated when it does, so you don't need to check in the meantime.

stephentoub avatar Nov 24 '15 12:11 stephentoub

Closed by dotnet/corefx#4652.

pgavlin avatar Nov 30 '15 17:11 pgavlin

In case anyone comes here and is having trouble with this, I've built a new System.Native.so which you may find helpful. It's built from the tree as of rc1-update1, so it should be compatible with the rest of that release, but it also includes this one patch. You can download it from http://tmp.chown.org.uk/System.Native.so and you should install it in ~/.dnx/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update1/bin .

I'm running 64bit Ubuntu Trusty. If you have a different system I doubt this file will work, and you'll probably have to build it yourself.

With this fix, the Postgres driver and EntityFramework7.Npgsql work as expected, which is great news.

PeteX avatar Dec 17 '15 17:12 PeteX

That's great @PeteX, thanks!

roji avatar Dec 17 '15 17:12 roji

@PeteX I have installed your System.Native library in my OS (Linux Mint 17.2 Mate). Although It didn't work for me, I appreciate your work.

sirentek avatar Dec 18 '15 20:12 sirentek

Thanks @PeteX, It works perfect.

rodrigo-a-moreno avatar Dec 28 '15 16:12 rodrigo-a-moreno

@freakZoid How did you have it worked ? You just copy-pasted the System.Native.so file to your ~/.dnx/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update1/bin directory and that was all ??

sirentek avatar Jan 01 '16 20:01 sirentek

@sirentek I have replaced file and after reboot It works perfect.

Rembel avatar Jan 02 '16 08:01 Rembel

@Rembel thanks for the reply. I tried again after reboot and I still have the same exceptions mentioned above.

sirentek avatar Jan 02 '16 08:01 sirentek

@PeteX , thank you so much for this! It works. My app can talk to AWS RDS PostgreSQL!

I take it you have submitted a corefx pull request with these changes :)

Anyone ( @sirentek ) wanting to use it can just add the file to your project root and then use docker COPY like this: COPY ./System.Native.so /opt/DNX_BRANCH/runtimes/dnx-coreclr-linux-x64.1.0.0-rc1-update1/bin

Be sure and also have these in your project.json or else this new file from Pete won't help at all since there are really several problems with getting a .NET Core (non-Mono) app using EF7 + NpgSql EF7 provider working

"runtime.linux.System.Net.NetworkInformation": "4.1.0-beta-23516",
"runtime.unix.System.Net.Security": "4.0.0-beta-23516"

I was told some magic addition to project.json would help resolve correct System.Net.* files

"Microsoft.NETCore.Platforms": "1.0.1-beta-23516"

but it did NOT, so you can exclude this.

I have even tried to dnu restore --runtime coreclr50 -s https://www.myget.org/F/aspnetvnext/api/v2/ -f https://www.nuget.org/api/v2/ (restoring from RC2 feed) and dnu build to --framework dnxcore50 to no avail so don't bother trying this.

Hope this all gets ironed out soon or in RC2 and does not fall through the cracks.

thmulvany avatar Jan 07 '16 05:01 thmulvany