| 1 |
# (c) 2012-2014, Michael DeHaan <[email protected]> |
| 2 |
# (c) 2015 Toshio Kuratomi <[email protected]> |
| 3 |
# (c) 2017, Peter Sprygada <[email protected]> |
| 4 |
# (c) 2017 Ansible Project |
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import collections.abc as c |
| 8 |
import fcntl |
| 9 |
import os |
| 10 |
import shlex |
| 11 |
import typing as t |
| 12 |
|
| 13 |
from abc import abstractmethod |
| 14 |
from functools import wraps |
| 15 |
|
| 16 |
from ansible import constants as C |
| 17 |
from ansible.errors import AnsibleValueOmittedError |
| 18 |
from ansible.module_utils.common.text.converters import to_text |
| 19 |
from ansible.playbook.play_context import PlayContext |
| 20 |
from ansible.plugins import AnsiblePlugin |
| 21 |
from ansible.plugins.become import BecomeBase |
| 22 |
from ansible.plugins.shell import ShellBase |
| 23 |
from ansible.utils.display import Display |
| 24 |
from ansible.plugins.loader import connection_loader, get_shell_plugin |
| 25 |
from ansible.utils.path import unfrackpath |
| 26 |
|
| 27 |
display = Display() |
| 28 |
|
| 29 |
|
| 30 |
__all__ = ['ConnectionBase', 'ensure_connect'] |
| 31 |
|
| 32 |
BUFSIZE = 65536 |
| 33 |
|
| 34 |
|
| 35 |
class ConnectionKwargs(t.TypedDict): |
| 36 |
task_uuid: str |
| 37 |
ansible_playbook_pid: str |
| 38 |
shell: t.NotRequired[ShellBase] |
| 39 |
|
| 40 |
|
| 41 |
def ensure_connect[T, **P]( |
| 42 |
func: c.Callable[t.Concatenate[ConnectionBase, P], T], |
| 43 |
) -> c.Callable[t.Concatenate[ConnectionBase, P], T]: |
| 44 |
@wraps(func) |
| 45 |
def wrapped(self: ConnectionBase, *args: P.args, **kwargs: P.kwargs) -> T: |
| 46 |
if not self._connected: |
| 47 |
self._connect() |
| 48 |
return func(self, *args, **kwargs) |
| 49 |
return wrapped |
| 50 |
|
| 51 |
|
| 52 |
class ConnectionBase(AnsiblePlugin): |
| 53 |
""" |
| 54 |
A base class for connections to contain common code. |
| 55 |
""" |
| 56 |
|
| 57 |
has_pipelining = False |
| 58 |
|
| 59 |
# The next 2 options are obsolete and should not be set to True. Plugins should instead override |
| 60 |
# is_pipelining_enabled if they need to change the pipelining behaviour. We cannot mark as deprecated yet as some |
| 61 |
# plugins may still need to set these for compatibility with older Ansible versions still in use. |
| 62 |
has_native_async = False |
| 63 |
always_pipeline_modules = False |
| 64 |
|
| 65 |
has_tty = True # for interacting with become plugins |
| 66 |
# When running over this connection type, prefer modules written in a certain language |
| 67 |
# as discovered by the specified file extension. An empty string as the |
| 68 |
# language means any language. |
| 69 |
module_implementation_preferences = ('',) # type: t.Iterable[str] |
| 70 |
allow_executable = True |
| 71 |
|
| 72 |
# the following control whether or not the connection supports the |
| 73 |
# persistent connection framework or not |
| 74 |
supports_persistence = False |
| 75 |
force_persistence = False |
| 76 |
|
| 77 |
default_user: str | None = None |
| 78 |
|
| 79 |
def __init__( |
| 80 |
self, |
| 81 |
play_context: PlayContext, |
| 82 |
*args: t.Any, |
| 83 |
**kwargs: t.Unpack[ConnectionKwargs], |
| 84 |
) -> None: |
| 85 |
|
| 86 |
super(ConnectionBase, self).__init__() |
| 87 |
|
| 88 |
# All these hasattrs allow subclasses to override these parameters |
| 89 |
if not hasattr(self, '_play_context'): |
| 90 |
# Backwards compat: self._play_context isn't really needed, using set_options/get_option |
| 91 |
self._play_context = play_context |
| 92 |
if not hasattr(self, '_display'): |
| 93 |
# Backwards compat: self._display isn't really needed, just import the global display and use that. |
| 94 |
self._display = display |
| 95 |
|
| 96 |
self.success_key = None |
| 97 |
self.prompt = None |
| 98 |
self._connected = False |
| 99 |
self._socket_path: str | None = None |
| 100 |
|
| 101 |
# we always must have shell |
| 102 |
if not (shell := kwargs.get('shell')): |
| 103 |
shell_type = play_context.shell if play_context.shell else getattr(self, '_shell_type', None) |
| 104 |
shell = get_shell_plugin(shell_type=shell_type, executable=self._play_context.executable) |
| 105 |
self._shell = shell |
| 106 |
|
| 107 |
self.become: BecomeBase | None = None |
| 108 |
|
| 109 |
def set_become_plugin(self, plugin: BecomeBase) -> None: |
| 110 |
self.become = plugin |
| 111 |
|
| 112 |
@property |
| 113 |
def connected(self) -> bool: |
| 114 |
"""Read-only property holding whether the connection to the remote host is active or closed.""" |
| 115 |
return self._connected |
| 116 |
|
| 117 |
@property |
| 118 |
def socket_path(self) -> str | None: |
| 119 |
"""Read-only property holding the connection socket path for this remote host""" |
| 120 |
return self._socket_path |
| 121 |
|
| 122 |
@staticmethod |
| 123 |
def _split_ssh_args(argstring: str) -> list[str]: |
| 124 |
""" |
| 125 |
Takes a string like '-o Foo=1 -o Bar="foo bar"' and returns a |
| 126 |
list ['-o', 'Foo=1', '-o', 'Bar=foo bar'] that can be added to |
| 127 |
the argument list. The list will not contain any empty elements. |
| 128 |
""" |
| 129 |
# In Python3, shlex.split doesn't work on a byte string. |
| 130 |
return [to_text(x.strip()) for x in shlex.split(argstring) if x.strip()] |
| 131 |
|
| 132 |
@property |
| 133 |
@abstractmethod |
| 134 |
def transport(self) -> str: |
| 135 |
"""String used to identify this Connection class from other classes""" |
| 136 |
pass |
| 137 |
|
| 138 |
@abstractmethod |
| 139 |
def _connect[T](self: T) -> T: |
| 140 |
"""Connect to the host we've been initialized with""" |
| 141 |
|
| 142 |
@ensure_connect |
| 143 |
@abstractmethod |
| 144 |
def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]: |
| 145 |
"""Run a command on the remote host. |
| 146 |
|
| 147 |
:arg cmd: byte string containing the command |
| 148 |
:kwarg in_data: If set, this data is passed to the command's stdin. |
| 149 |
This is used to implement pipelining. Currently not all |
| 150 |
connection plugins implement pipelining. |
| 151 |
:kwarg sudoable: Tell the connection plugin if we're executing |
| 152 |
a command via a privilege escalation mechanism. This may affect |
| 153 |
how the connection plugin returns data. Note that not all |
| 154 |
connections can handle privilege escalation. |
| 155 |
:returns: a tuple of (return code, stdout, stderr) The return code is |
| 156 |
an int while stdout and stderr are both byte strings. |
| 157 |
|
| 158 |
When a command is executed, it goes through multiple commands to get |
| 159 |
there. It looks approximately like this:: |
| 160 |
|
| 161 |
[LocalShell] ConnectionCommand [UsersLoginShell (*)] ANSIBLE_SHELL_EXECUTABLE [(BecomeCommand ANSIBLE_SHELL_EXECUTABLE)] Command |
| 162 |
:LocalShell: Is optional. It is run locally to invoke the |
| 163 |
``Connection Command``. In most instances, the |
| 164 |
``ConnectionCommand`` can be invoked directly instead. The ssh |
| 165 |
connection plugin which can have values that need expanding |
| 166 |
locally specified via ssh_args is the sole known exception to |
| 167 |
this. Shell metacharacters in the command itself should be |
| 168 |
processed on the remote machine, not on the local machine so no |
| 169 |
shell is needed on the local machine. (Example, ``/bin/sh``) |
| 170 |
:ConnectionCommand: This is the command that connects us to the remote |
| 171 |
machine to run the rest of the command. ``ansible_user``, |
| 172 |
``ansible_ssh_host`` and so forth are fed to this piece of the |
| 173 |
command to connect to the correct host (Examples ``ssh``, |
| 174 |
``chroot``) |
| 175 |
:UsersLoginShell: This shell may or may not be created depending on |
| 176 |
the ConnectionCommand used by the connection plugin. This is the |
| 177 |
shell that the ``ansible_user`` has configured as their login |
| 178 |
shell. In traditional UNIX parlance, this is the last field of |
| 179 |
a user's ``/etc/passwd`` entry We do not specifically try to run |
| 180 |
the ``UsersLoginShell`` when we connect. Instead it is implicit |
| 181 |
in the actions that the ``ConnectionCommand`` takes when it |
| 182 |
connects to a remote machine. ``ansible_shell_type`` may be set |
| 183 |
to inform ansible of differences in how the ``UsersLoginShell`` |
| 184 |
handles things like quoting if a shell has different semantics |
| 185 |
than the Bourne shell. |
| 186 |
:ANSIBLE_SHELL_EXECUTABLE: This is the shell set via the inventory var |
| 187 |
``ansible_shell_executable`` or via |
| 188 |
``constants.DEFAULT_EXECUTABLE`` if the inventory var is not set. |
| 189 |
We explicitly invoke this shell so that we have predictable |
| 190 |
quoting rules at this point. ``ANSIBLE_SHELL_EXECUTABLE`` is only |
| 191 |
settable by the user because some sudo setups may only allow |
| 192 |
invoking a specific shell. (For instance, ``/bin/bash`` may be |
| 193 |
allowed but ``/bin/sh``, our default, may not). We invoke this |
| 194 |
twice, once after the ``ConnectionCommand`` and once after the |
| 195 |
``BecomeCommand``. After the ConnectionCommand, this is run by |
| 196 |
the ``UsersLoginShell``. After the ``BecomeCommand`` we specify |
| 197 |
that the ``ANSIBLE_SHELL_EXECUTABLE`` is being invoked directly. |
| 198 |
:BecomeComand ANSIBLE_SHELL_EXECUTABLE: Is the command that performs |
| 199 |
privilege escalation. Setting this up is performed by the action |
| 200 |
plugin prior to running ``exec_command``. So we just get passed |
| 201 |
:param:`cmd` which has the BecomeCommand already added. |
| 202 |
(Examples: sudo, su) If we have a BecomeCommand then we will |
| 203 |
invoke a ANSIBLE_SHELL_EXECUTABLE shell inside of it so that we |
| 204 |
have a consistent view of quoting. |
| 205 |
:Command: Is the command we're actually trying to run remotely. |
| 206 |
(Examples: mkdir -p $HOME/.ansible, python $HOME/.ansible/tmp-script-file) |
| 207 |
""" |
| 208 |
pass |
| 209 |
|
| 210 |
@ensure_connect |
| 211 |
@abstractmethod |
| 212 |
def put_file(self, in_path: str, out_path: str) -> None: |
| 213 |
"""Transfer a file from local to remote""" |
| 214 |
pass |
| 215 |
|
| 216 |
@ensure_connect |
| 217 |
@abstractmethod |
| 218 |
def fetch_file(self, in_path: str, out_path: str) -> None: |
| 219 |
"""Fetch a file from remote to local; callers are expected to have pre-created the directory chain for out_path""" |
| 220 |
pass |
| 221 |
|
| 222 |
@abstractmethod |
| 223 |
def close(self) -> None: |
| 224 |
"""Terminate the connection""" |
| 225 |
pass |
| 226 |
|
| 227 |
def connection_lock(self) -> None: |
| 228 |
f = self._play_context.connection_lockfd |
| 229 |
display.vvvv('CONNECTION: pid %d waiting for lock on %d' % (os.getpid(), f), host=self._play_context.remote_addr) |
| 230 |
fcntl.lockf(f, fcntl.LOCK_EX) |
| 231 |
display.vvvv('CONNECTION: pid %d acquired lock on %d' % (os.getpid(), f), host=self._play_context.remote_addr) |
| 232 |
|
| 233 |
def connection_unlock(self) -> None: |
| 234 |
f = self._play_context.connection_lockfd |
| 235 |
fcntl.lockf(f, fcntl.LOCK_UN) |
| 236 |
display.vvvv('CONNECTION: pid %d released lock on %d' % (os.getpid(), f), host=self._play_context.remote_addr) |
| 237 |
|
| 238 |
def reset(self) -> None: |
| 239 |
display.warning("Reset is not implemented for this connection") |
| 240 |
|
| 241 |
def update_vars(self, variables: dict[str, t.Any]) -> None: |
| 242 |
""" |
| 243 |
Adds 'magic' variables relating to connections to the variable dictionary provided. |
| 244 |
In case users need to access from the play, this is a legacy from runner. |
| 245 |
""" |
| 246 |
for varname in C.COMMON_CONNECTION_VARS: |
| 247 |
value = None |
| 248 |
if varname in variables: |
| 249 |
# dont update existing |
| 250 |
continue |
| 251 |
elif 'password' in varname or 'passwd' in varname: |
| 252 |
# no secrets! |
| 253 |
continue |
| 254 |
elif varname == 'ansible_connection': |
| 255 |
# its me mom! |
| 256 |
value = self._load_name |
| 257 |
elif varname == 'ansible_shell_type' and self._shell: |
| 258 |
# its my cousin ... |
| 259 |
value = self._shell._load_name |
| 260 |
else: |
| 261 |
# deal with generic options if the plugin supports em (for example not all connections have a remote user) |
| 262 |
options = C.config.get_plugin_options_from_var('connection', self._load_name, varname) |
| 263 |
if options: |
| 264 |
value = self.get_option(options[0]) # for these variables there should be only one option |
| 265 |
elif 'become' not in varname: |
| 266 |
# fallback to play_context, unless become related TODO: in the end, should come from task/play and not pc |
| 267 |
for prop, var_list in C.MAGIC_VARIABLE_MAPPING.items(): |
| 268 |
if varname in var_list: |
| 269 |
try: |
| 270 |
value = getattr(self._play_context, prop) |
| 271 |
break |
| 272 |
except AttributeError: |
| 273 |
# It was not defined; fine to ignore |
| 274 |
continue |
| 275 |
|
| 276 |
if value is not None: |
| 277 |
display.debug('Set connection var {0} to {1}'.format(varname, value)) |
| 278 |
variables[varname] = value |
| 279 |
|
| 280 |
def _resolve_option_variables(self, variables, templar): |
| 281 |
""" |
| 282 |
Return a dict of variable -> templated value, for any variables that |
| 283 |
that match options registered by this plugin. |
| 284 |
""" |
| 285 |
# create dict of 'templated vars' |
| 286 |
var_options = { |
| 287 |
'_extras': {}, |
| 288 |
} |
| 289 |
for var_name in C.config.get_plugin_vars('connection', self._load_name): |
| 290 |
if var_name in variables: |
| 291 |
try: |
| 292 |
var_options[var_name] = templar.template(variables[var_name]) |
| 293 |
except AnsibleValueOmittedError: |
| 294 |
pass |
| 295 |
|
| 296 |
# add extras if plugin supports them |
| 297 |
if getattr(self, 'allow_extras', False): |
| 298 |
for var_name in variables: |
| 299 |
if var_name.startswith(f'ansible_{self.extras_prefix}_') and var_name not in var_options: |
| 300 |
try: |
| 301 |
var_options['_extras'][var_name] = templar.template(variables[var_name]) |
| 302 |
except AnsibleValueOmittedError: |
| 303 |
pass |
| 304 |
|
| 305 |
return var_options |
| 306 |
|
| 307 |
def is_pipelining_enabled(self, wrap_async: bool = False) -> bool: |
| 308 |
|
| 309 |
is_enabled = False |
| 310 |
if self.has_pipelining and (not self.become or self.become.pipelining): |
| 311 |
try: |
| 312 |
is_enabled = self.get_option('pipelining') |
| 313 |
except KeyError: |
| 314 |
is_enabled = getattr(self._play_context, 'pipelining', False) |
| 315 |
|
| 316 |
# We should deprecate always_pipeline_modules and has_native_async in favor of plugins just overriding this |
| 317 |
# method. We cannot add it now as plugins will need to be compatible with older Ansible versions that still need |
| 318 |
# to set this to be true. This function was added in 2.19 and when we expect 2.19 being a baseline for plugins |
| 319 |
# we can add a runtime deprecation that checks whether these are True and if so warn the function should be |
| 320 |
# overridden instead. |
| 321 |
# deprecate: description='Revisit adding a deprecation or bump the core_version' core_version='2.24' |
| 322 |
conditions = [ |
| 323 |
is_enabled or self.always_pipeline_modules, # enabled via config or forced via connection (eg winrm) |
| 324 |
not wrap_async or self.has_native_async, # async does not normally support pipelining unless it does (eg winrm) |
| 325 |
] |
| 326 |
return all(conditions) |
| 327 |
|
| 328 |
|
| 329 |
class NetworkConnectionBase(ConnectionBase): |
| 330 |
""" |
| 331 |
A base class for network-style connections. |
| 332 |
""" |
| 333 |
|
| 334 |
force_persistence = True |
| 335 |
# Do not use _remote_is_local in other connections |
| 336 |
_remote_is_local = True |
| 337 |
|
| 338 |
def __init__( |
| 339 |
self, |
| 340 |
play_context: PlayContext, |
| 341 |
*args: t.Any, |
| 342 |
**kwargs: t.Any, |
| 343 |
) -> None: |
| 344 |
super(NetworkConnectionBase, self).__init__(play_context, *args, **kwargs) |
| 345 |
self._messages: list[tuple[str, str]] = [] |
| 346 |
self._conn_closed = False |
| 347 |
|
| 348 |
self._network_os = self._play_context.network_os |
| 349 |
|
| 350 |
self._local = connection_loader.get('local', play_context, '/dev/null') |
| 351 |
self._local.set_options() |
| 352 |
|
| 353 |
self._sub_plugin: dict[str, t.Any] = {} |
| 354 |
self._cached_variables = (None, None, None) |
| 355 |
|
| 356 |
# reconstruct the socket_path and set instance values accordingly |
| 357 |
self._ansible_playbook_pid = kwargs.get('ansible_playbook_pid') |
| 358 |
self._update_connection_state() |
| 359 |
|
| 360 |
def __getattr__(self, name): |
| 361 |
try: |
| 362 |
return self.__dict__[name] |
| 363 |
except KeyError: |
| 364 |
if not name.startswith('_'): |
| 365 |
plugin = self._sub_plugin.get('obj') |
| 366 |
if plugin: |
| 367 |
method = getattr(plugin, name, None) |
| 368 |
if method is not None: |
| 369 |
return method |
| 370 |
raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) |
| 371 |
|
| 372 |
def exec_command(self, cmd: str, in_data: bytes | None = None, sudoable: bool = True) -> tuple[int, bytes, bytes]: |
| 373 |
return self._local.exec_command(cmd, in_data, sudoable) |
| 374 |
|
| 375 |
def queue_message(self, level: str, message: str) -> None: |
| 376 |
""" |
| 377 |
Adds a message to the queue of messages waiting to be pushed back to the controller process. |
| 378 |
|
| 379 |
:arg level: A string which can either be the name of a method in display, or 'log'. When |
| 380 |
the messages are returned to task_executor, a value of log will correspond to |
| 381 |
``display.display(message, log_only=True)``, while another value will call ``display.[level](message)`` |
| 382 |
""" |
| 383 |
self._messages.append((level, message)) |
| 384 |
|
| 385 |
def pop_messages(self) -> list[tuple[str, str]]: |
| 386 |
messages, self._messages = self._messages, [] |
| 387 |
return messages |
| 388 |
|
| 389 |
def put_file(self, in_path: str, out_path: str) -> None: |
| 390 |
"""Transfer a file from local to remote""" |
| 391 |
return self._local.put_file(in_path, out_path) |
| 392 |
|
| 393 |
def fetch_file(self, in_path: str, out_path: str) -> None: |
| 394 |
"""Fetch a file from remote to local""" |
| 395 |
return self._local.fetch_file(in_path, out_path) |
| 396 |
|
| 397 |
def reset(self) -> None: |
| 398 |
""" |
| 399 |
Reset the connection |
| 400 |
""" |
| 401 |
if self._socket_path: |
| 402 |
self.queue_message('vvvv', 'resetting persistent connection for socket_path %s' % self._socket_path) |
| 403 |
self.close() |
| 404 |
self.queue_message('vvvv', 'reset call on connection instance') |
| 405 |
|
| 406 |
def close(self) -> None: |
| 407 |
self._conn_closed = True |
| 408 |
if self._connected: |
| 409 |
self._connected = False |
| 410 |
|
| 411 |
def set_options( |
| 412 |
self, |
| 413 |
task_keys: dict[str, t.Any] | None = None, |
| 414 |
var_options: dict[str, t.Any] | None = None, |
| 415 |
direct: dict[str, t.Any] | None = None, |
| 416 |
) -> None: |
| 417 |
super(NetworkConnectionBase, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct) |
| 418 |
if self.get_option('persistent_log_messages'): |
| 419 |
warning = "Persistent connection logging is enabled for %s. This will log ALL interactions" % self._play_context.remote_addr |
| 420 |
logpath = getattr(C, 'DEFAULT_LOG_PATH') |
| 421 |
if logpath is not None: |
| 422 |
warning += " to %s" % logpath |
| 423 |
self.queue_message('warning', "%s and WILL NOT redact sensitive configuration like passwords. USE WITH CAUTION!" % warning) |
| 424 |
|
| 425 |
if self._sub_plugin.get('obj') and self._sub_plugin.get('type') != 'external': |
| 426 |
try: |
| 427 |
self._sub_plugin['obj'].set_options(task_keys=task_keys, var_options=var_options, direct=direct) |
| 428 |
except AttributeError: |
| 429 |
pass |
| 430 |
|
| 431 |
def _update_connection_state(self) -> None: |
| 432 |
""" |
| 433 |
Reconstruct the connection socket_path and check if it exists |
| 434 |
|
| 435 |
If the socket path exists then the connection is active and set |
| 436 |
both the _socket_path value to the path and the _connected value |
| 437 |
to True. If the socket path doesn't exist, leave the socket path |
| 438 |
value to None and the _connected value to False |
| 439 |
""" |
| 440 |
ssh = connection_loader.get('ssh', class_only=True) |
| 441 |
control_path = ssh._create_control_path( |
| 442 |
self._play_context.remote_addr, self._play_context.port, |
| 443 |
self._play_context.remote_user, self._play_context.connection, |
| 444 |
self._ansible_playbook_pid |
| 445 |
) |
| 446 |
|
| 447 |
tmp_path = unfrackpath(C.PERSISTENT_CONTROL_PATH_DIR) |
| 448 |
socket_path = unfrackpath(control_path % dict(directory=tmp_path)) |
| 449 |
|
| 450 |
if os.path.exists(socket_path): |
| 451 |
self._connected = True |
| 452 |
self._socket_path = socket_path |
| 453 |
|
| 454 |
def _log_messages(self, message: str) -> None: |
| 455 |
if self.get_option('persistent_log_messages'): |
| 456 |
self.queue_message('log', message) |