Skip to content

add sniff sockopts - #804

Merged
njsmith merged 8 commits into
python-trio:masterfrom
dd-dent:issue_251
Feb 11, 2019
Merged

njsmith merged 8 commits into
python-trio:masterfrom
dd-dent:issue_251

Conversation

@dd-dent

@dd-dent dd-dent commented Dec 15, 2018 •

Copy link
Copy Markdown
Contributor

WIP as _socket.fromfd doesn't work properly.
Also, shouldn't work on mac...

Fixes: #251

@njsmith njsmith left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Made a few comments below.

I don't understand why the tests are failing :-). For some reason it's consistently getting the type as SOCK_STREAM when it should be SOCK_DGRAM... do the tests pass for you locally? If they're only failing on Travis/Appveyor, then one hack is to add a bunch of print calls to trace what it's doing, and pushing that temporarily, so you can see what's happening in the logs. (Then of course you take the print calls out again before we merge :-).)

You'll also want to eventually add a newsfragment

Comment thread trio/_socket.py Resolved
Comment thread trio/_socket.py Resolved
Comment thread trio/tests/test_socket.py Outdated
for family_type in ['ipv4_tcp', 'ipv4_udp', 'ipv6_tcp', 'ipv6_udp']:
family, type = family_type.split('_')
family = stdlib_socket.AF_INET if family == 'ipv4' else stdlib_socket.AF_INET6
type = stdlib_socket.SOCK_STREAM if type == 'tcp' else stdlib_socket.SOCK_DGRAM

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe it would be nicer to write this like

for family in [stdlib_socket.AF_INET, stdlib_socket.AF_INET6]:
    for type in [stdlib_socket.SOCK_STREAM, stdlib_socket.SOCK_DGRAM]:
        ...

?

I guess it'd also be good to test AF_UNIX on systems where it's defined.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed it, did a bit of wiggling to avoid over indentation/yapf butchering my code...

@dd-dent

dd-dent commented Dec 18, 2018

Copy link
Copy Markdown
Contributor Author

Just so it's clear, I haven't yet abandoned this, just incredibly busy with work and RL...
Will probably have time to work on it this weekend.

@njsmith

njsmith commented Dec 19, 2018

Copy link
Copy Markdown
Member

No worries, work and RL definitely come first :-)

@codecov

codecov Bot commented Dec 28, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #804 into master will decrease coverage by 0.01%.
The diff coverage is 100%.

@@            Coverage Diff             @@
##           master     #804      +/-   ##
==========================================
- Coverage    99.4%   99.39%   -0.02%     
==========================================
  Files         102      102              
  Lines       12717    12461     -256     
  Branches      928      915      -13     
==========================================
- Hits        12641    12385     -256     
  Misses         56       56              
  Partials       20       20
Impacted Files Coverage Δ
trio/tests/test_socket.py 100% <100%> (ø) ⬆️
trio/_socket.py 99.18% <100%> (+0.06%) ⬆️
trio/_signals.py 100% <0%> (ø) ⬆️
trio/tests/test_sync.py 100% <0%> (ø) ⬆️
trio/_sync.py 100% <0%> (ø) ⬆️
trio/__init__.py 100% <0%> (ø) ⬆️
trio/tests/test_signals.py 100% <0%> (ø) ⬆️

@dd-dent

dd-dent commented Dec 28, 2018

Copy link
Copy Markdown
Contributor Author

RE newsfragments, is this considered a feature? Seems like a bit of a stretch, and I'm pretty sure this isn't a bugfix...
So I'm thinking misc?

@njsmith

njsmith commented Dec 29, 2018

Copy link
Copy Markdown
Member

(FYI: I edited the initial comment to include a Fixes: #251 note. This does two things: makes it easy to get from this to the issue and vice-versa, and it makes it so that if this PR is merged, then github will automatically mark that issue as closed, which is something we tend to forget to do otherwise :-).)

I dug into this a bit more on Windows. Apparently the answer is that I was working from incorrect information, and it isn't expected to work on Windows! Also AFAICT it can't work on Windows – even the getsockname hack doesn't work on Windows. So we should definitely skip the test on Windows. I'm glad we tried though, because otherwise we would have kept walking around with the wrong idea about how this worked! Validating assumptions is good.

Speaking of validating assumptions, it looks like the macOS tests did fail exactly the way we expected. So... that's nice to have confirmed, I guess? And, squinting at this output:

>           assert tsocket_socket.family == socket.family
E           AssertionError: assert <AddressFamily.AF_INET: 2> == <AddressFamily.AF_INET6: 30>
E            +  where <AddressFamily.AF_INET: 2> = <trio.socket.socket fd=27, family=AddressFamily.AF_INET, type=SocketKind.SOCK_DGRAM, proto=0, laddr=('::e82b:b90e:100:0', 0, 0, 1)>.family
E            +  and   <AddressFamily.AF_INET6: 30> = <socket.socket fd=27, family=AddressFamily.AF_INET6, type=SocketKind.SOCK_DGRAM, proto=0, laddr=('::', 0, 0, 0)>.family

I notice that the tsocket_socket's repr includes laddr=('::e82b:b90e:100:0', 0, 0, 1), which is an AF_INET6 address, even though the socket object has family=AF_INET. This suggests to me that Python's getsockname does detect the family correctly, even if it doesn't match the family field in the socket object. Which suggests that if we do implement the getsockname hack, then it will work on macOS.

OTOH AFAICT there's no hope of getting type autodetection working on macOS. Oh well.

Up to you whether you want to skip the test on macOS and leave it at that for now, or implement the getsockname hack and test just family on macOS.

RE newsfragments, is this considered a feature? Seems like a bit of a stretch, and I'm pretty sure this isn't a bugfix...

I think calling it a feature is fine. Before you had to specify manually, now you don't, yay. It's not the biggest feature, but who's counting?

@python-trio python-trio deleted a comment from codecov Bot Jan 17, 2019
@njsmith

njsmith commented Jan 17, 2019

Copy link
Copy Markdown
Member

I finally had a chance to dig into this a bit tonight.

It's extremely weird.

Running with 3.7 on windows, I do always get a failure on that test. The error happens when _sniff_sockopts_for_fileno tries to make its temporary socket object, by doing sockobj = _stdlib_socket.socket(fileno=fileno) – for some reason, on py37 on Windows only, this fails consistently in this test. BUT, it works if I try simpler things at the REPL, like fd = socket.socket().detach(); socket.socket(fileno=fd). Super weird!

I guess there is a workaround: make that line be

sockobj = _stdlib_socket.socket(family, type, proto, fileno=fileno)

(I.e., passing in the "initial guesses" that _sniff_sockopts_for_fileno receives.)

I think there's a Python bug here that we really ought to isolate and report though...

@njsmith

njsmith commented Jan 17, 2019

Copy link
Copy Markdown
Member

@tiran I know you made some changes to the behavior of socket.socket(fileno=fileno) in 3.7. This is a shot in the dark, but have you had any reports of strange failures on Windows? (See previous comment in this thread.)

@tiran

tiran commented Jan 17, 2019

Copy link
Copy Markdown

I remember an issue with proto. It was always 0 on Windows.

@dd-dent

dd-dent commented Jan 17, 2019 •

Copy link
Copy Markdown
Contributor Author

@njsmith A couple of notes:
This issue appeared following a rebase, but I'm uncertain if the rebase had anything to do with this (IIRC, the PR was broken in some other way prior to rebasing).
RE making this work, I can possibly bypass the issue with a _sys.platform == "linux" check prior to calling _sniff_sockopts_for_fileno, although I hadn't encountered it anywhere else in trio, so I'll assume it's considered a bad practice?

@tiran

tiran commented Jan 17, 2019

Copy link
Copy Markdown

Aaah, there is another issue. On most platforms it is not possible to retrieve socket information from a new, unconfigured socket fd. The socket most either be connected to a peer or in listening mode. Linux is one of the few platforms that supports this for the majority of sockets.

@dd-dent

dd-dent commented Jan 17, 2019 •

Copy link
Copy Markdown
Contributor Author

@tiran So, by extension, one might say this feature is only applicable to linux?
Also, it's implied from what you're saying no all sockets can be 'sniffed', so how do I go about finding which subset of sockets are 'sniffable'?

@tiran

tiran commented Jan 17, 2019

Copy link
Copy Markdown

The behavior depends on the platform and platform version.

  • For connected sockets it should work on all platforms.
  • For unconnected sockets, you can only try and catch the error. I'm not aware of any API.

One more thing, AFAIK Windows doesn't have the concept of protocols. In my experiments, the protocol value was always 0.

@njsmith

njsmith commented Jan 17, 2019

Copy link
Copy Markdown
Member

@tiran Sorry, my question is much more specific :-).

As far as I can tell, calling socket with a fileno and no other arguments used to always return a socket object (possibly with some messed up metadata):

socket.socket(fileno=fileno)  # where 'fileno' is a valid socket descriptor

But starting in 3.7, on Windows only, it now sometimes raises this exception instead:

OSError: [WinError 10022] An invalid argument was supplied: 'family'

We don't yet understand what the condition is to trigger this; I can't reproduce it at the REPL. But our test suite triggers it 100% of the time, so there is something consistent about it :-).

The question was whether you have any thoughts on:

  • Where this error comes from
  • Whether it should be considered a regression in 3.7 (since this didn't error out in previous versions AFAICT)
  • Why this might be happening in our test suite but not the REPL

@dd-dent

dd-dent commented Jan 18, 2019

Copy link
Copy Markdown
Contributor Author

The relevant log section from appveyor:

================================== FAILURES ===================================
_________________________ test_custom_socket_factory __________________________
    async def test_custom_socket_factory():
        class CustomSocketFactory:
            def socket(self, family, type, proto):
                return ("hi", family, type, proto)
    
        csf = CustomSocketFactory()
    
        assert tsocket.set_custom_socket_factory(csf) is None
    
        assert tsocket.socket() == ("hi", tsocket.AF_INET, tsocket.SOCK_STREAM, 0)
        assert tsocket.socket(1, 2, 3) == ("hi", 1, 2, 3)
    
        # socket with fileno= doesn't call our custom method
        fd = stdlib_socket.socket().detach()
>       wrapped = tsocket.socket(fileno=fd)
..\trio\tests\test_socket.py:840: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\trio\_socket.py:294: in socket
    family, type, proto, fileno
..\trio\_socket.py:307: in _sniff_sockopts_for_fileno
    sockobj = _stdlib_socket.socket(fileno=fileno)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <socket.socket fd=-1, family=AddressFamily.AF_UNSPEC, type=0, proto=0>
family = -1, type = -1, proto = -1, fileno = 1324
    def __init__(self, family=-1, type=-1, proto=-1, fileno=None):
        # For user code address family and type values are IntEnum members, but
        # for the underlying _socket.socket they're just integers. The
        # constructor of _socket.socket converts the given argument to an
        # integer automatically.
        if fileno is None:
            if family == -1:
                family = AF_INET
            if type == -1:
                type = SOCK_STREAM
            if proto == -1:
                proto = 0
>       _socket.socket.__init__(self, family, type, proto, fileno)
E       OSError: [WinError 10022] An invalid argument was supplied: 'family'
C:\Python37\lib\socket.py:151: OSError

It seems like it has something to do with the cpython's _socket.socket init on windows, called originally with only an fd.
I'm now pushing a commit which both:

  1. Only runs the relevant test on linux.
  2. Only executes the _sniff_sockopts_for_fileno func on linux.

Hopefully will work, but somewhat ugly in my opinion...

@dd-dent

dd-dent commented Jan 24, 2019

Copy link
Copy Markdown
Contributor Author

@njsmith Sorry to pester you, as I'm sure there's more important stuff than this, but is there anything new about this perchance?

@dd-dent dd-dent closed this Jan 26, 2019
@dd-dent dd-dent reopened this Jan 26, 2019
@njsmith

njsmith commented Jan 27, 2019

Copy link
Copy Markdown
Member

Thanks for pestering :-).

The explicit check for linux is a bit ugly yeah :-/. It's possible there's no alternative. I still have no idea about this failure... I tried a bit more to track it down, and it seems to be coming directly from some Windows API, not anything inside Python.

What do you think about the idea upthread, of changing it so _sniff_sockopts_for_fileno does

sockobj = _stdlib_socket.socket(family, type, proto, fileno=fileno)

i.e., passes in whatever family/type/proto the user gave us? Rationale:

  1. In my tests this seemed to get the tests passing
  2. If we're on a system where we can't usefully sniff anything, then we're ultimately going to end up making that exact call anyway, later. So at least it isn't making anything worse...

@njsmith

njsmith commented Jan 28, 2019

Copy link
Copy Markdown
Member

Looks like this is now passing everywhere except Linux? Frustrating :-(

Michael Arad added 3 commits February 8, 2019 16:49
@njsmith

njsmith commented Feb 10, 2019

Copy link
Copy Markdown
Member

Oof, I'm sorry this was so painful! I guess there must be some nicer way to write it, but we've run into so many weird issues here that I'm not even sure how to find it... so maybe we should stick with this version that seems to work :-). I did edit your newsfragment; you can take a look and see if you like the new version. And thanks for your patience with this so-called "easy first issue"...

@dd-dent

dd-dent commented Feb 10, 2019

Copy link
Copy Markdown
Contributor Author

No need to feel sorry about anything, it's just what it is (bloody annoying at times).
Your version of the newsfragment is far superior to mine, so let's go with that one!

@njsmith
njsmith merged commit 7bba4ef into python-trio:master Feb 11, 2019
@njsmith

njsmith commented Feb 11, 2019

Copy link
Copy Markdown
Member

Okay, merged! 🎉 🎂 And, no pressure, but if you'd like to keep contributing then we'd love to have you, so I'm sending you a github invite now. You can read more about this in our contributing documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants