Debian Codegraph @

ansible_collections/amazon/aws/plugins/plugin_utils/ssm/terminalmanager.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 random
7 import re
8 import string
9
10 from ansible.module_utils.common.text.converters import to_bytes
11 from ansible.module_utils.common.text.converters import to_text
12 from ansible.plugins.shell.powershell import _common_args
13
14
15 class TerminalManager:
16 def __init__(self, connection):
17 self.connection = connection
18
19 def prepare_terminal(self) -> None:
20 """perform any one-time terminal settings"""
21 # No Windows setup for now
22 if self.connection.is_windows:
23 return
24
25 # Ensure SSM Session has started
26 self.ensure_ssm_session_has_started()
27
28 # Disable echo command
29 self.disable_echo_command() # pylint: disable=unreachable
30
31 # Disable prompt command
32 self.disable_prompt_command() # pylint: disable=unreachable
33
34 self.connection.verbosity_display(4, "PRE Terminal configured") # pylint: disable=unreachable
35
36 def wrap_command(self, cmd: str, mark_start: str, mark_end: str) -> str:
37 """Wrap command so stdout and status can be extracted"""
38
39 if self.connection.is_windows:
40 if not cmd.startswith(" ".join(_common_args) + " -EncodedCommand"):
41 cmd = self.connection._shell._encode_script(cmd, preserve_rc=True)
42 cmd = f"{cmd}; echo {mark_start}\necho {mark_end}\n"
43 else:
44 cmd = (
45 f"printf '%s\\n' '{mark_start}';\n"
46 f"echo | {cmd};\n"
47 f"printf '\\n%s\\n%s\\n' \"$?\" '{mark_end}';\n"
48 ) # fmt: skip
49
50 self.connection.verbosity_display(4, f"wrap_command: \n'{to_text(cmd)}'")
51 return cmd
52
53 def disable_echo_command(self) -> None:
54 """Disable echo command from the host"""
55 disable_echo_cmd = to_bytes("stty -echo\n", errors="surrogate_or_strict")
56
57 # Send command
58 self.connection.verbosity_display(4, f"DISABLE ECHO Disabling Prompt: \n{disable_echo_cmd}")
59 self.connection.session_manager.stdin_write(disable_echo_cmd)
60
61 self.connection.session_manager.wait_for_match(label="DISABLE ECHO", cmd=disable_echo_cmd, match="stty -echo")
62
63 def disable_prompt_command(self) -> None:
64 """Disable prompt command from the host"""
65 end_mark = "".join([random.choice(string.ascii_letters) for i in range(self.connection.MARK_LENGTH)])
66 disable_prompt_cmd = to_bytes(
67 "PS1='' ; bind 'set enable-bracketed-paste off'; printf '\\n%s\\n' '" + end_mark + "'\n",
68 errors="surrogate_or_strict",
69 )
70 disable_prompt_reply = re.compile(r"\r\r\n" + re.escape(end_mark) + r"\r\r\n", re.MULTILINE)
71
72 # Send command
73 self.connection.verbosity_display(4, f"DISABLE PROMPT Disabling Prompt: \n{disable_prompt_cmd}")
74 self.connection.session_manager.stdin_write(disable_prompt_cmd)
75
76 self.connection.session_manager.wait_for_match(
77 label="DISABLE PROMPT", cmd=disable_prompt_cmd, match=disable_prompt_reply.search
78 )
79
80 def ensure_ssm_session_has_started(self) -> None:
81 """Ensure the SSM session has started on the host. We poll stdout
82 until we match the following string 'Starting session with SessionId'
83 """
84 self.connection.session_manager.wait_for_match(
85 label="START SSM SESSION", cmd="start_session", match="Starting session with SessionId"
86 )