2023-06-15 11:00:41 -06:00
|
|
|
import sys
|
|
|
|
from time import sleep
|
|
|
|
|
|
|
|
import requests
|
|
|
|
|
|
|
|
from . import nagios
|
2023-11-26 23:15:27 -07:00
|
|
|
from .result import print_icinga2_check_status
|
2023-06-15 11:00:41 -06:00
|
|
|
|
|
|
|
|
2023-06-27 17:56:40 -06:00
|
|
|
def fetch_with_retry(url, method: str = 'get', retries=3, delay=1, **kwargs):
|
2023-06-15 11:00:41 -06:00
|
|
|
"""
|
|
|
|
Wrapper function for requests.get() with a retry mechanism.
|
|
|
|
|
2023-06-27 17:56:40 -06:00
|
|
|
:param method: HTTP request type: get, post
|
2023-06-15 11:00:41 -06:00
|
|
|
: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
|
|
|
|
"""
|
2023-06-27 17:56:40 -06:00
|
|
|
|
2023-06-15 11:00:41 -06:00
|
|
|
for i in range(retries):
|
|
|
|
try:
|
2023-06-27 17:56:40 -06:00
|
|
|
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.')
|
2023-06-15 11:00:41 -06:00
|
|
|
response.raise_for_status()
|
|
|
|
return response
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
|
|
if i == retries - 1:
|
|
|
|
# raise e
|
2023-06-15 12:04:10 -06:00
|
|
|
print_icinga2_check_status(f'HTTP request failed after {i + 1} retries: {url}\n{e}', nagios.STATE_UNKNOWN)
|
2023-06-15 11:00:41 -06:00
|
|
|
sys.exit(nagios.STATE_UNKNOWN)
|
|
|
|
sleep(delay)
|