|
30 | 30 | import logging |
31 | 31 | from collections import deque |
32 | 32 | 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 |
34 | 34 | from struct import pack as struct_pack, unpack as struct_unpack |
35 | 35 | from threading import RLock |
36 | 36 |
|
|
47 | 47 | ChunkedOutputBuffer = _import_best("neo4j.bolt._io", "neo4j.bolt.io").ChunkedOutputBuffer |
48 | 48 |
|
49 | 49 |
|
| 50 | +DEFAULT_CONNECTION_TIMEOUT = 5.0 |
50 | 51 | DEFAULT_PORT = 7687 |
51 | 52 | DEFAULT_USER_AGENT = "neo4j-python/%s" % version |
52 | 53 |
|
@@ -443,17 +444,32 @@ def connect(address, ssl_context=None, **config): |
443 | 444 | # Catches refused connections see: |
444 | 445 | # https://docs.python.org/2/library/errno.html |
445 | 446 | log_info("~~ [CONNECT] %s", address) |
| 447 | + s = None |
446 | 448 | try: |
447 | 449 | if len(address) == 2: |
448 | 450 | s = socket(AF_INET) |
449 | 451 | elif len(address) == 4: |
450 | 452 | s = socket(AF_INET6) |
451 | 453 | else: |
452 | 454 | raise ValueError("Unsupported address {!r}".format(address)) |
| 455 | + t = s.gettimeout() |
| 456 | + s.settimeout(config.get("connection_timeout", DEFAULT_CONNECTION_TIMEOUT)) |
453 | 457 | s.connect(address) |
| 458 | + s.settimeout(t) |
454 | 459 | 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)) |
455 | 467 | except SocketError as error: |
456 | | - s.close() |
| 468 | + if s: |
| 469 | + try: |
| 470 | + s.close() |
| 471 | + except: |
| 472 | + pass |
457 | 473 | if error.errno in (61, 111, 10061): |
458 | 474 | raise ServiceUnavailable("Failed to establish connection to {!r}".format(address)) |
459 | 475 | else: |
|
0 commit comments