From 01616ab37a1a826b3cf8c45d5bf0dcb25142af93 Mon Sep 17 00:00:00 2001 From: AdamSimpson Date: Sun, 18 Feb 2018 14:12:36 -0500 Subject: [PATCH] Set TCP keep alive values for builder queue correctly(hopefully) --- Builder/src/main.cpp | 4 ---- BuilderQueue/include/Connection.h | 10 +++------- BuilderQueue/src/Connection.cpp | 22 ++++++++++++++++++++++ 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/Builder/src/main.cpp b/Builder/src/main.cpp index b6019bf..b756432 100644 --- a/Builder/src/main.cpp +++ b/Builder/src/main.cpp @@ -193,10 +193,6 @@ int main(int argc, char *argv[]) { acceptor.accept(client_stream.next_layer()); client_stream.accept(); - // Use keep alive, which hopefully detect badly disconnected clients - boost::asio::socket_base::keep_alive keep_alive(true); - socket.set_option(keep_alive); - Logger::info("Setting the websocket stream to handle binary data and have an unlimited(uint64_t) message size"); client_stream.binary(true); client_stream.read_message_max(0); diff --git a/BuilderQueue/include/Connection.h b/BuilderQueue/include/Connection.h index d45d0e4..08069d7 100644 --- a/BuilderQueue/include/Connection.h +++ b/BuilderQueue/include/Connection.h @@ -16,13 +16,7 @@ class Connection : public std::enable_shared_from_this { public: explicit Connection(tcp::socket socket, BuilderQueue &queue) : stream(std::move(socket)), queue(queue) { - // Use keep alive, which hopefully detect badly disconnected clients - boost::asio::socket_base::keep_alive keep_alive(true); - boost::system::error_code ec; - socket.set_option(keep_alive, ec); - if(ec) { - Logger::error("Error setting keep alive on socket"); - } + enable_keep_alive(); }; ~Connection() { @@ -40,6 +34,8 @@ class Connection : public std::enable_shared_from_this { beast::flat_buffer buffer; boost::optional builder; + void enable_keep_alive(); + void read_request_string(); void request_builder(); diff --git a/BuilderQueue/src/Connection.cpp b/BuilderQueue/src/Connection.cpp index 219d5e0..2c97c6d 100644 --- a/BuilderQueue/src/Connection.cpp +++ b/BuilderQueue/src/Connection.cpp @@ -5,6 +5,28 @@ using namespace std::placeholders; +void Connection::enable_keep_alive() { + auto socket = stream.next_layer().native_handle(); + + // Enable keep alive + int enable = 1; + int rc = setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, &enable, sizeof(enable)); + + // Set keep alive values + unsigned interval_milliseconds = 30000; + struct timeval tv; + tv.tv_sec = interval_milliseconds / 1000; + tv.tv_usec = interval_milliseconds % 1000; + int max_retry = 5; + rc |= setsockopt(socket, SOL_TCP, TCP_KEEPIDLE, &tv, sizeof(tv)); + rc |= setsockopt(socket, SOL_TCP, TCP_KEEPINTVL, &tv, sizeof(tv)); + rc |= setsockopt(socket, SOL_TCP, TCP_KEEPCNT, &max_retry, sizeof(max_retry)); + + if(rc != 0) { + Logger::error(std::string("Error setting keepalive: ") + strerror(errno)); + } +} + void Connection::wait_for_close() { // Persist this connection auto self(shared_from_this());