diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 915058eff0..21f09c4cf4 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -42,6 +42,12 @@ Changed Added ~~~~~ * added raw_string type to allow template strings to pass through variable processing (by @guzzijones12@gmail.com) #6351 +* st2client now retries failed HTTP requests and times out instead of hanging when the API can't + be reached. Connection errors are retried for all requests; timeouts and 502 / 503 / 504 + responses only for requests which are safe to send again (never ``POST``). Defaults: 3 retries + and a 10 second connect timeout. Configurable with ``--http-retries`` / ``--http-timeout``, + ``ST2_HTTP_RETRIES`` / ``ST2_HTTP_TIMEOUT`` or ``http_retries`` / ``http_timeout`` in the + ``[general]`` section of the CLI config. #6428 (by @Vipulucc115) 3.9.0 - October 10, 2025 ------------------------ diff --git a/conf/st2rc.sample.ini b/conf/st2rc.sample.ini index 5d62b59ef5..ef03b9b8e1 100644 --- a/conf/st2rc.sample.ini +++ b/conf/st2rc.sample.ini @@ -4,6 +4,14 @@ base_url = http://127.0.0.1 api_version = v1 # Path to the CA cert bundle used to validate the SSL certificates cacert = +# Seconds to wait for the StackStorm API, both to connect and for each reply. +# If not set, connecting times out after 10 seconds and there is no limit on +# waiting for a reply. +# http_timeout = 30 +# How many times a failed request is retried (default 3, 0 disables retrying). +# Connection errors are retried for all requests, timeouts and 502 / 503 / 504 +# responses only for requests which are safe to send again (not POST). +# http_retries = 3 [cli] debug = True diff --git a/st2client/st2client/base.py b/st2client/st2client/base.py index 5f35fb7947..85afdf5324 100644 --- a/st2client/st2client/base.py +++ b/st2client/st2client/base.py @@ -61,6 +61,8 @@ "api_version": ["general", "api_version"], "api_key": ["credentials", "api_key"], "cacert": ["general", "cacert"], + "timeout": ["general", "http_timeout"], + "retries": ["general", "http_retries"], "debug": ["cli", "debug"], "basic_auth": ["credentials", "basic_auth"], } @@ -101,6 +103,8 @@ def get_client(self, args, debug=False): cli_options["cacert"] = True elif cli_options["cacert"].lower() in ["false", "0", "f", "no"]: cli_options["cacert"] = False + cli_options["timeout"] = getattr(args, "http_timeout", None) + cli_options["retries"] = getattr(args, "http_retries", None) config_file_options = self._get_config_file_options(args=args) kwargs = {} @@ -402,6 +406,8 @@ def _authenticate_and_retrieve_auth_token(self, client, username, password): client.endpoints["auth"], cacert=client.cacert, debug=client.debug, + timeout=client.timeout, + retries=client.retries, ) instance = models.Token() instance = manager.create(instance, auth=(username, password)) diff --git a/st2client/st2client/client.py b/st2client/st2client/client.py index 4b3e74e849..58446165eb 100644 --- a/st2client/st2client/client.py +++ b/st2client/st2client/client.py @@ -52,6 +52,52 @@ DEFAULT_API_VERSION = "v1" +def get_http_timeout(value): + """ + Validate the HTTP timeout given as an argument, an environment variable or a config option. + + :rtype: ``float`` or ``None`` when no timeout was given. + """ + if value is None or value == "": + return None + + try: + timeout = float(value) + except (TypeError, ValueError): + timeout = None + + if timeout is None or not timeout > 0: + raise ValueError( + 'HTTP timeout needs to be a number of seconds greater than 0, got "%s"' + % (value) + ) + + return timeout + + +def get_http_retries(value): + """ + Validate the number of HTTP retries given as an argument, an environment variable or a + config option. + + :rtype: ``int`` or ``None`` when no number of retries was given. + """ + if value is None or value == "": + return None + + try: + retries = int(value) + except (TypeError, ValueError): + retries = None + + if retries is None or retries < 0: + raise ValueError( + 'HTTP retries needs to be a whole number, 0 or greater, got "%s"' % (value) + ) + + return retries + + class Client(object): def __init__( self, @@ -65,6 +111,8 @@ def __init__( token=None, api_key=None, basic_auth=None, + timeout=None, + retries=None, ): # Get CLI options. If not given, then try to get it from the environment. self.endpoints = dict() @@ -143,6 +191,16 @@ def __init__( else: self.basic_auth = None + # Timeout and retries used for every HTTP request to the StackStorm API. When not given, + # httpclient.HTTPClient defaults are used. + if timeout is None: + timeout = os.environ.get("ST2_HTTP_TIMEOUT", None) + self.timeout = get_http_timeout(timeout) + + if retries is None: + retries = os.environ.get("ST2_HTTP_RETRIES", None) + self.retries = get_http_retries(retries) + # Instantiate resource managers and assign appropriate API endpoint. self.managers = dict() self.managers["Token"] = ResourceManager( @@ -151,6 +209,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["RunnerType"] = ResourceManager( models.RunnerType, @@ -158,6 +218,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Action"] = ActionResourceManager( models.Action, @@ -165,6 +227,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["ActionAlias"] = ActionAliasResourceManager( models.ActionAlias, @@ -172,6 +236,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["ActionAliasExecution"] = ActionAliasExecutionManager( models.ActionAliasExecution, @@ -179,6 +245,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["ApiKey"] = ResourceManager( models.ApiKey, @@ -186,6 +254,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Config"] = ConfigManager( models.Config, @@ -193,6 +263,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["ConfigSchema"] = ResourceManager( models.ConfigSchema, @@ -200,6 +272,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Execution"] = ExecutionResourceManager( models.Execution, @@ -207,6 +281,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) # NOTE: LiveAction has been deprecated in favor of Execution. It will be left here for # backward compatibility reasons until v3.2.0 @@ -217,6 +293,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Pack"] = PackResourceManager( models.Pack, @@ -224,6 +302,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Policy"] = ResourceManager( models.Policy, @@ -231,6 +311,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["PolicyType"] = ResourceManager( models.PolicyType, @@ -238,6 +320,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Rule"] = ResourceManager( models.Rule, @@ -245,6 +329,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Sensor"] = ResourceManager( models.Sensor, @@ -252,6 +338,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["TriggerType"] = ResourceManager( models.TriggerType, @@ -259,6 +347,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Trigger"] = ResourceManager( models.Trigger, @@ -266,6 +356,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["TriggerInstance"] = TriggerInstanceResourceManager( models.TriggerInstance, @@ -273,6 +365,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["KeyValuePair"] = KeyValuePairResourceManager( models.KeyValuePair, @@ -280,6 +374,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Webhook"] = WebhookManager( models.Webhook, @@ -287,6 +383,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Timer"] = ResourceManager( models.Timer, @@ -294,6 +392,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Trace"] = ResourceManager( models.Trace, @@ -301,6 +401,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["RuleEnforcement"] = ResourceManager( models.RuleEnforcement, @@ -308,18 +410,24 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Stream"] = StreamManager( self.endpoints["stream"], cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["Workflow"] = WorkflowManager( self.endpoints["api"], cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) # Service Registry @@ -329,6 +437,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["ServiceRegistryMembers"] = ServiceRegistryMembersManager( @@ -337,6 +447,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) # RBAC @@ -346,6 +458,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) self.managers["UserRoleAssignment"] = ResourceManager( models.UserRoleAssignment, @@ -353,6 +467,8 @@ def __init__( cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) @add_auth_token_to_kwargs_from_env @@ -368,6 +484,8 @@ def get_user_info(self, **kwargs): cacert=self.cacert, debug=self.debug, basic_auth=self.basic_auth, + timeout=self.timeout, + retries=self.retries, ) response = client.get(url=url, **kwargs) diff --git a/st2client/st2client/config_parser.py b/st2client/st2client/config_parser.py index da181425c2..8caa1c86b8 100644 --- a/st2client/st2client/config_parser.py +++ b/st2client/st2client/config_parser.py @@ -47,6 +47,10 @@ "base_url": {"type": "string", "default": None}, "api_version": {"type": "string", "default": None}, "cacert": {"type": "string", "default": None}, + # Seconds to wait for the StackStorm API, both to connect and for each reply + "http_timeout": {"type": "float", "default": None}, + # How many times a failed HTTP request to the StackStorm API is retried + "http_retries": {"type": "int", "default": None}, "silence_ssl_warnings": {"type": "bool", "default": False}, "silence_schema_output": {"type": "bool", "default": True}, }, diff --git a/st2client/st2client/models/core.py b/st2client/st2client/models/core.py index 633e57911f..fd9f59d54d 100644 --- a/st2client/st2client/models/core.py +++ b/st2client/st2client/models/core.py @@ -185,6 +185,8 @@ def __init__( cacert: Optional[str] = None, debug: bool = False, basic_auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + retries: Optional[int] = None, ): """ :param resource: Name of the resource to operate on. @@ -193,6 +195,8 @@ def __init__( :param debug: True to enable debug mode where additional debug information will be logged. :param basic_auth: Optional additional basic auth credentials in tuple(username, password) notation. + :param timeout: Optional number of seconds to wait for the server (see HTTPClient). + :param retries: Optional number of times a failed request is retried (see HTTPClient). """ self.resource = resource self.endpoint = endpoint @@ -200,7 +204,12 @@ def __init__( self.debug = debug self.basic_auth = basic_auth self.client = httpclient.HTTPClient( - endpoint, cacert=cacert, debug=debug, basic_auth=basic_auth + endpoint, + cacert=cacert, + debug=debug, + basic_auth=basic_auth, + timeout=timeout, + retries=retries, ) @staticmethod @@ -739,13 +748,23 @@ def match(self, instance, **kwargs): class StreamManager(ResourceManager): - def __init__(self, endpoint, cacert=None, debug=False, basic_auth=None): + def __init__( + self, + endpoint, + cacert=None, + debug=False, + basic_auth=None, + timeout=None, + retries=None, + ): super(StreamManager, self).__init__( resource=None, endpoint=endpoint, cacert=cacert, debug=debug, basic_auth=basic_auth, + timeout=timeout, + retries=retries, ) self._url = httpclient.get_url_without_trailing_slash(endpoint) + "/stream" @@ -798,12 +817,19 @@ def listen(self, events=None, **kwargs): class WorkflowManager(object): - def __init__(self, endpoint, cacert, debug, basic_auth=None): + def __init__( + self, endpoint, cacert, debug, basic_auth=None, timeout=None, retries=None + ): self.debug = debug self.cacert = cacert self.endpoint = endpoint + "/workflows" self.client = httpclient.HTTPClient( - root=self.endpoint, cacert=cacert, debug=debug, basic_auth=basic_auth + root=self.endpoint, + cacert=cacert, + debug=debug, + basic_auth=basic_auth, + timeout=timeout, + retries=retries, ) @staticmethod diff --git a/st2client/st2client/shell.py b/st2client/st2client/shell.py index 8725ce66ba..e9567b162b 100755 --- a/st2client/st2client/shell.py +++ b/st2client/st2client/shell.py @@ -67,6 +67,8 @@ from st2client.commands.auth import TokenCreateCommand from st2client.commands.auth import LoginCommand from st2client.utils.profiler import setup_regular_profiler +from st2client.utils.httpclient import DEFAULT_HTTP_CONNECT_TIMEOUT +from st2client.utils.httpclient import DEFAULT_HTTP_RETRIES __all__ = ["Shell"] @@ -251,6 +253,31 @@ def __init__(self): "If this is not provided, then SSL cert will not be verified.", ) + self.parser.add_argument( + "--http-timeout", + action="store", + dest="http_timeout", + type=float, + default=None, + help="Seconds to wait for the StackStorm API, both to connect and for each " + "reply. Get ST2_HTTP_TIMEOUT from the environment variables by default. " + "If this is not provided, connecting times out after %s seconds and there " + "is no limit on waiting for a reply." % (DEFAULT_HTTP_CONNECT_TIMEOUT), + ) + + self.parser.add_argument( + "--http-retries", + action="store", + dest="http_retries", + type=int, + default=None, + help="How many times a failed request is retried. Connection errors are " + "retried for all requests, timeouts and 502 / 503 / 504 responses only for " + "requests that are safe to send again (not POST). Get ST2_HTTP_RETRIES from " + "the environment variables by default. Defaults to %s, 0 disables retrying." + % (DEFAULT_HTTP_RETRIES), + ) + self.parser.add_argument( "--basic-auth", action="store", diff --git a/st2client/st2client/utils/httpclient.py b/st2client/st2client/utils/httpclient.py index 99b4bbfa8a..1fa4e371d9 100644 --- a/st2client/st2client/utils/httpclient.py +++ b/st2client/st2client/utils/httpclient.py @@ -15,15 +15,81 @@ from __future__ import absolute_import +import http.cookiejar import json import logging from shlex import quote import requests +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry LOG = logging.getLogger(__name__) +# How many times a failed request is retried before the error is reported. +DEFAULT_HTTP_RETRIES = 3 + +# Seconds to wait while connecting to the StackStorm server. There is no default limit on +# waiting for the reply, because some API calls (e.g. installing a pack) are slow on purpose. +DEFAULT_HTTP_CONNECT_TIMEOUT = 10 + +# The first retry happens at once, then the waits double: 1s, 2s, 4s, ... +DEFAULT_HTTP_RETRY_BACKOFF_FACTOR = 0.5 + +# Never wait longer than this between retries, even if the server's Retry-After asks for more. +MAX_HTTP_RETRY_AFTER = 30 + +# Sending these again can't create anything twice on the server. POST and PATCH are left out: +# a POST that timed out may already have started an execution. +IDEMPOTENT_METHODS = frozenset(["DELETE", "GET", "HEAD", "OPTIONS", "PUT"]) + +# "Temporarily unavailable" answers from the server, or from a proxy in front of it. +RETRY_STATUS_CODES = frozenset([502, 503, 504]) + + +class HTTPRetry(Retry): + """ + urllib3 Retry which caps how long a Retry-After header can make the client wait. + """ + + def parse_retry_after(self, retry_after): + return min( + super(HTTPRetry, self).parse_retry_after(retry_after), MAX_HTTP_RETRY_AFTER + ) + + +def get_http_retry(retries, backoff_factor=None): + """ + Return the retry rules used for every request made by HTTPClient. + + - Connection errors are retried for every method: the request never reached the server. + - Read errors and 502 / 503 / 504 responses are only retried for idempotent methods. + - Other errors (e.g. an invalid SSL certificate) are not retried, retrying wouldn't help. + - When the retries run out on a bad status code, the last response is returned (not raised), + so callers report the error exactly as they did before retries existed. + + :param retries: How many times to retry. 0 disables retrying. + :type retries: ``int`` + + :param backoff_factor: Defaults to DEFAULT_HTTP_RETRY_BACKOFF_FACTOR. + :type backoff_factor: ``float`` + + :rtype: :class:`urllib3.util.retry.Retry` + """ + if backoff_factor is None: + backoff_factor = DEFAULT_HTTP_RETRY_BACKOFF_FACTOR + + return HTTPRetry( + total=retries, + other=0, + allowed_methods=IDEMPOTENT_METHODS, + status_forcelist=RETRY_STATUS_CODES, + backoff_factor=backoff_factor, + respect_retry_after_header=True, + raise_on_status=False, + ) + def add_ssl_verify_to_kwargs(func): def decorate(*args, **kwargs): @@ -35,6 +101,20 @@ def decorate(*args, **kwargs): return decorate +def add_timeout_to_kwargs(func): + """ + Add the HTTPClient's "timeout" to the kwargs passed to the requests method, unless the + caller passed one. + """ + + def decorate(*args, **kwargs): + if isinstance(args[0], HTTPClient): + kwargs.setdefault("timeout", args[0].timeout) + return func(*args, **kwargs) + + return decorate + + def add_basic_auth_creds_to_kwargs(func): """ Add "auth" tuple parameter to the kwargs object which is passed to requests method in case it's @@ -107,60 +187,106 @@ def get_url_without_trailing_slash(value): class HTTPClient(object): - def __init__(self, root, cacert=None, debug=False, basic_auth=None): + def __init__( + self, + root, + cacert=None, + debug=False, + basic_auth=None, + timeout=None, + retries=None, + ): + """ + :param timeout: Seconds to wait for the server, both to connect and for each reply. + Defaults to DEFAULT_HTTP_CONNECT_TIMEOUT to connect and no limit on + the reply. + :type timeout: ``float`` + + :param retries: How many times a failed request is retried. Defaults to + DEFAULT_HTTP_RETRIES. 0 disables retrying. + :type retries: ``int`` + """ self.root = get_url_without_trailing_slash(root) self.cacert = cacert self.debug = debug self.basic_auth = basic_auth + if timeout is None: + # (connect timeout, read timeout) + timeout = (DEFAULT_HTTP_CONNECT_TIMEOUT, None) + self.timeout = timeout + + self.retries = retries if retries is not None else DEFAULT_HTTP_RETRIES + self.session = self._get_session() + + def _get_session(self): + session = requests.Session() + + # Keep requests independent of each other, as they were before a session was used: + # don't store cookies the API sets (e.g. auth-token) and send them on later requests. + session.cookies.set_policy( + http.cookiejar.DefaultCookiePolicy(allowed_domains=[]) + ) + + adapter = HTTPAdapter(max_retries=get_http_retry(self.retries)) + session.mount("http://", adapter) + session.mount("https://", adapter) + return session + @add_ssl_verify_to_kwargs + @add_timeout_to_kwargs @add_auth_token_to_headers @add_basic_auth_creds_to_kwargs def get(self, url, **kwargs): - response = requests.get(self.root + url, **kwargs) + response = self.session.get(self.root + url, **kwargs) response = self._response_hook(response=response) return response @add_ssl_verify_to_kwargs + @add_timeout_to_kwargs @add_auth_token_to_headers @add_json_content_type_to_headers @add_basic_auth_creds_to_kwargs def post(self, url, data, **kwargs): - response = requests.post(self.root + url, json.dumps(data), **kwargs) + response = self.session.post(self.root + url, json.dumps(data), **kwargs) response = self._response_hook(response=response) return response @add_ssl_verify_to_kwargs + @add_timeout_to_kwargs @add_auth_token_to_headers @add_basic_auth_creds_to_kwargs def post_raw(self, url, data, **kwargs): - response = requests.post(self.root + url, data, **kwargs) + response = self.session.post(self.root + url, data, **kwargs) response = self._response_hook(response=response) return response @add_ssl_verify_to_kwargs + @add_timeout_to_kwargs @add_auth_token_to_headers @add_json_content_type_to_headers @add_basic_auth_creds_to_kwargs def put(self, url, data, **kwargs): - response = requests.put(self.root + url, json.dumps(data), **kwargs) + response = self.session.put(self.root + url, json.dumps(data), **kwargs) response = self._response_hook(response=response) return response @add_ssl_verify_to_kwargs + @add_timeout_to_kwargs @add_auth_token_to_headers @add_json_content_type_to_headers @add_basic_auth_creds_to_kwargs def patch(self, url, data, **kwargs): - response = requests.patch(self.root + url, data, **kwargs) + response = self.session.patch(self.root + url, data, **kwargs) response = self._response_hook(response=response) return response @add_ssl_verify_to_kwargs + @add_timeout_to_kwargs @add_auth_token_to_headers @add_basic_auth_creds_to_kwargs def delete(self, url, **kwargs): - response = requests.delete(self.root + url, **kwargs) + response = self.session.delete(self.root + url, **kwargs) response = self._response_hook(response=response) return response diff --git a/st2client/tests/fixtures/st2rc.full.ini b/st2client/tests/fixtures/st2rc.full.ini index b55bd619d0..b1b8511136 100644 --- a/st2client/tests/fixtures/st2rc.full.ini +++ b/st2client/tests/fixtures/st2rc.full.ini @@ -2,6 +2,8 @@ base_url = http://127.0.0.1 api_version = v1 cacert = cacartpath +http_timeout = 30.5 +http_retries = 5 [cli] debug = True diff --git a/st2client/tests/unit/test_auth.py b/st2client/tests/unit/test_auth.py index e59b31dfaf..b71bba1290 100644 --- a/st2client/tests/unit/test_auth.py +++ b/st2client/tests/unit/test_auth.py @@ -30,6 +30,7 @@ from st2client.models.core import add_auth_token_to_kwargs_from_env from st2client.commands.resource import add_auth_token_to_kwargs_from_cli from st2client.utils.httpclient import ( + DEFAULT_HTTP_CONNECT_TIMEOUT, add_auth_token_to_headers, add_json_content_type_to_headers, ) @@ -37,6 +38,9 @@ LOG = logging.getLogger(__name__) +# Timeout HTTPClient passes to requests when none is configured: (connect, read) +HTTP_TIMEOUT = (DEFAULT_HTTP_CONNECT_TIMEOUT, None) + if six.PY3: RULE = { "name": "drule", @@ -130,7 +134,7 @@ class TestLoginPasswordAndConfig(TestLoginBase): } @mock.patch.object( - requests, + requests.Session, "post", mock.MagicMock(return_value=base.FakeResponse(json.dumps(TOKEN), 200, "OK")), ) @@ -178,12 +182,12 @@ class TestLoginIntPwdAndConfig(TestLoginBase): } @mock.patch.object( - requests, + requests.Session, "post", mock.MagicMock(return_value=base.FakeResponse(json.dumps(TOKEN), 200, "OK")), ) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock(return_value=base.FakeResponse(json.dumps({}), 200, "OK")), ) @@ -202,8 +206,11 @@ def runTest(self, mock_gp): "headers": {"content-type": "application/json"}, "auth": ("st2admin", "Password1!"), } - requests.post.assert_called_with( - "http://127.0.0.1:9100/tokens", "{}", **expected_kwargs + requests.Session.post.assert_called_with( + "http://127.0.0.1:9100/tokens", + "{}", + timeout=HTTP_TIMEOUT, + **expected_kwargs, ) # Check file permissions @@ -232,8 +239,8 @@ def runTest(self, mock_gp): "headers": {"X-Auth-Token": self.TOKEN["token"]}, "params": {"include_attributes": "ref,name,description,version,author"}, } - requests.get.assert_called_with( - "http://127.0.0.1:9101/v1/packs", **expected_kwargs + requests.Session.get.assert_called_with( + "http://127.0.0.1:9101/v1/packs", timeout=HTTP_TIMEOUT, **expected_kwargs ) @@ -250,7 +257,7 @@ class TestLoginWritePwdOkay(TestLoginBase): } @mock.patch.object( - requests, + requests.Session, "post", mock.MagicMock(return_value=base.FakeResponse(json.dumps(TOKEN), 200, "OK")), ) @@ -301,7 +308,7 @@ class TestLoginUncaughtException(TestLoginBase): } @mock.patch.object( - requests, + requests.Session, "post", mock.MagicMock(return_value=base.FakeResponse(json.dumps(TOKEN), 200, "OK")), ) @@ -413,7 +420,7 @@ def test_decorate_without_auth_token_to_http_headers(self): self.assertDictEqual(kwargs["headers"], expected) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock(return_value=base.FakeResponse(json.dumps({}), 200, "OK")), ) @@ -427,23 +434,23 @@ def test_decorate_resource_list(self): # Test without token. self.shell.run(["rule", "list"]) kwargs = {} - requests.get.assert_called_with(url, **kwargs) + requests.Session.get.assert_called_with(url, timeout=HTTP_TIMEOUT, **kwargs) # Test with token from cli. token = uuid.uuid4().hex self.shell.run(["rule", "list", "-t", token]) kwargs = {"headers": {"X-Auth-Token": token}} - requests.get.assert_called_with(url, **kwargs) + requests.Session.get.assert_called_with(url, timeout=HTTP_TIMEOUT, **kwargs) # Test with token from env. token = uuid.uuid4().hex os.environ["ST2_AUTH_TOKEN"] = token self.shell.run(["rule", "list"]) kwargs = {"headers": {"X-Auth-Token": token}} - requests.get.assert_called_with(url, **kwargs) + requests.Session.get.assert_called_with(url, timeout=HTTP_TIMEOUT, **kwargs) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock(return_value=base.FakeResponse(json.dumps(RULE), 200, "OK")), ) @@ -454,23 +461,23 @@ def test_decorate_resource_get(self): # Test without token. self.shell.run(["rule", "get", rule_ref]) kwargs = {} - requests.get.assert_called_with(url, **kwargs) + requests.Session.get.assert_called_with(url, timeout=HTTP_TIMEOUT, **kwargs) # Test with token from cli. token = uuid.uuid4().hex self.shell.run(["rule", "get", rule_ref, "-t", token]) kwargs = {"headers": {"X-Auth-Token": token}} - requests.get.assert_called_with(url, **kwargs) + requests.Session.get.assert_called_with(url, timeout=HTTP_TIMEOUT, **kwargs) # Test with token from env. token = uuid.uuid4().hex os.environ["ST2_AUTH_TOKEN"] = token self.shell.run(["rule", "get", rule_ref]) kwargs = {"headers": {"X-Auth-Token": token}} - requests.get.assert_called_with(url, **kwargs) + requests.Session.get.assert_called_with(url, timeout=HTTP_TIMEOUT, **kwargs) @mock.patch.object( - requests, + requests.Session, "post", mock.MagicMock(return_value=base.FakeResponse(json.dumps(RULE), 200, "OK")), ) @@ -486,7 +493,9 @@ def test_decorate_resource_post(self): # Test without token. self.shell.run(["rule", "create", path]) kwargs = {"headers": {"content-type": "application/json"}} - requests.post.assert_called_with(url, json.dumps(data), **kwargs) + requests.Session.post.assert_called_with( + url, json.dumps(data), timeout=HTTP_TIMEOUT, **kwargs + ) # Test with token from cli. token = uuid.uuid4().hex @@ -494,7 +503,9 @@ def test_decorate_resource_post(self): kwargs = { "headers": {"content-type": "application/json", "X-Auth-Token": token} } - requests.post.assert_called_with(url, json.dumps(data), **kwargs) + requests.Session.post.assert_called_with( + url, json.dumps(data), timeout=HTTP_TIMEOUT, **kwargs + ) # Test with token from env. token = uuid.uuid4().hex @@ -503,18 +514,20 @@ def test_decorate_resource_post(self): kwargs = { "headers": {"content-type": "application/json", "X-Auth-Token": token} } - requests.post.assert_called_with(url, json.dumps(data), **kwargs) + requests.Session.post.assert_called_with( + url, json.dumps(data), timeout=HTTP_TIMEOUT, **kwargs + ) finally: os.close(fd) os.unlink(path) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock(return_value=base.FakeResponse(json.dumps(RULE), 200, "OK")), ) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock(return_value=base.FakeResponse(json.dumps(RULE), 200, "OK")), ) @@ -537,45 +550,57 @@ def test_decorate_resource_put(self): # Test without token. self.shell.run(["rule", "update", rule_ref, path]) kwargs = {} - requests.get.assert_called_with(get_url, **kwargs) + requests.Session.get.assert_called_with( + get_url, timeout=HTTP_TIMEOUT, **kwargs + ) kwargs = {"headers": {"content-type": "application/json"}} - requests.put.assert_called_with(put_url, json.dumps(RULE), **kwargs) + requests.Session.put.assert_called_with( + put_url, json.dumps(RULE), timeout=HTTP_TIMEOUT, **kwargs + ) # Test with token from cli. token = uuid.uuid4().hex self.shell.run(["rule", "update", rule_ref, path, "-t", token]) kwargs = {"headers": {"X-Auth-Token": token}} - requests.get.assert_called_with(get_url, **kwargs) + requests.Session.get.assert_called_with( + get_url, timeout=HTTP_TIMEOUT, **kwargs + ) kwargs = { "headers": {"content-type": "application/json", "X-Auth-Token": token} } - requests.put.assert_called_with(put_url, json.dumps(RULE), **kwargs) + requests.Session.put.assert_called_with( + put_url, json.dumps(RULE), timeout=HTTP_TIMEOUT, **kwargs + ) # Test with token from env. token = uuid.uuid4().hex os.environ["ST2_AUTH_TOKEN"] = token self.shell.run(["rule", "update", rule_ref, path]) kwargs = {"headers": {"X-Auth-Token": token}} - requests.get.assert_called_with(get_url, **kwargs) + requests.Session.get.assert_called_with( + get_url, timeout=HTTP_TIMEOUT, **kwargs + ) # Note: We parse the payload because data might not be in the same # order as the fixture kwargs = { "headers": {"content-type": "application/json", "X-Auth-Token": token} } - requests.put.assert_called_with(put_url, json.dumps(RULE), **kwargs) + requests.Session.put.assert_called_with( + put_url, json.dumps(RULE), timeout=HTTP_TIMEOUT, **kwargs + ) finally: os.close(fd) os.unlink(path) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock(return_value=base.FakeResponse(json.dumps(RULE), 200, "OK")), ) @mock.patch.object( - requests, + requests.Session, "delete", mock.MagicMock(return_value=base.FakeResponse("", 204, "OK")), ) @@ -587,20 +612,26 @@ def test_decorate_resource_delete(self): # Test without token. self.shell.run(["rule", "delete", rule_ref]) kwargs = {} - requests.get.assert_called_with(get_url, **kwargs) - requests.delete.assert_called_with(del_url, **kwargs) + requests.Session.get.assert_called_with(get_url, timeout=HTTP_TIMEOUT, **kwargs) + requests.Session.delete.assert_called_with( + del_url, timeout=HTTP_TIMEOUT, **kwargs + ) # Test with token from cli. token = uuid.uuid4().hex self.shell.run(["rule", "delete", rule_ref, "-t", token]) kwargs = {"headers": {"X-Auth-Token": token}} - requests.get.assert_called_with(get_url, **kwargs) - requests.delete.assert_called_with(del_url, **kwargs) + requests.Session.get.assert_called_with(get_url, timeout=HTTP_TIMEOUT, **kwargs) + requests.Session.delete.assert_called_with( + del_url, timeout=HTTP_TIMEOUT, **kwargs + ) # Test with token from env. token = uuid.uuid4().hex os.environ["ST2_AUTH_TOKEN"] = token self.shell.run(["rule", "delete", rule_ref]) kwargs = {"headers": {"X-Auth-Token": token}} - requests.get.assert_called_with(get_url, **kwargs) - requests.delete.assert_called_with(del_url, **kwargs) + requests.Session.get.assert_called_with(get_url, timeout=HTTP_TIMEOUT, **kwargs) + requests.Session.delete.assert_called_with( + del_url, timeout=HTTP_TIMEOUT, **kwargs + ) diff --git a/st2client/tests/unit/test_client.py b/st2client/tests/unit/test_client.py index 11e9206056..9403a7640a 100644 --- a/st2client/tests/unit/test_client.py +++ b/st2client/tests/unit/test_client.py @@ -26,12 +26,16 @@ from st2client import models from st2client.client import Client +from st2client.utils.httpclient import DEFAULT_HTTP_CONNECT_TIMEOUT from tests import base LOG = logging.getLogger(__name__) +# Timeout HTTPClient passes to requests when none is configured: (connect, read) +HTTP_TIMEOUT = (DEFAULT_HTTP_CONNECT_TIMEOUT, None) + NONRESOURCES = ["workflows"] @@ -73,7 +77,7 @@ def test_default(self): self.assertEqual(endpoints["stream"], stream_url) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock(return_value=base.FakeResponse(json.dumps({}), 200, "OK")), ) @@ -81,16 +85,19 @@ def test_basic_auth_option_success(self): client = Client(basic_auth="username:password") self.assertEqual(client.basic_auth, ("username", "password")) - self.assertEqual(requests.get.call_count, 0) + self.assertEqual(requests.Session.get.call_count, 0) client.actions.get_all() - self.assertEqual(requests.get.call_count, 1) + self.assertEqual(requests.Session.get.call_count, 1) - requests.get.assert_called_with( - "http://127.0.0.1:9101/v1/actions", auth=("username", "password"), params={} + requests.Session.get.assert_called_with( + "http://127.0.0.1:9101/v1/actions", + auth=("username", "password"), + params={}, + timeout=HTTP_TIMEOUT, ) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock(return_value=base.FakeResponse(json.dumps({}), 200, "OK")), ) @@ -98,14 +105,15 @@ def test_basic_auth_option_success_password_with_colon(self): client = Client(basic_auth="username:password:with:colon") self.assertEqual(client.basic_auth, ("username", "password:with:colon")) - self.assertEqual(requests.get.call_count, 0) + self.assertEqual(requests.Session.get.call_count, 0) client.actions.get_all() - self.assertEqual(requests.get.call_count, 1) + self.assertEqual(requests.Session.get.call_count, 1) - requests.get.assert_called_with( + requests.Session.get.assert_called_with( "http://127.0.0.1:9101/v1/actions", auth=("username", "password:with:colon"), params={}, + timeout=HTTP_TIMEOUT, ) def test_basic_auth_option_invalid_notation(self): diff --git a/st2client/tests/unit/test_config_parser.py b/st2client/tests/unit/test_config_parser.py index e06f2f4b45..b3cd4e25f3 100644 --- a/st2client/tests/unit/test_config_parser.py +++ b/st2client/tests/unit/test_config_parser.py @@ -61,6 +61,8 @@ def test_parse(self): "base_url": "http://127.0.0.1", "api_version": "v1", "cacert": "cacartpath", + "http_timeout": 30.5, + "http_retries": 5, "silence_ssl_warnings": False, "silence_schema_output": True, }, diff --git a/st2client/tests/unit/test_httpclient.py b/st2client/tests/unit/test_httpclient.py new file mode 100644 index 0000000000..3e2e54f055 --- /dev/null +++ b/st2client/tests/unit/test_httpclient.py @@ -0,0 +1,396 @@ +# Copyright 2026 The StackStorm Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Tests for the timeout and retry behaviour of st2client's HTTP client. + +The retry tests talk to a real (tiny) HTTP server running in a thread, so they check what +actually goes over the wire: how many requests the server received. +""" + +from __future__ import absolute_import + +import os +import socket +import tempfile +import threading +import time +import unittest +from http.server import BaseHTTPRequestHandler +from http.server import ThreadingHTTPServer + +import mock +import requests +from urllib3.util.retry import Retry + +from st2client import shell +from st2client.client import Client +from st2client.utils import httpclient +from st2client.utils.httpclient import HTTPClient +from st2client.utils.httpclient import HTTPRetry + + +class ScriptedRequestHandler(BaseHTTPRequestHandler): + """ + Answers with the next status code from the server's script (200 when it runs out) and + counts the requests it receives. + """ + + def _handle(self): + server = self.server + server.hits += 1 + server.cookies.append(self.headers.get("Cookie")) + + length = int(self.headers.get("Content-Length") or 0) + self.rfile.read(length) + + if server.delay: + time.sleep(server.delay) + + status = server.statuses.pop(0) if server.statuses else 200 + body = b"{}" + self.send_response(status) + for name, value in server.response_headers.items(): + self.send_header(name, value) + self.send_header("Set-Cookie", "auth-token=secret") + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + + try: + self.wfile.write(body) + except (BrokenPipeError, ConnectionResetError): + # The client gave up waiting (read timeout tests) + pass + + do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = _handle + + def log_message(self, *args): + pass + + +class HTTPClientRetryTestCase(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = ThreadingHTTPServer(("127.0.0.1", 0), ScriptedRequestHandler) + cls.server.daemon_threads = True + cls.thread = threading.Thread(target=cls.server.serve_forever, daemon=True) + cls.thread.start() + cls.url = "http://127.0.0.1:%s" % (cls.server.server_port) + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + + def setUp(self): + super(HTTPClientRetryTestCase, self).setUp() + + # Retry immediately, so the tests don't sleep + patcher = mock.patch.object(httpclient, "DEFAULT_HTTP_RETRY_BACKOFF_FACTOR", 0) + patcher.start() + self.addCleanup(patcher.stop) + + self.script() + + def script(self, statuses=None, delay=0, headers=None): + self.server.statuses = list(statuses or []) + self.server.delay = delay + self.server.response_headers = headers or {} + self.server.hits = 0 + self.server.cookies = [] + + def test_get_is_retried_until_it_succeeds(self): + self.script(statuses=[503, 503]) + + response = HTTPClient(self.url).get("/v1/actions") + + self.assertEqual(response.status_code, 200) + self.assertEqual(self.server.hits, 3) + + def test_idempotent_methods_are_retried_on_502_503_504(self): + client = HTTPClient(self.url) + calls = [ + ("GET", lambda: client.get("/v1/actions")), + ("PUT", lambda: client.put("/v1/actions/1", {})), + ("DELETE", lambda: client.delete("/v1/actions/1")), + ] + + for status in [502, 503, 504]: + for method, call in calls: + self.script(statuses=[status]) + response = call() + self.assertEqual(response.status_code, 200, (method, status)) + self.assertEqual(self.server.hits, 2, (method, status)) + + def test_last_response_is_returned_when_retries_run_out(self): + self.script(statuses=[503] * 10) + + response = HTTPClient(self.url).get("/v1/actions") + + # Callers handle the error response exactly as they did before retries existed + self.assertEqual(response.status_code, 503) + self.assertEqual(self.server.hits, 1 + httpclient.DEFAULT_HTTP_RETRIES) + + def test_post_and_patch_are_never_sent_twice(self): + client = HTTPClient(self.url) + calls = [ + ("POST", lambda: client.post("/v1/executions", {})), + ("POST raw", lambda: client.post_raw("/v1/executions", "{}")), + ("PATCH", lambda: client.patch("/v1/executions/1", "{}")), + ] + + for method, call in calls: + self.script(statuses=[503, 503]) + response = call() + self.assertEqual(response.status_code, 503, method) + self.assertEqual(self.server.hits, 1, method) + + def test_other_error_status_codes_are_not_retried(self): + client = HTTPClient(self.url) + + for status in [400, 401, 404, 500]: + self.script(statuses=[status]) + response = client.get("/v1/actions") + self.assertEqual(response.status_code, status) + self.assertEqual(self.server.hits, 1, status) + + def test_custom_number_of_retries(self): + self.script(statuses=[503] * 10) + + response = HTTPClient(self.url, retries=1).get("/v1/actions") + + self.assertEqual(response.status_code, 503) + self.assertEqual(self.server.hits, 2) + + def test_zero_retries_disables_retrying(self): + self.script(statuses=[503]) + + response = HTTPClient(self.url, retries=0).get("/v1/actions") + + self.assertEqual(response.status_code, 503) + self.assertEqual(self.server.hits, 1) + + def test_read_timeout_is_retried_for_get(self): + self.script(delay=0.5) + + client = HTTPClient(self.url, timeout=0.1, retries=1) + self.assertRaises( + requests.exceptions.ConnectionError, client.get, "/v1/actions" + ) + self.assertEqual(self.server.hits, 2) + + def test_read_timeout_is_not_retried_for_post(self): + self.script(delay=0.5) + + client = HTTPClient(self.url, timeout=0.1) + self.assertRaises( + requests.exceptions.ReadTimeout, client.post, "/v1/executions", {} + ) + self.assertEqual(self.server.hits, 1) + + def test_retry_after_header_is_respected_but_capped(self): + self.script(statuses=[503], headers={"Retry-After": "3600"}) + + with mock.patch.object(httpclient, "MAX_HTTP_RETRY_AFTER", 0.2): + start = time.time() + response = HTTPClient(self.url).get("/v1/actions") + elapsed = time.time() - start + + self.assertEqual(response.status_code, 200) + self.assertEqual(self.server.hits, 2) + self.assertGreaterEqual(elapsed, 0.2) + self.assertLess(elapsed, 5) + + def test_cookies_set_by_the_api_are_not_sent_back(self): + client = HTTPClient(self.url) + + client.get("/v1/actions") + client.get("/v1/actions") + + self.assertEqual(self.server.cookies, [None, None]) + + +class HTTPClientConnectionErrorTestCase(unittest.TestCase): + def setUp(self): + super(HTTPClientConnectionErrorTestCase, self).setUp() + + patcher = mock.patch.object(httpclient, "DEFAULT_HTTP_RETRY_BACKOFF_FACTOR", 0) + patcher.start() + self.addCleanup(patcher.stop) + + # A port nothing listens on + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + self.url = "http://127.0.0.1:%s" % (sock.getsockname()[1]) + sock.close() + + def test_connection_errors_are_retried_for_every_method(self): + # The request never reached the server, so sending it again is safe, even for POST + client = HTTPClient(self.url) + calls = [ + ("GET", lambda: client.get("/v1/actions")), + ("POST", lambda: client.post("/v1/executions", {})), + ] + + for method, call in calls: + with mock.patch.object( + HTTPRetry, "increment", autospec=True, side_effect=Retry.increment + ) as increment: + self.assertRaises(requests.exceptions.ConnectionError, call) + + self.assertEqual( + increment.call_count, 1 + httpclient.DEFAULT_HTTP_RETRIES, method + ) + + +class HTTPClientOptionsTestCase(unittest.TestCase): + def test_default_timeout_limits_connecting_only(self): + client = HTTPClient("http://127.0.0.1:9101") + + self.assertEqual( + client.timeout, (httpclient.DEFAULT_HTTP_CONNECT_TIMEOUT, None) + ) + self.assertEqual(client.retries, httpclient.DEFAULT_HTTP_RETRIES) + + @mock.patch.object(requests.Session, "get") + def test_timeout_is_passed_to_requests(self, mock_get): + HTTPClient("http://127.0.0.1:9101", timeout=5).get("/v1/actions") + + mock_get.assert_called_with("http://127.0.0.1:9101/v1/actions", timeout=5) + + @mock.patch.object(requests.Session, "get") + def test_timeout_given_by_the_caller_wins(self, mock_get): + HTTPClient("http://127.0.0.1:9101", timeout=5).get("/v1/actions", timeout=60) + + mock_get.assert_called_with("http://127.0.0.1:9101/v1/actions", timeout=60) + + def test_retry_after_is_capped(self): + retry = HTTPRetry() + + self.assertEqual( + retry.parse_retry_after("3600"), httpclient.MAX_HTTP_RETRY_AFTER + ) + self.assertEqual(retry.parse_retry_after("2"), 2) + + def test_retry_rules(self): + retry = httpclient.get_http_retry(3) + + self.assertEqual(retry.total, 3) + self.assertEqual(retry.other, 0) + self.assertFalse(retry.raise_on_status) + self.assertNotIn("POST", retry.allowed_methods) + self.assertNotIn("PATCH", retry.allowed_methods) + self.assertEqual(set(retry.status_forcelist), {502, 503, 504}) + + +class ClientHTTPOptionsTestCase(unittest.TestCase): + def setUp(self): + super(ClientHTTPOptionsTestCase, self).setUp() + + patcher = mock.patch.dict(os.environ) + patcher.start() + self.addCleanup(patcher.stop) + for name in ["ST2_HTTP_TIMEOUT", "ST2_HTTP_RETRIES"]: + os.environ.pop(name, None) + + def assertHTTPOptions(self, client, timeout, retries): + self.assertEqual(client.timeout, timeout) + self.assertEqual(client.retries, retries) + + # Every manager's HTTP client gets the same options + for name, manager in client.managers.items(): + if timeout is None: + expected_timeout = (httpclient.DEFAULT_HTTP_CONNECT_TIMEOUT, None) + else: + expected_timeout = timeout + if retries is None: + expected_retries = httpclient.DEFAULT_HTTP_RETRIES + else: + expected_retries = retries + + self.assertEqual(manager.client.timeout, expected_timeout, name) + self.assertEqual(manager.client.retries, expected_retries, name) + + def test_defaults(self): + self.assertHTTPOptions(Client(), timeout=None, retries=None) + + def test_arguments(self): + self.assertHTTPOptions(Client(timeout=5, retries=1), timeout=5.0, retries=1) + + def test_environment_variables(self): + os.environ["ST2_HTTP_TIMEOUT"] = "7.5" + os.environ["ST2_HTTP_RETRIES"] = "0" + + self.assertHTTPOptions(Client(), timeout=7.5, retries=0) + + def test_arguments_win_over_environment_variables(self): + os.environ["ST2_HTTP_TIMEOUT"] = "7.5" + os.environ["ST2_HTTP_RETRIES"] = "0" + + self.assertHTTPOptions(Client(timeout=5, retries=1), timeout=5.0, retries=1) + + def test_invalid_values_are_rejected(self): + for timeout in [0, -1, "abc", "nan"]: + self.assertRaisesRegex(ValueError, "HTTP timeout", Client, timeout=timeout) + + for retries in [-1, "abc", "1.5"]: + self.assertRaisesRegex(ValueError, "HTTP retries", Client, retries=retries) + + os.environ["ST2_HTTP_RETRIES"] = "two" + self.assertRaisesRegex(ValueError, "HTTP retries", Client) + + +class ShellHTTPOptionsTestCase(unittest.TestCase): + def setUp(self): + super(ShellHTTPOptionsTestCase, self).setUp() + + patcher = mock.patch.dict(os.environ) + patcher.start() + self.addCleanup(patcher.stop) + for name in ["ST2_HTTP_TIMEOUT", "ST2_HTTP_RETRIES", "ST2_CLI_SKIP_CONFIG"]: + os.environ.pop(name, None) + + self.shell = shell.Shell() + + config_fd, self.config_path = tempfile.mkstemp(suffix=".ini") + with os.fdopen(config_fd, "w") as config_file: + config_file.write("[general]\nhttp_timeout = 30.5\nhttp_retries = 5\n") + self.addCleanup(os.unlink, self.config_path) + + def get_client(self, args): + parsed_args = self.shell.parser.parse_args(args + ["action", "list"]) + return self.shell.get_client(parsed_args) + + def test_cli_arguments(self): + client = self.get_client( + ["--skip-config", "--http-timeout", "2.5", "--http-retries", "0"] + ) + + self.assertEqual(client.timeout, 2.5) + self.assertEqual(client.retries, 0) + + def test_config_file(self): + client = self.get_client(["--config-file", self.config_path]) + + self.assertEqual(client.timeout, 30.5) + self.assertEqual(client.retries, 5) + + def test_cli_arguments_win_over_config_file(self): + client = self.get_client( + ["--config-file", self.config_path, "--http-retries", "1"] + ) + + self.assertEqual(client.timeout, 30.5) + self.assertEqual(client.retries, 1) diff --git a/st2client/tests/unit/test_inquiry.py b/st2client/tests/unit/test_inquiry.py index c8804dae47..719d913552 100644 --- a/st2client/tests/unit/test_inquiry.py +++ b/st2client/tests/unit/test_inquiry.py @@ -126,7 +126,7 @@ def tearDown(self): class TestInquirySubcommands(TestInquiryBase): @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock( return_value=base.FakeResponse(json.dumps(INQUIRY_1), 200, "OK") @@ -140,7 +140,7 @@ def test_get_inquiry(self): self.assertEqual(retcode, 0) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock( return_value=base.FakeResponse(json.dumps({}), 404, "NOT FOUND") @@ -159,7 +159,7 @@ def test_get_inquiry_not_found(self): self.assertEqual(retcode, 1) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock( return_value=( @@ -177,7 +177,7 @@ def test_list_inquiries(self): self.assertEqual(self.stdout.getvalue().count("1440"), 1) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock( return_value=( @@ -201,7 +201,7 @@ def test_list_inquiries_limit(self): ) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock( return_value=( @@ -216,14 +216,14 @@ def test_list_empty_inquiries(self): self.assertEqual(retcode, 0) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock( return_value=(base.FakeResponse(json.dumps(INQUIRY_1), 200, "OK")) ), ) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=( @@ -245,14 +245,14 @@ def test_respond(self, mock_form): self.assertEqual(retcode, 0) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock( return_value=(base.FakeResponse(json.dumps(INQUIRY_1), 200, "OK")) ), ) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=( @@ -271,14 +271,14 @@ def test_respond_response_flag(self): self.assertEqual(retcode, 0) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock( return_value=(base.FakeResponse(json.dumps(INQUIRY_1), 200, "OK")) ), ) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=( @@ -296,7 +296,7 @@ def test_respond_invalid(self): ) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock( return_value=base.FakeResponse(json.dumps({}), 404, "NOT FOUND") @@ -314,7 +314,7 @@ def test_respond_nonexistent_inquiry(self): ) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock( return_value=( diff --git a/st2client/tests/unit/test_keyvalue.py b/st2client/tests/unit/test_keyvalue.py index 955c08738e..9c98b4d7d1 100644 --- a/st2client/tests/unit/test_keyvalue.py +++ b/st2client/tests/unit/test_keyvalue.py @@ -113,7 +113,7 @@ def tearDown(self): class TestKeyValueSet(TestKeyValueBase): @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=base.FakeResponse( @@ -143,7 +143,7 @@ def test_encrypt_and_encrypted_flags_are_mutually_exclusive(self): class TestKeyValueLoad(TestKeyValueBase): @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE), 200, "OK")), ) @@ -162,7 +162,7 @@ def test_load_keyvalue_json(self): os.unlink(path) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock(return_value=base.FakeResponse(json.dumps(KEYVALUE), 200, "OK")), ) @@ -181,7 +181,7 @@ def test_load_keyvalue_yaml(self): os.unlink(path) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=base.FakeResponse(json.dumps(KEYVALUE_USER), 200, "OK") @@ -202,7 +202,7 @@ def test_load_keyvalue_user(self): os.unlink(path) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=base.FakeResponse(json.dumps(KEYVALUE_SECRET), 200, "OK") @@ -223,7 +223,7 @@ def test_load_keyvalue_secret(self): os.unlink(path) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=base.FakeResponse( @@ -246,7 +246,7 @@ def test_load_keyvalue_already_encrypted(self): os.unlink(path) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=base.FakeResponse(json.dumps(KEYVALUE_TTL), 200, "OK") @@ -267,7 +267,7 @@ def test_load_keyvalue_ttl(self): os.unlink(path) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=base.FakeResponse(json.dumps(KEYVALUE_OBJECT), 200, "OK") @@ -294,7 +294,7 @@ def test_load_keyvalue_object(self): os.unlink(path) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=base.FakeResponse(json.dumps(KEYVALUE_OBJECT), 200, "OK") @@ -318,7 +318,7 @@ def test_load_keyvalue_object_fail(self): os.unlink(path) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=base.FakeResponse(json.dumps(KEYVALUE_ALL), 200, "OK") @@ -339,7 +339,7 @@ def test_load_keyvalue_all(self): os.unlink(path) @mock.patch.object( - requests, + requests.Session, "put", mock.MagicMock( return_value=base.FakeResponse(json.dumps(KEYVALUE_ALL), 200, "OK") diff --git a/st2client/tests/unit/test_ssl.py b/st2client/tests/unit/test_ssl.py index 5db836482b..cb227eeda5 100644 --- a/st2client/tests/unit/test_ssl.py +++ b/st2client/tests/unit/test_ssl.py @@ -23,10 +23,14 @@ from tests import base from st2client import shell +from st2client.utils.httpclient import DEFAULT_HTTP_CONNECT_TIMEOUT LOG = logging.getLogger(__name__) +# Timeout HTTPClient passes to requests when none is configured: (connect, read) +HTTP_TIMEOUT = (DEFAULT_HTTP_CONNECT_TIMEOUT, None) + USERNAME = "stanley" PASSWORD = "ShhhDontTell" HEADERS = {"content-type": "application/json"} @@ -70,17 +74,19 @@ def tearDown(self): os.unlink(self.cacert_path) @mock.patch.object( - requests, + requests.Session, "post", mock.MagicMock(return_value=base.FakeResponse(json.dumps({}), 200, "OK")), ) def test_decorate_https_without_cacert(self): self.shell.run(["auth", USERNAME, "-p", PASSWORD]) kwargs = {"verify": False, "headers": HEADERS, "auth": (USERNAME, PASSWORD)} - requests.post.assert_called_with(AUTH_URL, json.dumps({}), **kwargs) + requests.Session.post.assert_called_with( + AUTH_URL, json.dumps({}), timeout=HTTP_TIMEOUT, **kwargs + ) @mock.patch.object( - requests, + requests.Session, "post", mock.MagicMock(return_value=base.FakeResponse(json.dumps({}), 200, "OK")), ) @@ -91,10 +97,12 @@ def test_decorate_https_with_cacert_from_cli(self): "headers": HEADERS, "auth": (USERNAME, PASSWORD), } - requests.post.assert_called_with(AUTH_URL, json.dumps({}), **kwargs) + requests.Session.post.assert_called_with( + AUTH_URL, json.dumps({}), timeout=HTTP_TIMEOUT, **kwargs + ) @mock.patch.object( - requests, + requests.Session, "post", mock.MagicMock(return_value=base.FakeResponse(json.dumps({}), 200, "OK")), ) @@ -106,32 +114,34 @@ def test_decorate_https_with_cacert_from_env(self): "headers": HEADERS, "auth": (USERNAME, PASSWORD), } - requests.post.assert_called_with(AUTH_URL, json.dumps({}), **kwargs) + requests.Session.post.assert_called_with( + AUTH_URL, json.dumps({}), timeout=HTTP_TIMEOUT, **kwargs + ) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock(return_value=base.FakeResponse(json.dumps([]), 200, "OK")), ) def test_decorate_http_without_cacert(self): self.shell.run(["rule", "list"]) - requests.get.assert_called_with(GET_RULES_URL) + requests.Session.get.assert_called_with(GET_RULES_URL, timeout=HTTP_TIMEOUT) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock(return_value=base.FakeResponse(json.dumps({}), 200, "OK")), ) def test_decorate_http_with_cacert_from_cli(self): self.shell.run(["--cacert", self.cacert_path, "rule", "list"]) - requests.get.assert_called_with(GET_RULES_URL) + requests.Session.get.assert_called_with(GET_RULES_URL, timeout=HTTP_TIMEOUT) @mock.patch.object( - requests, + requests.Session, "get", mock.MagicMock(return_value=base.FakeResponse(json.dumps({}), 200, "OK")), ) def test_decorate_http_with_cacert_from_env(self): os.environ["ST2_CACERT"] = self.cacert_path self.shell.run(["rule", "list"]) - requests.get.assert_called_with(GET_RULES_URL) + requests.Session.get.assert_called_with(GET_RULES_URL, timeout=HTTP_TIMEOUT)