icinga2-checks/checker/http.py

38 lines
1.3 KiB
Python
Raw Normal View History

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
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.
: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-15 11:00:41 -06:00
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.')
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
2024-06-22 21:45:38 -06:00
print_icinga2_check_status(f'HTTP request failed after {i + 1} retries: {url}\n{e}', nagios.STATE_CRIT)
sys.exit(nagios.STATE_CRIT)
2023-06-15 11:00:41 -06:00
sleep(delay)