Add support for connection retry

With the new optional parameter `retries` the number of retries in case of a
failure can be specified.

For compability reasons the default is kept as zero.

Change-Id: I9483343208d6f1be7b2b74ba993499c51852f431
This commit is contained in:
Jonas Scharpf 2025-03-17 15:08:28 +01:00
parent e0b7e33800
commit f29d64f991

View File

@ -59,11 +59,13 @@ import multi_key_dict
import requests
import requests.exceptions as req_exc
import urllib3.util.timeout
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from http.client import BadStatusLine
from urllib.error import URLError
from urllib.parse import quote, urlencode, urljoin, urlparse
import xml.etree.ElementTree as ET
from urllib3.util import parse_url, Retry
from jenkins import plugins
@ -93,6 +95,7 @@ LAUNCHER_JNLP = 'hudson.slaves.JNLPLauncher'
LAUNCHER_WINDOWS_SERVICE = 'hudson.os.windows.ManagedWindowsServiceLauncher'
DEFAULT_HEADERS = {'Content-Type': 'text/xml; charset=utf-8'}
DEFAULT_TIMEOUT = getattr(urllib3.util.timeout, '_DEFAULT_TIMEOUT', socket._GLOBAL_DEFAULT_TIMEOUT)
DEFAULT_RETRIES = 0
# REST Endpoints
INFO = 'api/json'
@ -302,7 +305,7 @@ class Jenkins(object):
_timeout_warning_issued = False
def __init__(self, url, username=None, password=None,
timeout=DEFAULT_TIMEOUT):
timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES):
'''Create handle to Jenkins instance.
All methods will raise :class:`JenkinsException` on failure.
@ -336,6 +339,11 @@ class Jenkins(object):
self.timeout = timeout
self._session = WrappedSession()
self._session.mount(
parse_url(self.server).scheme,
HTTPAdapter(max_retries=Retry(total=retries, backoff_factor=0.1))
)
extra_headers = os.environ.get("JENKINS_API_EXTRA_HEADERS", "")
if extra_headers:
logging.warning("JENKINS_API_EXTRA_HEADERS adds these HTTP headers: %s", extra_headers.split("\n"))