From 4524aca5d9a22f5e81d9408a55f090227478ed15 Mon Sep 17 00:00:00 2001 From: Lukas Trippe Date: Wed, 11 Sep 2024 16:31:19 +0200 Subject: [PATCH] fix: connection check failing (#1280) --- rules/common.smk | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/rules/common.smk b/rules/common.smk index ef518beb9..203fb9c06 100644 --- a/rules/common.smk +++ b/rules/common.smk @@ -115,20 +115,26 @@ def input_custom_extra_functionality(w): return [] -# Check if the workflow has access to the internet by trying to access the HEAD of specified url -def has_internet_access(url="www.zenodo.org") -> bool: - import http.client as http_client +def has_internet_access(url: str = "https://www.zenodo.org", timeout: int = 3) -> bool: + """ + Checks if internet connection is available by sending a HEAD request + to a reliable server like Google. + + Parameters: + - url (str): The URL to check for internet connection. Default is Google. + - timeout (int | float): The maximum time (in seconds) the request should wait. - # based on answer and comments from - # https://stackoverflow.com/a/29854274/11318472 - conn = http_client.HTTPConnection(url, timeout=5) # need access to zenodo anyway + Returns: + - bool: True if the internet is available, otherwise False. + """ try: - conn.request("HEAD", "/") - return True - except: + # Send a HEAD request to avoid fetching full response + response = requests.head(url, timeout=timeout, allow_redirects=True) + return response.status_code == 200 + except requests.ConnectionError: # (e.g., no internet, DNS issues) + return False + except requests.Timeout: # (e.g., slow or no network) return False - finally: - conn.close() def solved_previous_horizon(w):