| 1 |
# (c) 2012, Michael DeHaan <[email protected]> |
| 2 |
# (c) 2015, 2017 Toshio Kuratomi <[email protected]> |
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = """ |
| 8 |
name: local |
| 9 |
short_description: execute on controller |
| 10 |
description: |
| 11 |
- This connection plugin allows ansible to execute tasks on the Ansible 'controller' instead of on a remote host. |
| 12 |
author: ansible (@core) |
| 13 |
version_added: historical |
| 14 |
options: |
| 15 |
become_success_timeout: |
| 16 |
version_added: '2.19' |
| 17 |
type: int |
| 18 |
default: 10 |
| 19 |
description: |
| 20 |
- Number of seconds to wait for become to succeed when enabled. |
| 21 |
- The default will be used if the configured value is less than 1. |
| 22 |
vars: |
| 23 |
- name: ansible_local_become_success_timeout |
| 24 |
become_strip_preamble: |
| 25 |
version_added: '2.19' |
| 26 |
type: bool |
| 27 |
default: true |
| 28 |
description: |
| 29 |
- Strip internal become output preceding command execution. Disable for additional diagnostics. |
| 30 |
vars: |
| 31 |
- name: ansible_local_become_strip_preamble |
| 32 |
extends_documentation_fragment: |
| 33 |
- connection_pipelining |
| 34 |
notes: |
| 35 |
- The remote user is ignored, the user with which the ansible CLI was executed is used instead. |
| 36 |
""" |
| 37 |
|
| 38 |
import functools |
| 39 |
import getpass |
| 40 |
import os |
| 41 |
import pty |
| 42 |
import selectors |
| 43 |
import shutil |
| 44 |
import subprocess |
| 45 |
import time |
| 46 |
import typing as t |
| 47 |
|
| 48 |
import ansible.constants as C |
| 49 |
from ansible.errors import AnsibleError, AnsibleFileNotFound, AnsibleConnectionFailure |
| 50 |
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text |
| 51 |
from ansible.plugins.connection import ConnectionBase |
| 52 |
from ansible.utils.display import Display |
| 53 |
from ansible.utils.path import unfrackpath |
| 54 |
|
| 55 |
display = Display() |
| 56 |
|
| 57 |
|
| 58 |
class Connection(ConnectionBase): |
| 59 |
""" Local based connections """ |
| 60 |
|
| 61 |
transport = 'local' |
| 62 |
has_pipelining = True |
| 63 |
|
| 64 |
def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: |
| 65 |
|
| 66 |
super(Connection, self).__init__(*args, **kwargs) |
| 67 |
self.cwd = None |
| 68 |
try: |
| 69 |
self.default_user = getpass.getuser() |
| 70 |
except OSError: |
| 71 |
display.vv("Current user (uid=%s) does not seem to exist on this system, leaving user empty." % os.getuid()) |
| 72 |
self.default_user = "" |
| 73 |
|
| 74 |
def _connect(self) -> Connection: |
| 75 |
""" connect to the local host; nothing to do here """ |
| 76 |
|
| 77 |
# Because we haven't made any remote connection we're running as |
| 78 |
# the local user, rather than as whatever is configured in remote_user. |
| 79 |
self._play_context.remote_user = self.default_user |
| 80 |
|
| 81 |
if not self._connected: |
| 82 |
display.vvv(u"ESTABLISH LOCAL CONNECTION FOR USER: {0}".format(self._play_context.remote_user), host=self._play_context.remote_addr) |
| 83 |
self._connected = True |
| 84 |
return self |
| 85 |
|
| 86 |
def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]: |
| 87 |
""" run a command on the local host """ |
| 88 |
|
| 89 |
super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) |
| 90 |
|
| 91 |
display.debug("in local.exec_command()") |
| 92 |
|
| 93 |
executable = C.DEFAULT_EXECUTABLE.split()[0] if C.DEFAULT_EXECUTABLE else None |
| 94 |
|
| 95 |
if not os.path.exists(to_bytes(executable, errors='surrogate_or_strict')): |
| 96 |
raise AnsibleError("failed to find the executable specified %s." |
| 97 |
" Please verify if the executable exists and re-try." % executable) |
| 98 |
|
| 99 |
display.vvv(u"EXEC {0}".format(to_text(cmd)), host=self._play_context.remote_addr) |
| 100 |
display.debug("opening command with Popen()") |
| 101 |
|
| 102 |
if isinstance(cmd, (str, bytes)): |
| 103 |
cmd = to_text(cmd) |
| 104 |
else: |
| 105 |
cmd = map(to_text, cmd) |
| 106 |
|
| 107 |
pty_primary = None |
| 108 |
stdin = subprocess.PIPE |
| 109 |
if sudoable and self.become and self.become.expect_prompt() and not self.get_option('pipelining'): |
| 110 |
# Create a pty if sudoable for privilege escalation that needs it. |
| 111 |
# Falls back to using a standard pipe if this fails, which may |
| 112 |
# cause the command to fail in certain situations where we are escalating |
| 113 |
# privileges or the command otherwise needs a pty. |
| 114 |
try: |
| 115 |
pty_primary, stdin = pty.openpty() |
| 116 |
except OSError as ex: |
| 117 |
display.debug(f"Unable to open pty: {ex}") |
| 118 |
|
| 119 |
p = subprocess.Popen( |
| 120 |
cmd, |
| 121 |
shell=isinstance(cmd, (str, bytes)), |
| 122 |
executable=executable, |
| 123 |
cwd=self.cwd, |
| 124 |
stdin=stdin, |
| 125 |
stdout=subprocess.PIPE, |
| 126 |
stderr=subprocess.PIPE, |
| 127 |
) |
| 128 |
|
| 129 |
# if we created a pty, we can close the other half of the pty now, otherwise primary is stdin |
| 130 |
if pty_primary is not None: |
| 131 |
os.close(stdin) |
| 132 |
|
| 133 |
display.debug("done running command with Popen()") |
| 134 |
|
| 135 |
become_stdout_bytes, become_stderr_bytes = self._ensure_become_success(p, pty_primary, sudoable) |
| 136 |
|
| 137 |
display.debug("getting output with communicate()") |
| 138 |
stdout, stderr = p.communicate(in_data) |
| 139 |
display.debug("done communicating") |
| 140 |
|
| 141 |
# preserve output from privilege escalation stage as `bytes`; it may contain actual output (eg `raw`) or error messages |
| 142 |
stdout = become_stdout_bytes + stdout |
| 143 |
stderr = become_stderr_bytes + stderr |
| 144 |
|
| 145 |
# finally, close the other half of the pty, if it was created |
| 146 |
if pty_primary: |
| 147 |
os.close(pty_primary) |
| 148 |
|
| 149 |
display.debug("done with local.exec_command()") |
| 150 |
return p.returncode, stdout, stderr |
| 151 |
|
| 152 |
def _ensure_become_success(self, p: subprocess.Popen, pty_primary: int, sudoable: bool) -> tuple[bytes, bytes]: |
| 153 |
""" |
| 154 |
Ensure that become succeeds, returning a tuple containing stdout captured after success and all stderr. |
| 155 |
Returns immediately if `self.become` or `sudoable` are False, or `build_become_command` was not called, without performing any additional checks. |
| 156 |
""" |
| 157 |
if not self.become or not sudoable or not self.become._id: # _id is set by build_become_command, if it was not called, assume no become |
| 158 |
return b'', b'' |
| 159 |
|
| 160 |
start_seconds = time.monotonic() |
| 161 |
become_stdout = bytearray() |
| 162 |
become_stderr = bytearray() |
| 163 |
last_stdout_prompt_offset = 0 |
| 164 |
last_stderr_prompt_offset = 0 |
| 165 |
|
| 166 |
# map the buffers to their associated stream for the selector reads |
| 167 |
become_capture = { |
| 168 |
p.stdout: become_stdout, |
| 169 |
p.stderr: become_stderr, |
| 170 |
} |
| 171 |
|
| 172 |
expect_password_prompt = self.become.expect_prompt() |
| 173 |
sent_password = False |
| 174 |
|
| 175 |
def become_error_msg(reason: str) -> str: |
| 176 |
error_message = f'{reason} waiting for become success' |
| 177 |
|
| 178 |
if expect_password_prompt and not sent_password: |
| 179 |
error_message += ' or become password prompt' |
| 180 |
|
| 181 |
error_message += '.' |
| 182 |
|
| 183 |
if become_stdout: |
| 184 |
error_message += f'\n>>> Standard Output\n{to_text(bytes(become_stdout))}' |
| 185 |
|
| 186 |
if become_stderr: |
| 187 |
error_message += f'\n>>> Standard Error\n{to_text(bytes(become_stderr))}' |
| 188 |
|
| 189 |
return error_message |
| 190 |
|
| 191 |
os.set_blocking(p.stdout.fileno(), False) |
| 192 |
os.set_blocking(p.stderr.fileno(), False) |
| 193 |
|
| 194 |
with selectors.DefaultSelector() as selector: |
| 195 |
selector.register(p.stdout, selectors.EVENT_READ, 'stdout') |
| 196 |
selector.register(p.stderr, selectors.EVENT_READ, 'stderr') |
| 197 |
|
| 198 |
while not self.become.check_success(become_stdout): |
| 199 |
if not selector.get_map(): # we only reach end of stream after all descriptors are EOF |
| 200 |
raise AnsibleError(become_error_msg('Premature end of stream')) |
| 201 |
|
| 202 |
if expect_password_prompt and ( |
| 203 |
self.become.check_password_prompt(bytes(become_stdout[last_stdout_prompt_offset:])) or |
| 204 |
self.become.check_password_prompt(bytes(become_stderr[last_stderr_prompt_offset:])) |
| 205 |
): |
| 206 |
if sent_password: |
| 207 |
raise AnsibleError(become_error_msg('Duplicate become password prompt encountered')) |
| 208 |
|
| 209 |
last_stdout_prompt_offset = len(become_stdout) |
| 210 |
last_stderr_prompt_offset = len(become_stderr) |
| 211 |
|
| 212 |
password_to_send = to_bytes(self.become.get_option('become_pass') or '') + b'\n' |
| 213 |
|
| 214 |
if pty_primary is None: |
| 215 |
p.stdin.write(password_to_send) |
| 216 |
p.stdin.flush() |
| 217 |
else: |
| 218 |
os.write(pty_primary, password_to_send) |
| 219 |
|
| 220 |
sent_password = True |
| 221 |
|
| 222 |
remaining_timeout_seconds = self._become_success_timeout - (time.monotonic() - start_seconds) |
| 223 |
events = selector.select(remaining_timeout_seconds) if remaining_timeout_seconds > 0 else [] |
| 224 |
|
| 225 |
if not events: |
| 226 |
# ignoring remaining output after timeout to prevent hanging |
| 227 |
raise AnsibleConnectionFailure(become_error_msg('Timed out')) |
| 228 |
|
| 229 |
# read all content (non-blocking) from streams that signaled available input and append to the associated buffer |
| 230 |
for key, event in events: |
| 231 |
obj = t.cast(t.BinaryIO, key.fileobj) |
| 232 |
|
| 233 |
if chunk := obj.read(): |
| 234 |
become_capture[obj] += chunk |
| 235 |
else: |
| 236 |
selector.unregister(obj) # EOF on this obj, stop polling it |
| 237 |
|
| 238 |
os.set_blocking(p.stdout.fileno(), True) |
| 239 |
os.set_blocking(p.stderr.fileno(), True) |
| 240 |
|
| 241 |
become_stdout_bytes = bytes(become_stdout) |
| 242 |
become_stderr_bytes = bytes(become_stderr) |
| 243 |
|
| 244 |
if self.get_option('become_strip_preamble'): |
| 245 |
become_stdout_bytes = self.become.strip_become_success(self.become.strip_become_prompt(become_stdout_bytes)) |
| 246 |
become_stderr_bytes = self.become.strip_become_prompt(become_stderr_bytes) |
| 247 |
|
| 248 |
return become_stdout_bytes, become_stderr_bytes |
| 249 |
|
| 250 |
@functools.cached_property |
| 251 |
def _become_success_timeout(self) -> int: |
| 252 |
"""Timeout value for become success in seconds.""" |
| 253 |
if (timeout := self.get_option('become_success_timeout')) < 1: |
| 254 |
timeout = C.config.get_config_default('become_success_timeout', plugin_type='connection', plugin_name='local') |
| 255 |
|
| 256 |
return timeout |
| 257 |
|
| 258 |
def put_file(self, in_path: str, out_path: str) -> None: |
| 259 |
""" transfer a file from local to local """ |
| 260 |
|
| 261 |
super(Connection, self).put_file(in_path, out_path) |
| 262 |
|
| 263 |
in_path = unfrackpath(in_path, basedir=self.cwd) |
| 264 |
out_path = unfrackpath(out_path, basedir=self.cwd) |
| 265 |
|
| 266 |
display.vvv(u"PUT {0} TO {1}".format(in_path, out_path), host=self._play_context.remote_addr) |
| 267 |
if not os.path.exists(to_bytes(in_path, errors='surrogate_or_strict')): |
| 268 |
raise AnsibleFileNotFound("file or module does not exist: {0}".format(to_native(in_path))) |
| 269 |
try: |
| 270 |
shutil.copyfile(to_bytes(in_path, errors='surrogate_or_strict'), to_bytes(out_path, errors='surrogate_or_strict')) |
| 271 |
except shutil.Error: |
| 272 |
raise AnsibleError("failed to copy: {0} and {1} are the same".format(to_native(in_path), to_native(out_path))) |
| 273 |
except OSError as ex: |
| 274 |
raise AnsibleError(f"Failed to transfer file to {out_path!r}.") from ex |
| 275 |
|
| 276 |
def fetch_file(self, in_path: str, out_path: str) -> None: |
| 277 |
""" fetch a file from local to local -- for compatibility """ |
| 278 |
|
| 279 |
super(Connection, self).fetch_file(in_path, out_path) |
| 280 |
|
| 281 |
display.vvv(u"FETCH {0} TO {1}".format(in_path, out_path), host=self._play_context.remote_addr) |
| 282 |
self.put_file(in_path, out_path) |
| 283 |
|
| 284 |
def reset(self) -> None: |
| 285 |
pass |
| 286 |
|
| 287 |
def close(self) -> None: |
| 288 |
""" terminate the connection; nothing to do here """ |
| 289 |
self._connected = False |