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