Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

net: add mechanism to wait for readability on a TCPConn #15735

Open
bradfitz opened this issue May 18, 2016 · 74 comments
Open

net: add mechanism to wait for readability on a TCPConn #15735

bradfitz opened this issue May 18, 2016 · 74 comments

Comments

@bradfitz
Copy link
Contributor

@bradfitz bradfitz commented May 18, 2016

EDIT: this proposal has shifted. See #15735 (comment) below.

Old:

The net/http package needs a way to wait for readability on a TCPConn without actually reading from it. (See #15224)

http://golang.org/cl/22031 added such a mechanism, making Read(0 bytes) do a wait for readability, followed by returning (0, nil). But maybe that is strange. Windows already works like that, though. (See new tests in that CL)

Reconsider this for Go 1.8.

Maybe we could add a new method to TCPConn instead, like WaitRead.

@bradfitz bradfitz added this to the Go1.8 milestone May 18, 2016
@bradfitz bradfitz self-assigned this May 18, 2016
@bradfitz
Copy link
Contributor Author

@bradfitz bradfitz commented May 18, 2016

@gopherbot
Copy link

@gopherbot gopherbot commented May 18, 2016

CL https://golang.org/cl/23227 mentions this issue.

gopherbot pushed a commit that referenced this issue May 19, 2016
Updates #15735

Change-Id: I42ab2345443bbaeaf935d683460fc2c941b7679c
Reviewed-on: https://go-review.googlesource.com/23227
Reviewed-by: Ian Lance Taylor <iant@golang.org>
gopherbot pushed a commit that referenced this issue May 19, 2016
Updates #15735.
Fixes #15741.

Change-Id: Ic4ad7e948e8c3ab5feffef89d7a37417f82722a1
Reviewed-on: https://go-review.googlesource.com/23199
Run-TryBot: Mikio Hara <mikioh.mikioh@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
@RalphCorderoy
Copy link

@RalphCorderoy RalphCorderoy commented May 20, 2016

read(2) with a count of zero may be used to detect errors. Linux man page confirms, as does POSIX's read(3p) here. Mentioning it in case it influences this subverting of a Read(0 bytes) not calling syscall.Read.

@bradfitz
Copy link
Contributor Author

@bradfitz bradfitz commented Oct 21, 2016

I found a way to do without this in net/http, so punting to Go 1.9.

@bradfitz bradfitz modified the milestones: Go1.9, Go1.8 Oct 21, 2016
@bradfitz
Copy link
Contributor Author

@bradfitz bradfitz commented Dec 12, 2016

Actually, the more I think about this, I don't even want my idle HTTP/RPC goroutines to stick around blocked in a read call. In addition to the array memory backed by the slice given to Read, the goroutine itself is ~4KB of wasted memory.

What I'd really like is a way to register a func() to run when my *net.TCPConn is readable (when a Read call wouldn't block). By analogy, I want the time.AfterFunc efficiency of running a func in a goroutine later, rather than running a goroutine just to block in a time.Sleep.

My new proposal is more like:

package net

// OnReadable runs f in a new goroutine when c is readable;
// that is, when a call to c.Read will not block.
func (c *TCPConn) OnReadable(f func()) {
   // ...
}

Yes, maybe this is getting dangerously into event-based programming land.

Or maybe just the name ("OnWhatever") is offensive. Maybe there's something better.

I would use this in http, http2, and grpc.

/cc @ianlancetaylor @rsc

@ianlancetaylor
Copy link
Contributor

@ianlancetaylor ianlancetaylor commented Dec 12, 2016

Sounds like you are getting close to #15021.

I'm worried that the existence of such a method will encourage people to start writing their code as callbacks rather than as straightforward goroutines.

@bradfitz
Copy link
Contributor Author

@bradfitz bradfitz commented Dec 12, 2016

Yeah. I'm conflicted. I see the benefits and the opportunity for overuse.

@dvyukov
Copy link
Member

@dvyukov dvyukov commented Jan 6, 2017

If we do OnReadable(f func()), won't we need to fork half of standard library for async style? Compress, io, tls, etc readers all assume blocking style and require a blocked goroutine.
I don't see any way to push something asynchronously into e.g. gzip.Reader. Does this mean that I have to choose between no blocked goroutine + my own gzip impl and blocked goroutine + std lib?

@dvyukov
Copy link
Member

@dvyukov dvyukov commented Jan 6, 2017

Re 0-sized reads.
It should work with level-triggered notifications, but netpoll uses epoll in edge-triggered mode (and kqueue iirc). I am concerned if cl/22031 works in more complex cases: waiting for already ready IO, double wait, wait without completely draining read buffer first, etc?

@bradfitz
Copy link
Contributor Author

@bradfitz bradfitz commented Jan 6, 2017

@dvyukov, no, we would only use OnReadable in very high-level places, like the http1 and http2 servers where we know the conn is expected to be idle for long periods of time. The rest of the code underneath would remain in the blocking style.

@dvyukov
Copy link
Member

@dvyukov dvyukov commented Jan 6, 2017

This looks like a half-measure. An http connection can halt in the middle of request...

@bradfitz
Copy link
Contributor Author

@bradfitz bradfitz commented Jan 6, 2017

@dvyukov, but not commonly. This would be an optimization for the common case.

@dvyukov
Copy link
Member

@dvyukov dvyukov commented Jan 7, 2017

An alternative interface can be to register a channel that will receive readiness notifications. The other camp wants this for packet-processing servers, and there starting a goroutine for every packet will be too expensive. However, if at the end you want a goroutine, then the channel will introduce unnecessary overhead.
Channel has a problem with overflow handling (netpoll can't block on send, on the other hand it is not OK to lose notifications).
For completeness, this API should also handle writes.

@DemiMarie
Copy link

@DemiMarie DemiMarie commented Jan 10, 2017

We need to make sure that this works with Windows IOCP as well.

@rsc
Copy link
Contributor

@rsc rsc commented Jan 10, 2017

Not obvious to me why the API has to handle writes. The thing about reads is that until the data is ready for reading, you can use the memory for other work. If you're waiting to write data, that memory is not reusable (otherwise you'd lose the data you are waiting to write).

@dvyukov
Copy link
Member

@dvyukov dvyukov commented Jan 11, 2017

@rsc If we do just 0-sized reads, then write support is not necessary. However, if we do Brad's "My new proposal is more like": func (c *TCPConn) OnReadable(f func()), then this equally applies to writes as well -- to avoid 2 blocked goroutines per connection.

@noblehng
Copy link

@noblehng noblehng commented Feb 21, 2017

If memory usage is the concern, it is possible to make long parked G use less memory instead of changing programming style? One main selling point of Go to me is high efficiency network servers without resorting to callbacks.

Something like shrink the stack or move the stack to heap by the GC using some heuristics, that will be littile different from spinning up a new goroutine on callback memory usage wise, and scheduling wise a callback is not much different than goready(). Also I assume the liveness change in Go1.8 could help here too.

For the backing array, if it is preallocated buffer, than a callback doesn't make much different than Read(), maybe it will make some different if it is allocated per-callback and use a pool.

Edit:
Actually we could have some GC deadline or gopark time in runtime.pollDesc, so we could get a list of long parked G from the poller, then GC can kick in, but more dance is still needed to avoid race and make it fast.

@noblehng
Copy link

@noblehng noblehng commented Feb 22, 2017

How about a epoll like interface for net.Listener:

type PollableListener interface {
   net.Listener
   // Poll will block till at least one connection been ready for read or write
   // reads and writes are special net.Conn that will not block on EAGAIN
   Poll() (reads []net.Conn, writes []net.Conn)
}

Then the caller of Poll() can has a small number of goroutines to poll for readiness and handle the reads and writes. This should also works well for packet-processing servers.

Note that this only needs to be implemented in the runtime for those Listeners that multiplexed in the kernel, like the net.TCPListener. For other protocol that multiplex in the userspace and doesn't attached to the runtime poller directly, like udp listener or multiplexing streams in a tcp connection, can be implemented outside the runtime. For example, for multiplexing in a tcp connection, we can implemented the epoll like behavior by read from/write to some buffers then poll from them or register callbacks on buffer size changed.

Edit:
To implement this, we can let users of the runtime poller, like socket and os.File, provide a callback function pointer when open the poller for a fd, to notify them the readiness of I/O. The callback should
looks like:

type IOReadyNotify func(mode int32)

And we store this in the runtime.pollDesc, then the runtime.netpollready() function should also call this callback if not nil besides give out the pending goroutine(s).

@aajtodd
Copy link

@aajtodd aajtodd commented Feb 27, 2017

I'm fairly new to Go but seeing the callback interface is a little grating given the blocking API exposed everywhere else. Why not expose a public API to the netpoll interfaces?

Go provides no standard public facing event loop (correct me if I'm wrong please). I have need to wait for readability on external FFI socket(s) (given through cgo). It would be nice to re-use the existing netpoll abstraction to also spawn FFI sockets onto rather than having to wrap epoll/IOCP/select. Also I'm guessing wrapping (e.g) epoll from the sys package does not integrate with the scheduler which would also be a bummer.

@mjgarton
Copy link
Contributor

@mjgarton mjgarton commented Mar 15, 2017

For a number of my use cases, something like this :

package net

// Readable returns a channel which can be read from whenever a call to c.Read
// would not block.
func (c *TCPConn) Readable() <-chan struct{} {
        // ...
}

.. would be nice because I can select on it. I have no idea whether it's practical to implement this though.

Another alternative (for some of my cases at least) might be somehow enabling reads to be canceled by using a context.

@funny-falcon
Copy link
Contributor

@funny-falcon funny-falcon commented Feb 15, 2019

typical Go style is quite convenient for high-level nd medium-level logic, and quite inefficient at low level.

@gobwas
Copy link

@gobwas gobwas commented Feb 18, 2019

@ianlancetaylor as exploration, maybe option of exporting network poller API would be better idea than a callback? I mean something like this:

import "net/poll"

p, err := poll.Create(...) // epoll_create() on Linux.
if err != nil {
    // handle error
}
go func() {
    for ev := range poll.Wait() { // epoll_wait on Linux.
        ev.Conn.Read(...)
        ev.Data // User data bound within Notify() call.
    }
}()
conn, err := net.Dial(...)
if err != nil {
    // handle error
}
if err := p.Notify(poll.Read, conn, data); err != nil { // epoll_ctl on Linux.
    // handle error
}

Thus, we may leave general poller untouched (and non-blocking), but provide additional polling mechanism which will block when poll.Wait() stopped being drained.

Also Notify() api may differ, e.g. accepting different channels to write event to, as you suggested, but in blocking manner – without events loss and with strong notice in method comment =)

@networkimprov
Copy link

@networkimprov networkimprov commented Feb 19, 2019

I also wonder if we will be able to do this "exactly one non-spurious notification". I think C networking servers will do own polling, but then always followed by non-blocking reads/writes. If we leave reads/writes blocking, then it will bring very unique requirements for the polling mechanism.

@dvyukov, would it work to do a non-blocking read of a byte or two internally to verify readability before raising a notification? That adds at least one syscall to the overhead, but for a network or storage situation, maybe that's OK.

In the spirit of epoll, it would be helpful to get notifications for an arbitrary set of io.Reader objects via a single channel, since we cannot select on a runtime-defined set of channels.

@dvyukov
Copy link
Member

@dvyukov dvyukov commented Feb 19, 2019

would it work to do a non-blocking read of a byte or two internally to verify readability before raising a notification?

This looks dirty and slow and in the end there can be just 1 byte. So it was readable, but not now anymore ;)

In the spirit of epoll, it would be helpful to get notifications for an arbitrary set of io.Reader objects via a single channel, since we cannot select on a runtime-defined set of channels.

I think this is supported by the Ian's proposal, no?

@networkimprov
Copy link

@networkimprov networkimprov commented Feb 19, 2019

Then let r.Read() be non-blocking after r.NotifyWhenReadable() and possibly return error io.WouldBlock?

@gobwas
Copy link

@gobwas gobwas commented Feb 19, 2019

@networkimprov JFYI there is an ability to Select() on runtime defined set of channels via reflect api.

@ianlancetaylor
Copy link
Contributor

@ianlancetaylor ianlancetaylor commented Feb 19, 2019

@networkimprov Having a non-blocking Read method amounts to the C API. It's appropriate for single-threaded programs but it's not a good choice for Go.

@gobwas I think that in practice using a poller is going to lead people to write code using callback APIs. It's the most natural way to use a poller.

@networkimprov
Copy link

@networkimprov networkimprov commented Feb 19, 2019

Do you have a plan to deal with the issue Dmitry raised?

@ianlancetaylor
Copy link
Contributor

@ianlancetaylor ianlancetaylor commented Feb 19, 2019

@networkimprov Which issue? If you mean the problem with possibly losing a channel notification, then of course he is quite right, and the channel send must be a blocking send. Depending on the implementation, this may require spinning up a goroutine to do the send.

@networkimprov
Copy link

@networkimprov networkimprov commented Feb 19, 2019

No, I was referring to

I also wonder if we will be able to do this "exactly one non-spurious notification". I think C networking servers will do own polling, but then always followed by non-blocking reads/writes. If we leave reads/writes blocking, then it will bring very unique requirements for the polling mechanism. E.g. the current linux polling scheme is always armed edge-triggered epoll. It by design generates spurious notifications.

How do you deal with this without letting r.Read() be non-blocking after r.NotifyWhenReadable() and possibly returning error io.WouldBlock?

@ianlancetaylor
Copy link
Contributor

@ianlancetaylor ianlancetaylor commented Feb 19, 2019

The problem I was trying to address was "large server with a lot of goroutines burns a lot of memory in buffers waiting to read." For that purpose it's OK if a spurious notification leads to a blocking Read, as long as spurious notifications are rare. But maybe I'm missing something.

@networkimprov
Copy link

@networkimprov networkimprov commented Feb 20, 2019

Brad was trying to get rid of the idle goroutines: #15735 (comment)

If that's not a requirement, an alternate read API could internally poll, malloc/free, and do non-blocking reads, and return a new buffer on success. An internal buffer pool would avoid thrashing the allocator due to fruitless reads after spurious poll events.

func (r *T) ReadSize(maxLen int) (byte[], error)
@ianlancetaylor
Copy link
Contributor

@ianlancetaylor ianlancetaylor commented Feb 20, 2019

My channel suggestion also permits getting rid of the idle goroutines, for people who want to write a more complex program.

@networkimprov
Copy link

@networkimprov networkimprov commented Feb 20, 2019

But it does incur a read-buffer + idle goroutine for every spurious poll event, which could be costly.

@dvyukov, any idea as to the proportion of spurious epoll wakeups in Linux?

More on epoll difficulties (from 2y ago):
https://news.ycombinator.com/item?id=13736674

@dvyukov
Copy link
Member

@dvyukov dvyukov commented Feb 20, 2019

@dvyukov, any idea as to the proportion of spurious epoll wakeups in Linux?

No, I don't.
But if a solution relies on absence of spurious wakeups for correctness/performance, I guess we need these numbers for all OSes before making a decision.

@MaurGi
Copy link

@MaurGi MaurGi commented Apr 9, 2019

I am trying to understand when a tcp server has closed the connection, as I am not receiving errors on the reads.
So if I understand correctly, I am stuck: I cannot read a 0 byte string to detect if the connection is closed and I cannot read a 1 byte because my server never writes anything and the read is blocking -

Is there any reliable way to detect that a TCP connection was closed from the server without relying on the server writing something on the connection ?

Also see https://stackoverflow.com/questions/55544914/cannot-detect-that-a-tcp-service-in-kubernetes-has-no-pods-with-golang-app?answertab=oldest#tab-top

@methane
Copy link
Contributor

@methane methane commented Apr 10, 2019

FYI, we implemented this in mysql driver.
https://github.com/go-sql-driver/mysql/blob/master/conncheck.go

Note that it works only on Unix, and it caused several allocations.
I really want this is implemented in stdlib in efficient (and probably cross platform) way.

@detailyang
Copy link

@detailyang detailyang commented Apr 30, 2019

It's highly useful to reduce overhead when the go program holds a lot of connections (connection pool) and now I'm using the epoll mechanisms do this which is not idiomatic.

Looking forward to land in Go, many thanks:)

@szuecs
Copy link

@szuecs szuecs commented Jul 10, 2019

@ianlancetaylor + @bradfitz a typical problem I have in an http proxy is, that connection spikes can create spikes in memory usage. I think this can be fixed with using epoll and I hope your approach will cover the problem. We would need to be able to set the max concurrency level for the goroutine calls, that will read and write from/to sockets.
We have an internal protection mechanism to avoid this problem, but you can see the memory spike in in bufio:

image

@xtaci
Copy link

@xtaci xtaci commented Nov 27, 2019

I need readability notification badly in my project, as I have to pre-allocate 4k buffer per connection before conn.Read([]byte), just like io.Copy does:

https://golang.org/src/io/io.go?s=12796:12856#L399

UPDATE:
solved this by RawConn:
https://github.com/xtaci/kcptun/blob/v20191219/generic/rawcopy_unix.go

@eloff
Copy link

@eloff eloff commented Dec 22, 2019

So there is RawConn now which has an interface very much like what @bradfitz was proposing here. However, it calls the read callback before calling wait for read. It must do this, as the net poller uses edge-triggered events - they won't fire if there is already data on the socket.

One workaround is to use a small stack buffer for the initial Read, and then when that reads some data, allocate and copy it to a real buffer, and then call Read again. That helps, but you'll still have the goroutine's 4KB stack overhead.

Another option is use RawConn.Control with unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.TCP_DEFER_ACCEPT, 1) for connections like HTTP where the client must send data first, it won't create a goroutine in the first place until there's data buffered, but only helps for that initial Read. It can be combined with the stack buffer approach for long-lived connections.

I'd still like to see an approach (maybe an async OnReadable callback method on RawConn, like bradfitz is proposing here?) to avoid having the goroutine overhead. Mail.ru avoids the net poller entirely and manually manages epoll for precisely this reason, as 4KB per WebSocket connection with millions of open but mostly idle WebSockets waiting for new mail is just too much overhead.

@xtaci
Copy link

@xtaci xtaci commented Dec 23, 2019

I'd still like to see an approach (maybe an async OnReadable callback method on RawConn, like bradfitz is proposing here?) to avoid having the goroutine overhead. Mail.ru avoids the net poller entirely and manually manages epoll for precisely this reason, as 4KB per WebSocket connection with millions of open but mostly idle WebSockets waiting for new mail is just too much overhead.

I don't think OnReadable callback is a good idea. If I have 2 handlers to toggle based on incoming data, then it's not impossible to code this kind of nested callbacks which reference to each other.

For such reason, in order to writing comprehensive logic we have to copy the buffer from callback out to another goroutine, in such case, the memory usage will be out of control, as we lost the ability to back-pressure the congestion signal to senders. (Before, we won't start next net.Read() until we've processed data.)

Even for a callback like func() { Read();Process();Write() } scenario, if Write() blocks, this callback still holds 4KB-buffer waiting to be sent.

In all these cases above, we still have inactive 4KB-buffers somewhere.

@xtaci
Copy link

@xtaci xtaci commented Jan 13, 2020

I wrote a library based on ideas above, golang async-io

https://github.com/xtaci/gaio

@ortuman
Copy link

@ortuman ortuman commented Dec 29, 2020

For my particular use case having a non-blocking Read is highly desirable. An chat service aiming to manage millions of connections per instance. Blocking interface forces to have an alive goroutine per connection, which makes this goal totally unrealistic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
You can’t perform that action at this time.