Skip to content

Add API to intercept socket.close() #76219

Closed

Description

@1st1
BPO 32038
Nosy @gvanrossum, @pitrou, @vstinner, @asvetlov, @bdarnell, @1st1

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields:

assignee = None
closed_at = <Date 2018-05-28.19:58:25.712>
created_at = <Date 2017-11-15.19:00:27.020>
labels = ['type-feature', '3.7', 'expert-IO', 'expert-asyncio']
title = 'Add API to intercept socket.close()'
updated_at = <Date 2018-05-28.19:58:25.711>
user = 'https://github.com/1st1'

bugs.python.org fields:

activity = <Date 2018-05-28.19:58:25.711>
actor = 'yselivanov'
assignee = 'none'
closed = True
closed_date = <Date 2018-05-28.19:58:25.712>
closer = 'yselivanov'
components = ['IO', 'asyncio']
creation = <Date 2017-11-15.19:00:27.020>
creator = 'yselivanov'
dependencies = []
files = []
hgrepos = []
issue_num = 32038
keywords = []
message_count = 21.0
messages = ['306298', '306299', '306300', '306301', '306335', '306368', '306370', '306372', '306373', '306375', '306378', '306379', '306380', '306383', '306384', '306385', '306386', '306388', '306391', '306392', '317910']
nosy_count = 6.0
nosy_names = ['gvanrossum', 'pitrou', 'vstinner', 'asvetlov', 'Ben.Darnell', 'yselivanov']
pr_nums = []
priority = 'normal'
resolution = 'rejected'
stage = 'resolved'
status = 'closed'
superseder = None
type = 'enhancement'
url = 'https://bugs.python.org/issue32038'
versions = ['Python 3.7']

Activity

  1. 1st1 commented on Nov 15, 2017

    @1st1
    MemberAuthor

    asyncio has a few APIs that accept a Python socket object: loop.sock_recv(), loop.sock_accept() etc.

    asyncio (and event loops such as uvloop) expect that it controls the socket for the duration of the call. However, it cannot prevent the socket object from being closing *while* it is working with it:

        loop = asyncio.get_event_loop()
        sock = socket.socket()
        sock.connect(('google.com', 80))
        sock.setblocking(0)
        f = loop.sock_recv(sock, 100)
        sock.close()
        await f

    The above snippet makes asyncio to forever try to read from 'sock' (resource leak). uvloop simply segfaults (at least on Linux) because libuv assumes that sockets can't be closed while it's working with them.

    Same problem exists when a user calls loop.create_server(sock=sock) and later manually calls sock.close().

    My proposal is to add a new API: socket.register_close(callback). callback will be called whenever a socket object is about to be closed.

    This will enable asyncio and uvloop to detect when sockets they are working with are about to be closed and to either raise an error, log a debug line, or/and to stop polling the socket.

    See also: MagicStack/uvloop#100

  2. pitrou commented on Nov 15, 2017

    @pitrou
    Member

    Why not instead add loop.sock_close()?

  3. 1st1 commented on Nov 15, 2017

    @1st1
    MemberAuthor

    Why not instead add loop.sock_close()?

    It wouldn't help if the program calls socket.close() somewhere. This can happen easily in big code bases.

    Ideally (at least I think so) we need to provide a guarantee that the socket object can't be closed at all (or be closed in a controlled manner) if it's being operated by asyncio/event-loop.

  4. pitrou commented on Nov 15, 2017

    @pitrou
    Member

    Ok, that sounds reasonable to me. Also cc'ing Ben Darnell (maintainer of Tornado) in case he wants to chime in.

  5. bdarnell commented on Nov 16, 2017

    bdarnellmannequin
    Mannequin

    It's worse than a resource leak - the same file descriptor number could be reused for a different file/socket, and then depending on the selector in use, you could see the data from a completely different connection.

    I did see a bug like this years ago (in libcurl), although it's not a common problem. I'd use the proposed hook if it existed, but it seems like an intrusive solution to a rare issue.

  6. 1st1 commented on Nov 16, 2017

    @1st1
    MemberAuthor

    It's worse than a resource leak - the same file descriptor number could be reused for a different file/socket, and then depending on the selector in use, you could see the data from a completely different connection.

    I actually debugged a bug like this in asyncio code once. Took me quite a bit of time to figure it out.

    I did see a bug like this years ago (in libcurl), although it's not a common problem. I'd use the proposed hook if it existed, but it seems like an intrusive solution to a rare issue.

    I don't think the proposed solution is too intrusive. If we don't like the "set a callback to intercept all socket.close()" idea, we can change it to: "add socket.add_close_callback() method to the socket object."

  7. vstinner commented on Nov 16, 2017

    @vstinner
    Member

    The socket.socket (Python type) has a private _io_refs counter. close() does nothing until _io_refs reachs zero.

    Maybe we can develop an API to temporary increase the _io_refs counter to prevent a real close?

    Pseudo-code:

    @contextlib.contextmanager
    def dont_close_socket(sock):
        assert not sock._closed
        sock._io_refs += 1
        try:
            yield sock
        finally:
            sock._io_refs -= 1

    It may be a context manager or a new object. It would probably be better to put in the socket.socke type, since it uses private attributes.

  8. 1st1 commented on Nov 16, 2017

    @1st1
    MemberAuthor

    The socket.socket (Python type) has a private _io_refs counter. close() does nothing until _io_refs reachs zero.

    I didn't know about this. Looks like I can use '_io_refs' to fix some problems in uvloop, thanks Victor!

    The only problem with '_io_refs' and dont_close_socket approach is that the original intent to close the socket is "lost". Consider this example:

      fut = loop.sock_recv(sock)
      sock.close()
      await fut

    Ideally, I'd expect sock to be closed right after await fut is completed. One way to make that possible is to initialize socket object with 'self._io_refs = 1', not 0. Whenever it goes to 0, the socket gets closed. This is a slight change to the existing machinery, but it would make sock.close() more predictable.

  9. vstinner commented on Nov 16, 2017

    @vstinner
    Member

    From my example: "finally: sock._io_refs -= 1"

    Oh, sock._decref_socketios() must be uesd here to really close the socket if it was closed in the meanwhile:

        def _decref_socketios(self):
            if self._io_refs > 0:
                self._io_refs -= 1
            if self._closed:
                self.close()
  10. 1st1 commented on Nov 16, 2017

    @1st1
    MemberAuthor

    Oh, sock._decref_socketios() must be uesd here to really close the socket if it was closed in the meanwhile:

    There's also 'sock._closed' attribute that sock.close() and sock. _decref_socketios() interact with.. Alright, let me play with this in uvloop. So far it looks like we don't need any new APIs :)

  11. pitrou commented on Nov 16, 2017

    @pitrou
    Member

    Hmm... _decref_socketios() is not really a public API. I think it would be nice to have an official way to deal with this, and a socket close callback sounds reasonable to me.

  12. vstinner commented on Nov 16, 2017

    @vstinner
    Member

    Hmm... _decref_socketios() is not really a public API. I think it would be nice to have an official way to deal with this, and a socket close callback sounds reasonable to me.

    I dislike the idea of an event when a socket is closed. It doesn't prevent a crash if you are using the socket with the GIL released.

    I prefer to "hold" the socket while using it.

  13. 1st1 commented on Nov 16, 2017

    @1st1
    MemberAuthor

    Hmm... _decref_socketios() is not really a public API. I think it would be nice to have an official way to deal with this, and a socket close callback sounds reasonable to me.

    We can just make it public (after some renames) :) My first idea was to add a refcounting API to sockets, I just didn't know it's already there (I assumed that socketmodule.c implements the actual 'socket' object, and never even looked in socket.py module).

    I'll experiment with this stuff in asyncio/uvloop and report back to this issue.

  14. gvanrossum commented on Nov 16, 2017

    @gvanrossum
    Member

    Perhaps you can just dup() the socket? That's what the ref counter is for
    IIRC.

  15. vstinner commented on Nov 16, 2017

    @vstinner
    Member

    Perhaps you can just dup() the socket? That's what the ref counter is for IIRC.

    Sure. That's another option.

    But for asyncio with a lot of concurrent users, I'm not sure that it's ok to create a temporary file descriptor, since there is a risk of hitting the maximum number of open file descriptors :-(

    Depending on the platform and the event loop implementation, the limit may be low.

  16. 1st1 commented on Nov 16, 2017

    @1st1
    MemberAuthor

    Perhaps you can just dup() the socket? That's what the ref counter is for IIRC.

    I already dup them for loop.create_server(sock=sock) and loop.create_connection(sock=sock) cases. Duping for sock_recv & friends will add too much overhead (they are relatively short operations). Another argument against duping is that the number of open FDs is a limited OS resource.

    So far Victor's idea of using '_io_refs' sounds like a perfect fit for both asyncio and uvloop. After all, asyncio use case is very similar to socket.makefile() -- keep the socket object alive while another API relies on it.

  17. gvanrossum commented on Nov 16, 2017

    @gvanrossum
    Member

    OK, then maybe socket objects should get a dup() method that just
    increments the ref counter, and that would be the public API you're looking
    for?

  18. 1st1 commented on Nov 16, 2017

    @1st1
    MemberAuthor

    OK, then maybe socket objects should get a dup() method that just
    increments the ref counter, and that would be the public API you're looking
    for?

    "dup()" returns a new socket object, but here we only want to protect the original one.

    Maybe just 'sock.inc_io_ref()' and 'sock.dec_io_ref()'? OTOH using the current private socket API in asyncio and uvloop doesn't really scare me as long as it works, so keeping the status quo is also OK.

  19. bdarnell commented on Nov 16, 2017

    bdarnellmannequin
    Mannequin

    Note that a guard on socket objects can only solve part of the problem: in the case where i've seen this bug, it was with raw file descriptors from libcurl, and there's nothing python can do about that because there are no (python) socket objects.

  20. 1st1 commented on Nov 16, 2017

    @1st1
    MemberAuthor

    Note that a guard on socket objects can only solve part of the problem: in the case where i've seen this bug, it was with raw file descriptors from libcurl, and there's nothing python can do about that because there are no (python) socket objects.

    Well, in this case 'dup' is the only option.

  21. 1st1 commented on May 28, 2018

    @1st1
    MemberAuthor

    Closing this one. Using private socket.socket APIs works fine for uvloop/asyncio.

  22. added
    type-feature
    on May 28, 2018
  23. transferred this issue fromon Apr 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.7 (EOL)topic-IOtopic-asynciotype-feature

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions