Skip to content

Commit b7e0e3a

Browse files
committed
Added connection timeout
1 parent 2c843da commit b7e0e3a

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

neo4j/bolt/connection.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
import logging
3131
from collections import deque
3232
from select import select
33-
from socket import socket, SOL_SOCKET, SO_KEEPALIVE, SHUT_RDWR, error as SocketError, AF_INET, AF_INET6
33+
from socket import socket, SOL_SOCKET, SO_KEEPALIVE, SHUT_RDWR, error as SocketError, timeout as SocketTimeout, AF_INET, AF_INET6
3434
from struct import pack as struct_pack, unpack as struct_unpack
3535
from threading import RLock
3636

@@ -47,6 +47,7 @@
4747
ChunkedOutputBuffer = _import_best("neo4j.bolt._io", "neo4j.bolt.io").ChunkedOutputBuffer
4848

4949

50+
DEFAULT_CONNECTION_TIMEOUT = 5.0
5051
DEFAULT_PORT = 7687
5152
DEFAULT_USER_AGENT = "neo4j-python/%s" % version
5253

@@ -443,17 +444,32 @@ def connect(address, ssl_context=None, **config):
443444
# Catches refused connections see:
444445
# https://docs.python.org/2/library/errno.html
445446
log_info("~~ [CONNECT] %s", address)
447+
s = None
446448
try:
447449
if len(address) == 2:
448450
s = socket(AF_INET)
449451
elif len(address) == 4:
450452
s = socket(AF_INET6)
451453
else:
452454
raise ValueError("Unsupported address {!r}".format(address))
455+
t = s.gettimeout()
456+
s.settimeout(config.get("connection_timeout", DEFAULT_CONNECTION_TIMEOUT))
453457
s.connect(address)
458+
s.settimeout(t)
454459
s.setsockopt(SOL_SOCKET, SO_KEEPALIVE, 1 if config.get("keep_alive", True) else 0)
460+
except SocketTimeout:
461+
if s:
462+
try:
463+
s.close()
464+
except:
465+
pass
466+
raise ServiceUnavailable("Timed out trying to establish connection to {!r}".format(address))
455467
except SocketError as error:
456-
s.close()
468+
if s:
469+
try:
470+
s.close()
471+
except:
472+
pass
457473
if error.errno in (61, 111, 10061):
458474
raise ServiceUnavailable("Failed to establish connection to {!r}".format(address))
459475
else:

0 commit comments

Comments
 (0)