Debian Codegraph @

ansible_collections/amazon/aws/plugins/plugin_utils/ssm/sessionmanager.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 json
7 import os
8 import select
9 import time
10 from pty import openpty
11 from subprocess import PIPE
12 from subprocess import Popen
13 from typing import Any
14 from typing import Callable
15 from typing import Dict
16 from typing import NoReturn
17 from typing import Optional
18 from typing import Union
19
20 from ansible.errors import AnsibleConnectionFailure
21 from ansible.module_utils.common.text.converters import to_text
22
23 verbosity_display_type = Callable[[int, str], None]
24
25
26 class SSMProcessManagerTimeOutFailure(AnsibleConnectionFailure):
27 pass
28
29
30 def _create_polling_obj(fd: Any) -> Any:
31 """create polling object using select.poll, this is helpful for unit testing"""
32 poller = select.poll()
33 poller.register(fd, select.POLLIN)
34 return poller
35
36
37 class ProcessManager:
38 def __init__(
39 self, instance_id: str, session: Any, stdout: Any, timeout: int, verbosity_display: verbosity_display_type
40 ) -> None:
41 self._session = session
42 self._stdout = stdout
43 self.verbosity_display = verbosity_display
44 self._timeout = timeout
45 self._poller = None
46 self.instance_id = instance_id
47 self._session_id = None
48 self._poller = _create_polling_obj(self._stdout)
49 self._has_timeout = False
50
51 def stdin_write(self, command: Union[bytes, str]) -> None:
52 self._session.stdin.write(command)
53
54 def stdout_read_text(self, size: int = 1024) -> str:
55 return to_text(self._stdout.read(size))
56
57 def stdout_readline(self) -> str:
58 return self._stdout.readline()
59
60 def flush_stderr(self) -> str:
61 """read and return stderr with minimal blocking"""
62
63 poller = _create_polling_obj(self._session.stderr)
64 stderr = ""
65 while self._session.poll() is None:
66 if not poller.poll(1):
67 break
68 line = self._session.stderr.readline()
69 self.verbosity_display(4, f"stderr line: {to_text(line)}")
70 stderr = stderr + line
71 return stderr
72
73 def poll_stdout(self, length: int = 1000) -> bool:
74 return bool(self._poller.poll(length))
75
76 def poll(self, label: str, cmd: str) -> NoReturn:
77 """Poll session to retrieve content from stdout.
78
79 :param label: A label for the display (EXEC, PRE...)
80 :param cmd: The command being executed
81 """
82 start = round(time.time())
83 yield self.poll_stdout()
84 while self._session.poll() is None:
85 remaining = start + self._timeout - round(time.time())
86 self.verbosity_display(4, f"{label} remaining: {remaining} second(s)")
87 if remaining < 0:
88 self._has_timeout = True
89 raise SSMProcessManagerTimeOutFailure(f"{label} command '{cmd}' timeout on host: {self.instance_id}")
90 yield self.poll_stdout()
91
92 def wait_for_match(self, label: str, cmd: Union[str, bytes], match: Union[str, Callable[[str], bool]]) -> None:
93 stdout = ""
94 self.verbosity_display(4, f"{label} WAIT FOR: {match} - Command = {to_text(cmd)}")
95 for result in self.poll(label=label, cmd=to_text(cmd)):
96 if result:
97 text = self.stdout_read_text()
98 self.verbosity_display(4, f"{label} stdout line: \n{text}")
99 stdout += text
100 if isinstance(match, str):
101 if stdout.find(match) != -1:
102 break
103 elif match(stdout):
104 break
105
106 def terminate(self) -> None:
107 if self._has_timeout:
108 self._session.terminate()
109 else:
110 cmd = b"\nexit\n"
111 self._session.communicate(cmd)
112
113
114 class SSMSessionManager:
115 MARK_LENGTH = 26
116
117 def __init__(
118 self, ssm_client: Any, instance_id: str, ssm_timeout: int, verbosity_display: verbosity_display_type
119 ) -> None:
120 self._session_id = None
121 self._instance_id = instance_id
122 self.verbosity_display = verbosity_display
123 self._client = ssm_client
124 self._process_mgr = None
125 self._timeout = ssm_timeout
126 self._session = None
127
128 @property
129 def instance_id(self) -> str:
130 return self._instance_id
131
132 @property
133 def session(self) -> Any:
134 return self._session
135
136 @property
137 def stdout(self) -> Any:
138 return self._stdout
139
140 def __getattr__(self, attr: str) -> Callable:
141 if self._process_mgr and hasattr(self._process_mgr, attr):
142 return getattr(self._process_mgr, attr)
143 raise AttributeError(f"class SSMSessionManager has no attribute '{attr}'")
144
145 def start_session(
146 self,
147 executable: str,
148 document_name: Optional[str],
149 region_name: Optional[str],
150 profile_name: str,
151 parameters: Dict[str, Any] = None,
152 ) -> None:
153 """Start SSM Session manager session and eventually prepare terminal"""
154
155 self.verbosity_display(3, f"ESTABLISH SSM CONNECTION TO: {self.instance_id}")
156 if parameters is None:
157 parameters = {}
158 start_session_args = dict(Target=self.instance_id, Parameters=parameters)
159 if document_name is not None:
160 start_session_args["DocumentName"] = document_name
161 response = self._client.start_session(**start_session_args)
162 self._session_id = response["SessionId"]
163 self.verbosity_display(4, f"SSM CONNECTION ID: {self._session_id}")
164
165 cmd = [
166 executable,
167 json.dumps(response),
168 region_name,
169 "StartSession",
170 profile_name,
171 json.dumps({"Target": self.instance_id}),
172 self._client.meta.endpoint_url,
173 ]
174
175 self.verbosity_display(4, f"SSM COMMAND: {to_text(cmd)}")
176
177 stdout_r, stdout_w = openpty()
178 self._session = Popen(cmd, stdin=PIPE, stdout=stdout_w, stderr=PIPE, close_fds=True, bufsize=0)
179
180 os.close(stdout_w)
181 stdout = os.fdopen(stdout_r, "rb", 0)
182
183 self._process_mgr = ProcessManager(
184 instance_id=self.instance_id,
185 session=self._session,
186 stdout=stdout,
187 timeout=self._timeout,
188 verbosity_display=self.verbosity_display,
189 )
190
191 def terminate(self) -> None:
192 if self._process_mgr:
193 self._process_mgr.terminate()
194 if self._session_id and self._client:
195 try:
196 self._client.terminate_session(SessionId=self._session_id)
197 except ReferenceError:
198 pass
199 self._session_id = None