38 lines
1.3 KiB
Python
38 lines
1.3 KiB
Python
import sys
|
|
from time import sleep
|
|
|
|
import requests
|
|
|
|
from . import nagios
|
|
from .print import print_icinga2_check_status
|
|
|
|
|
|
def fetch_with_retry(url, method: str = 'get', retries=3, delay=1, **kwargs):
|
|
"""
|
|
Wrapper function for requests.get() with a retry mechanism.
|
|
|
|
:param method: HTTP request type: get, post
|
|
:param url: URL to send the GET request
|
|
:param retries: Number of retries in case of HTTP failures (default: 3)
|
|
:param delay: Time delay between retries in seconds (default: 1)
|
|
:param kwargs: Additional keyword arguments for requests.get()
|
|
:return: Response object
|
|
"""
|
|
|
|
for i in range(retries):
|
|
try:
|
|
if method == 'get':
|
|
response = requests.get(url, **kwargs)
|
|
elif method == 'post':
|
|
response = requests.post(url, **kwargs)
|
|
else:
|
|
raise ValueError('Invalid method! Must be get or post.')
|
|
response.raise_for_status()
|
|
return response
|
|
except requests.exceptions.RequestException as e:
|
|
if i == retries - 1:
|
|
# raise e
|
|
print_icinga2_check_status(f'HTTP request failed after {i + 1} retries: {url}\n{e}', nagios.STATE_UNKNOWN)
|
|
sys.exit(nagios.STATE_UNKNOWN)
|
|
sleep(delay)
|