Background
When writing Go networking applications, there is a series of TCP connection methods that I use a lot: SetDeadline
, SetReadDeadline
, SetWriteDeadline
. Their purpose is to wait for a read or write operation on a TCP connection, and if there is no read or write operation at the preset time point, the read method will get an ErrDeadlineExceeded
error, which is often used to determine if a connection has been lost. In this article, I’ll describe how to use them and how Go implements them, and try to achieve a similar effect in C++.
Why we need Deadline
As you known something about TCP, you might ask: doesn’t TCP have Keepalive protocol? Why do we still need to use the Deadline
for the Connection
? Obviously, we know the keepalive for TCP is system level, and it’s configured at the /proc/sys/net/ipv4/
directory:
[root@liqiang.io]# ls -al /proc/sys/net/ipv4/tcp_keepalive_*
-rw-r--r-- 1 root root 0 Oct 29 11:56 /proc/sys/net/ipv4/tcp_keepalive_intvl
-rw-r--r-- 1 root root 0 Oct 29 11:56 /proc/sys/net/ipv4/tcp_keepalive_probes
-rw-r--r-- 1 root root 0 Oct 29 11:56 /proc/sys/net/ipv4/tcp_keepalive_time
If we choose to use the keepalive configure for the TCP, you might need to setup the system global config, but in the enterprise network development, it’s no a good practive, as each application will have it’s self requirement, so we can’t use the same configure directly.
How to use Deadline
An simple demo to use Deadline
will be like:
[root@liqiang.io]# cat test.go
func (c *ApplicationConnection) readLoop() {
var err error
c.conn, err = net.Dial("tcp", c.GetDialerAddr())
if err != nil {
c.logger.Error(c.ctx, "connect to %s: %v", d.GetDialerAddr(), err)
return
}
c.conn.SetReadDeadline(time.Now().Add(time.Second * 10))
for {
bytes, err := io.ReadAll(c.conn)
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
c.logger.Trace(c.ctx, "Read timeout, send a heartbeat message")
c.heartbeat()
continue
}
c.logger.Error(c.ctx, "Failed to copy data from listener to Dialer: %v", err)
return
}
c.conn.SetReadDeadline(time.Now().Add(time.Second * 10))
c.process(bytes)
}
}
Here we can set a waiting time, if there is no data to be read from the connection within the expected time, then an error will be returned and we can process the connection as needed; if there is data to be read during this period, then we need to be careful to reset the Deadline value, otherwise, the value will still be valid.
How to implement Deadline
After knowing how to use, the next question is how Go implement Connection’s Deadline? In the previous analysis of Go’s source code, we know that Go still uses epoll at the bottom of the network, so how does Go runtime do it with Deadline?
I can imagine a solution is to package Connection into a struct structure, struct structure contains the original connection information, deadline information (a timer), and timer handler, and then add the corresponding timer in epoll, so that when the timer is triggered, it means that there is nothing to be done during the period. , it means that there are no readable events in the meantime, so you can call the handler function directly, thus achieving the effect of a deadline.
However, how Go achieves this, we still have to look at the code (here I follow the previous Go source code analysis logic, looking at the code of 1.12):
[root@liqiang.io]# internal/poll/fd_poll_runtime.go
func (fd *FD) SetReadDeadline(t time.Time) error {
return setDeadlineImpl(fd, t, 'r')
---> internal/poll/fd_poll_runtime.go
func setDeadlineImpl(fd *FD, t time.Time, mode int) error {
... ...
runtime_pollSetDeadline(fd.pd.runtimeCtx, d, mode)
---> runtime/netpoll.go
func poll_runtime_pollSetDeadline(pd *pollDesc, d int64, mode int) {
... ...
netpollgoready(rg, 3)
---> runtime/netpoll.go
... ...
pd.rt.f = rtf
pd.rt.when = pd.rd
pd.rt.arg = pd
pd.rt.seq = pd.rseq
addtimer(&pd.rt)
As you can see, the Go implementation is largely what I envisioned, except with more conditional guarantees and such.
How to implement in C++
Recently, I’ve been trying to write some network programs in C++, so naturally I wanted to see if C++ supports similar functionality, but there doesn’t seem to be any direct support for it, so I implemented it myself based on libevent, and the code is divided into several parts:
- connection encapsulate struct
[root@liqiang.io]# cat echo_server.cpp
struct TimeoutConnection {
long int last_read_ts;
std::string name;
evutil_socket_t fd;
struct event_base *base;
struct bufferevent *bev;
struct event *timeout_event;
};
- connection creation part
static void listener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sa, int socklen, void *user_data) {
std::cout << get_current_time() << " listener_cb" << std::endl;
struct event_base *base = (event_base *) user_data;
struct bufferevent *bev;
bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
if (!bev) {
std::cerr << get_current_time() << " failed to constructing bufferevent!" << std::endl;
event_base_loopbreak(base);
return;
}
struct TimeoutConnection *timeoutConn = (struct TimeoutConnection *) malloc(sizeof(struct TimeoutConnection));
timeoutConn->last_read_ts = std::time(nullptr);
timeoutConn->name = "test";
timeoutConn->fd = fd;
timeoutConn->base = base;
timeoutConn->bev = bev;
timeoutConn->timeout_event = event_new(base, -1, EV_PERSIST, timeout_cb, timeoutConn);
bufferevent_setcb(bev, conn_readcb, NULL, conn_eventcb, timeoutConn);
bufferevent_enable(bev, EV_READ);
struct timeval tv = {.tv_sec = 5, .tv_usec = 0};
auto result = event_add(timeoutConn->timeout_event, &tv);
if (result != 0) {
std::cout << "event_add failed" << std::endl;
}
}
- read data part
[root@liqiang.io]# cat echo_server.cpp
static void conn_readcb(struct bufferevent *bev, void *ptr) {
struct TimeoutConnection *timeoutConn = (struct TimeoutConnection *) ptr;
timeoutConn->last_read_ts = std::time(nullptr);
char buf[1024];
int n;
struct evbuffer *input = bufferevent_get_input(bev);
while ((n = evbuffer_remove(input, buf, sizeof(buf))) > 0) {
std::cout << get_current_time() << " connection " << timeoutConn->name << " recv: " << buf << std::endl;
bufferevent_write(bev, buf, n);
}
}
- timer implement part
[root@liqiang.io]# cat echo_server.cpp
static void timeout_cb(evutil_socket_t fd, short what, void *arg) {
std::cout << get_current_time() << " connection timeout invoked" << std::endl;
auto currTs = std::time(nullptr);
struct TimeoutConnection *timeoutConn = (struct TimeoutConnection *) arg;
if (currTs - timeoutConn->last_read_ts > 10) {
std::cout << get_current_time() << " connection " << timeoutConn->name << " timeout" << std::endl;
std::cout << get_current_time() << " connection " << timeoutConn->name << " last read at: " << timeoutConn->last_read_ts << std::endl;
bufferevent_free(timeoutConn->bev);
event_free(timeoutConn->timeout_event);
free(timeoutConn);
return;
}
std::cout << get_current_time() << " connection " << timeoutConn->name << " last read at: " << timeoutConn->last_read_ts << std::endl;
}
Summary
That’s pretty much all you need to know about this part of the implementation, and it’s not too complicated. However, there’s a lot to dig into, such as how Go’s underlying timer is implemented, but I’ve written similar things before(Linux 实现定时器),here I will not to write more.