Skip to content

enabling TCP keepalive to avoid connections getting closed #205

Description

@traffetseder

We ran into an issue with NAT gateway closing connections for long running queries that do not stream data back to the client. To fix this, we enabled TCP keepalive on the socket.

I haven't created a PR because this is linux specific code, but wanted to add it here to see if the community finds it useful.

See diff below.

-Thomas

--- a/vertica_python/vertica/connection.py
+++ b/vertica_python/vertica/connection.py
@@ -111,6 +112,20 @@ class Connection(object):
         self.transaction_status = None
         self.socket = None

+    def set_keepalive_linux(self, sock, after_idle_sec=60, interval_sec=60, max_fails=10):
+        """Set TCP keepalive on an open socket.
+        It activates after after_idle_sec of idleness,
+        then sends a keepalive ping once every interval_sec,
+        and closes the connection after max_fails failed ping ()
+        """
+        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
+        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
+        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
+        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)
+
     def _socket(self):
         if self.socket is not None:
             return self.socket
@@ -121,9 +136,13 @@ class Connection(object):
         raw_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         raw_socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
         if connection_timeout is not None:
             raw_socket.settimeout(connection_timeout)
         raw_socket.connect((host, port))

+        self.set_keepalive_linux(sock=raw_socket, after_idle_sec=60, interval_sec=60, max_fails=10)
+
         ssl_options = self.options.get('ssl')
         if ssl_options is not None and ssl_options is not False:
             from ssl import CertificateError, SSLError

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions