Debian Codegraph @

ansible_collections/amazon/aws/plugins/plugin_utils/ssm/common.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: Contributors to the Ansible project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 import time
7 from functools import wraps
8 from typing import Any
9 from typing import TypedDict
10
11 from ansible.errors import AnsibleConnectionFailure
12 from ansible.module_utils.common.text.converters import to_text
13
14
15 def ssm_retry(func: Any) -> Any:
16 """
17 Decorator to retry in the case of a connection failure
18 Will retry if:
19 * an exception is caught
20 Will not retry if
21 * remaining_tries is <2
22 * retries limit reached
23 """
24
25 @wraps(func)
26 def wrapped(self, *args: Any, **kwargs: Any) -> Any:
27 reconnection_retries = getattr(self, "reconnection_retries")
28 remaining_tries = int(reconnection_retries) + 1
29 verbosity_d = getattr(self, "verbosity_display", None)
30 cmd_summary = f"{args[0]}..."
31 for attempt in range(remaining_tries):
32 try:
33 return_tuple = func(self, *args, **kwargs)
34 verbosity_d(4, f"ssm_retry: (success) {to_text(return_tuple)}")
35 return return_tuple
36 except (AnsibleConnectionFailure, Exception) as e:
37 if attempt == remaining_tries - 1:
38 raise
39 pause = 2**attempt - 1
40 pause = min(pause, 30)
41
42 if isinstance(e, AnsibleConnectionFailure):
43 msg = f"ssm_retry: attempt: {attempt}, cmd ({cmd_summary}), pausing for {pause} seconds"
44 else:
45 msg = (
46 f"ssm_retry: attempt: {attempt}, caught exception({e})"
47 f"from cmd ({cmd_summary}),pausing for {pause} seconds"
48 )
49
50 verbosity_d(2, msg)
51
52 time.sleep(pause)
53
54 # Do not attempt to reuse the existing session on retries
55 # This will cause the SSM session to be completely restarted,
56 # as well as reinitializing the boto3 clients
57 if hasattr(self, "close"):
58 self.close()
59
60 continue
61
62 return wrapped
63
64
65 class CommandResult(TypedDict):
66 """
67 A dictionary that contains the executed command results.
68 """
69
70 returncode: int
71 stdout: str
72 stderr: str