diff --git a/include/fluent-bit/flb_network.h b/include/fluent-bit/flb_network.h index 900ec691cf4..9569ba22ed3 100644 --- a/include/fluent-bit/flb_network.h +++ b/include/fluent-bit/flb_network.h @@ -68,6 +68,18 @@ struct flb_net_setup { /* maximum of times a keepalive connection can be used */ int keepalive_max_recycle; + /* enable/disable tcp keepalive */ + int tcp_keepalive; + + /* interval between the last data packet sent and the first TCP keepalive probe */ + int tcp_keepalive_time; + + /* the interval between TCP keepalive probes */ + int tcp_keepalive_interval; + + /* number of unacknowledged probes to consider a connection dead */ + int tcp_keepalive_probes; + /* dns mode : TCP or UDP */ char *dns_mode; @@ -154,6 +166,7 @@ int flb_net_socket_blocking(flb_sockfd_t fd); int flb_net_socket_nonblocking(flb_sockfd_t fd); int flb_net_socket_rcv_buffer(flb_sockfd_t fd, int rcvbuf); int flb_net_socket_tcp_fastopen(flb_sockfd_t sockfd); +int flb_net_socket_tcp_keepalive(flb_sockfd_t fd, struct flb_net_setup *net); /* Socket handling */ flb_sockfd_t flb_net_socket_create(int family, int nonblock); diff --git a/src/flb_network.c b/src/flb_network.c index d183209fd52..7ac86e98f67 100644 --- a/src/flb_network.c +++ b/src/flb_network.c @@ -116,6 +116,10 @@ void flb_net_setup_init(struct flb_net_setup *net) net->keepalive = FLB_TRUE; net->keepalive_idle_timeout = 30; net->keepalive_max_recycle = 0; + net->tcp_keepalive = FLB_FALSE; + net->tcp_keepalive_time = -1; + net->tcp_keepalive_interval = -1; + net->tcp_keepalive_probes = -1; net->accept_timeout = 10; net->connect_timeout = 10; net->io_timeout = 0; /* Infinite time */ @@ -298,6 +302,51 @@ int flb_net_socket_tcp_fastopen(flb_sockfd_t fd) return setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &qlen, sizeof(qlen)); } + +/* + * Enable TCP keepalive + */ +int flb_net_socket_tcp_keepalive(flb_sockfd_t fd, struct flb_net_setup *net) +{ + int interval; + int enabled; + int probes; + int time; + int ret; + + enabled = 1; + + time = net->tcp_keepalive_time; + probes = net->tcp_keepalive_probes; + interval = net->tcp_keepalive_interval; + + ret = setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, + (const void *) &enabled, sizeof(enabled)); + + if (ret == 0 && time >= 0) { + ret = setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, + (const void *) &time, sizeof(time)); + } + + if (ret == 0 && interval >= 0) { + ret = setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, + (const void *) &interval, sizeof(interval)); + } + + if (ret == 0 && probes >= 0) { + ret = setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, + (const void *) &probes, sizeof(probes)); + } + + if (ret != 0) { + flb_error("[net] failed to configure TCP keepalive for connection #%i", fd); + + ret = -1; + } + + return ret; +} + flb_sockfd_t flb_net_socket_create(int family, int nonblock) { flb_sockfd_t fd;