diff --git a/silkaj/network_tools.py b/silkaj/network_tools.py index 968936866047916757db1b692e0624d77c99b3cf..5b0cd1d319ca06eddf895986e37a05adb61d0c19 100644 --- a/silkaj/network_tools.py +++ b/silkaj/network_tools.py @@ -3,10 +3,12 @@ from ipaddress import ip_address from json import loads import socket import urllib.request +import logging from sys import exit, stderr from commandlines import Command from silkaj.constants import G1_DEFAULT_ENDPOINT, G1_TEST_DEFAULT_ENDPOINT +CONNECTION_TIMEOUT = 10 def discover_peers(discover): """ @@ -125,7 +127,7 @@ def get_request(path, ep=EndPoint().ep): if ep["port"] == "443": url = "https://" + ep[address] + "/" + path request = urllib.request.Request(url) - response = urllib.request.urlopen(request) + response = urllib.request.urlopen(request, timeout=CONNECTION_TIMEOUT) encoding = response.info().get_content_charset('utf8') return loads(response.read().decode(encoding)) @@ -138,7 +140,7 @@ def post_request(path, postdata): url = "http://" + ep[address] + ":" + ep["port"] + "/" + path if ep["port"] == "443": url = "https://" + ep[address] + "/" + path - request = urllib.request.Request(url, bytes(postdata, 'utf-8')) + request = urllib.request.Request(url, bytes(postdata, 'utf-8'), timeout=CONNECTION_TIMEOUT) try: response = urllib.request.urlopen(request) except urllib.error.URLError as e: @@ -150,15 +152,16 @@ def post_request(path, postdata): def best_node(ep, main): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - addresses, port = {"ip6", "ip4", "domain"}, int(ep["port"]) + s.settimeout(CONNECTION_TIMEOUT) + addresses, port = ("domain", "ip6", "ip4"), int(ep["port"]) for address in addresses: if address in ep: try: s.connect((ep[address], port)) s.close() return address - except: - pass + except Exception as e: + logging.debug("Connection to endpoint %s (%s) failled (%s)" % (ep, address, e)) if main: print("Wrong node given as argument", file=stderr) exit(1)