Debian Codegraph @

lib/ansible/executor/task_executor.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 # (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 from __future__ import annotations
5
6 import itertools
7 import os
8 import time
9 import json
10 import pathlib
11 import subprocess
12 import sys
13
14 import traceback
15 import typing as t
16
17 from ansible import constants as C
18 from ansible._internal._task import TaskContext, UnifiedTaskResult
19 from ansible.cli import scripts
20 from ansible.errors import (
21 AnsibleError, AnsibleParserError, AnsibleUndefinedVariable, AnsibleTaskError,
22 AnsibleValueOmittedError,
23 )
24
25 from ansible._internal import _display_utils
26 from ansible._internal._datatag import _utils
27 from ansible.module_utils.datatag import native_type_name
28 from ansible._internal._datatag._tags import TrustedAsTemplate
29 from ansible.module_utils.parsing.convert_bool import boolean
30 from ansible.module_utils.common.text.converters import to_text, to_native
31 from ansible.module_utils.connection import write_to_stream
32 from ansible.playbook.play_context import PlayContext
33 from ansible.plugins import get_plugin_class
34 from ansible.plugins.action import ActionBase
35 from ansible.plugins.connection import ConnectionBase
36 from ansible.plugins.loader import become_loader, cliconf_loader, connection_loader, httpapi_loader, netconf_loader, terminal_loader, PluginLoadContext
37 from ansible._internal._templating._jinja_plugins import _invoke_lookup, _DirectCall
38 from ansible._internal._templating._engine import TemplateEngine
39 from ansible.template import Templar
40 from ansible.utils.collection_loader import AnsibleCollectionConfig
41 from ansible.utils.display import Display
42 from ansible.utils.vars import combine_vars
43 from ansible.vars.clean import namespace_facts
44 from ansible.vars.manager import _clean_and_deprecate_top_level_facts, _INJECT_FACTS
45 from ansible._internal._errors import _task_timeout
46 from ansible._internal import _task
47 from ansible.playbook.task import Task
48 from ansible.executor.task_queue_manager import FinalQueue
49
50
51 display = Display()
52
53
54 _DELEGATED_CONNECTION_PLUGIN_VAR_NAMES = frozenset({
55 'ansible_host',
56 'ansible_port',
57 'ansible_user',
58 'ansible_connection',
59 })
60
61 __all__ = ['TaskExecutor']
62
63
64 class TaskExecutor:
65
66 """
67 This is the main worker class for the executor pipeline, which
68 handles loading an action plugin to actually dispatch the task to
69 a given host. This class roughly corresponds to the old Runner()
70 class.
71 """
72
73 def __init__(
74 self,
75 host,
76 play_context: PlayContext,
77 loader,
78 shared_loader_obj,
79 final_q: FinalQueue,
80 variable_manager,
81 ) -> None:
82 self._host = host
83 self._play_context = play_context
84 self._loader = loader
85 self._shared_loader_obj = shared_loader_obj
86 self._connection = None
87 self._final_q = final_q
88 self._variable_manager = variable_manager
89 self._loop_eval_error: Exception | None = None
90
91 @property
92 def _task(self) -> Task:
93 return TaskContext.current().task
94
95 def run(self) -> UnifiedTaskResult:
96 """
97 The main executor entrypoint, where we determine if the specified
98 task requires looping and either runs the task with self._run_loop()
99 or self._execute(). After that, the returned results are parsed and
100 returned as a dict.
101 """
102
103 display.debug("in run() - task %s" % self._task._uuid)
104
105 task_ctx = TaskContext.current()
106
107 try:
108 try:
109 items = self._get_loop_items()
110 except AnsibleUndefinedVariable as e:
111 # save the error raised here for use later
112 items = None
113 self._loop_eval_error = e
114
115 if items is None: # non-loop
116 utr = self._execute()
117 elif not items: # empty loop
118 with UnifiedTaskResult.create_and_record() as utr:
119 utr.set_skipped('No items in the list', include_skipped_reason=True)
120 utr.loop_results = []
121 else: # loop with values
122 utr = self._run_loop(items)
123
124 return utr
125 except Exception as ex:
126 utr = UnifiedTaskResult.create_from_action_exception(ex)
127
128 self._task.update_result_no_log(task_ctx.task_templar, utr)
129
130 if not isinstance(ex, AnsibleError):
131 utr.msg = f'Unexpected failure during task execution: {utr.msg}'
132
133 return utr
134 finally:
135 try:
136 self._connection.close()
137 except AttributeError:
138 pass
139 except Exception as e:
140 display.debug(u"error closing connection: %s" % to_text(e))
141
142 def _get_loop_items(self) -> list[t.Any] | None:
143 """
144 Loads a lookup plugin to handle the with_* portion of a task (if specified),
145 and returns the items result.
146 """
147 task_ctx = TaskContext.current()
148
149 # get search path for this task to pass to lookup plugins
150 task_ctx.task_vars['ansible_search_path'] = self._task.get_search_path()
151
152 # ensure basedir is always in (dwim already searches here but we need to display it)
153 if self._loader.get_basedir() not in task_ctx.task_vars['ansible_search_path']:
154 task_ctx.task_vars['ansible_search_path'].append(self._loader.get_basedir())
155
156 items = None
157 if self._task.loop_with:
158 terms = self._task.loop
159
160 if isinstance(terms, str):
161 terms = task_ctx.task_templar.resolve_to_container(_utils.str_problematic_strip(terms))
162
163 if not isinstance(terms, list):
164 terms = [terms]
165
166 @_DirectCall.mark
167 def invoke_lookup() -> t.Any:
168 """Scope-capturing wrapper around _invoke_lookup to avoid functools.partial obscuring its usage from type-checking tools."""
169 return _invoke_lookup(
170 plugin_name=self._task.loop_with,
171 lookup_terms=terms,
172 lookup_kwargs=dict(wantlist=True),
173 invoked_as_with=True,
174 )
175
176 # Smuggle a special wrapped lookup invocation in as a local variable for its exclusive use when being evaluated as `with_(lookup)`.
177 # This value will not be visible to other users of this templar or its `available_variables`.
178 items = task_ctx.task_templar.evaluate_expression(
179 expression=TrustedAsTemplate().tag("invoke_lookup()"),
180 local_variables=dict(invoke_lookup=invoke_lookup),
181 )
182
183 elif self._task.loop is not None:
184 items = task_ctx.task_templar.template(self._task.loop)
185
186 if not isinstance(items, list):
187 raise AnsibleError(
188 f"The `loop` value must resolve to a 'list', not {native_type_name(items)!r}.",
189 help_text="Provide a list of items/templates, or a template resolving to a list.",
190 obj=self._task.loop,
191 )
192
193 return items
194
195 def _run_loop(self, items: list[t.Any]) -> UnifiedTaskResult:
196 """
197 Runs the task with the loop items specified and collates the result
198 into an array named 'results' which is inserted into the final result
199 along with the item for which the loop ran.
200 """
201 task_ctx = TaskContext.current()
202
203 task_ctx._loop_items = items
204
205 self._task.loop_control.post_validate(templar=task_ctx.task_templar)
206 self._check_loop_control()
207
208 loop_pause = self._task.loop_control.pause
209
210 ran_once = False
211 last_loop_task: Task | None = None
212
213 for _item_index, _item in task_ctx.start_loop():
214 # pause between loop iterations
215 if loop_pause and ran_once:
216 time.sleep(loop_pause)
217 else:
218 ran_once = True
219
220 with task_ctx.loop_item_context(self):
221 last_loop_task = self._task
222
223 utr = self._execute()
224
225 if self._task.loop_control and self._task.loop_control.break_when:
226 try:
227 utr.set_break_when_result(self._task._resolve_conditional(self._task.loop_control.break_when, task_ctx.task_vars))
228 except AnsibleError as ex:
229 # RPFIX-5: UX: This this bypasses AnsibleTaskError handling, resulting in less information than a normal task failure.
230 utr.set_break_when_result(ex)
231
232 self._update_task_connection()
233
234 if utr.failed or utr.unreachable:
235 self._final_q.send_callback('v2_runner_item_on_failed', self._host, self._task, utr)
236 elif utr.skipped:
237 self._final_q.send_callback('v2_runner_item_on_skipped', self._host, self._task, utr)
238 else:
239 if self._task.diff:
240 # non-loop diff dispatch is handled controller-side by the strategy
241 self._final_q.send_callback('v2_on_file_diff', self._host, self._task, utr)
242
243 self._final_q.send_callback('v2_runner_item_on_ok', self._host, self._task, utr)
244
245 # update the connection value on the original task to reflect the resolved value
246 self._update_task_connection()
247
248 if last_loop_task:
249 # FUTURE: hide this in Task/LoopContext once they're fully implemented
250 # NOTE: run_once cannot contain loop vars because it's templated earlier also
251 # This is saving the post-validated field from the last loop so the strategy can use the templated value post task execution
252 self._task.run_once = last_loop_task.run_once
253 self._task.action = last_loop_task.action
254
255 return task_ctx.build_loop_result()
256
257 def _check_loop_control(self) -> None:
258 """Check loop_control configuration for potential problems."""
259 task_ctx = TaskContext.current()
260
261 loop_variables = dict(
262 loop_var=self._task.loop_control.loop_var,
263 index_var=self._task.loop_control.index_var,
264 )
265
266 # These reserved variables are set in TaskContext.start_loop,
267 # so shouldn't be expected to already be in task variables.
268 reserved_loop_variables = {
269 "ansible_index_var",
270 "ansible_loop",
271 "ansible_loop_var",
272 }
273
274 duplicate_loop_variables = {
275 key for key, group in itertools.groupby(sorted(value for value in loop_variables.values() if value)) if len(list(group)) > 1
276 }
277
278 for var_name, var_value in loop_variables.items():
279 if not var_value:
280 continue
281
282 if var_value in task_ctx.task_vars:
283 conflict = "already in use"
284 elif var_value in reserved_loop_variables:
285 conflict = "reserved"
286 elif var_value in C.COMMON_CONNECTION_VARS:
287 conflict = "reserved"
288 elif var_value in duplicate_loop_variables:
289 conflict = "used more than once"
290 else:
291 continue
292
293 display.warning(
294 msg=f"The variable {var_value!r} is {conflict}.",
295 help_text=f"You should set the `{var_name}` value in the `loop_control` option for the task "
296 "to something else to avoid variable collisions and unexpected behavior.",
297 obj=var_value,
298 )
299
300 def _calculate_delegate_to(self):
301 """This method is responsible for effectively pre-validating Task.delegate_to and will
302 happen before Task.post_validate is executed
303 """
304 task_ctx = TaskContext.current()
305
306 delegated_vars, delegated_host_name = self._variable_manager.get_delegated_vars_and_hostname(task_ctx.task_templar, self._task, task_ctx.task_vars)
307 # At the point this is executed it is safe to mutate self._task,
308 # since `self._task` is either a copy referred to by `tmp_task` in `_run_loop`
309 # or just a singular non-looped task
310
311 self._task.delegate_to = delegated_host_name # always override, since a templated result could be an omit (-> None)
312
313 task_ctx.task_vars.update(delegated_vars)
314
315 def _execute(self) -> UnifiedTaskResult:
316 utr: UnifiedTaskResult
317
318 task_ctx = TaskContext.current()
319
320 with _display_utils.DeferredWarningContext(variables=task_ctx.task_vars) as warning_ctx:
321 try:
322 # DTFIX-FUTURE: improve error handling to prioritize the earliest exception, turning the remaining ones into warnings
323 utr = self._execute_internal()
324 utr.maybe_raise_on_result()
325 except (Exception, _task_timeout.TaskTimeoutError) as ex: # TaskTimeoutError is BaseException
326 try:
327 raise AnsibleTaskError(obj=self._task.get_ds()) from ex
328 except AnsibleTaskError as atex:
329 utr = UnifiedTaskResult.create_from_action_exception(atex, accept_result_contribution=True)
330
331 self._task.update_result_no_log(task_ctx.task_templar, utr)
332
333 # The warnings/deprecations in the result have already been captured in the DeferredWarningContext by _apply_task_result_compat.
334 # The captured warnings/deprecations are a superset of the ones from the result, and may have been converted from a dict to a dataclass.
335 # These are then used to supersede the entries in the result.
336
337 utr.finalize_warnings(warning_ctx)
338
339 return utr
340
341 def _update_task_connection(self, task: Task | None = None) -> None:
342 """If a connection plugin is loaded, ensure the resolved name is propagated back to the controller as the task's connection."""
343 if not task:
344 task = self._task
345
346 # FUTURE: What value should be reported when there is no connection?
347 # This is currently not possible, but it should be.
348
349 if isinstance(self._connection, ConnectionBase):
350 task.connection = self._connection.ansible_name
351
352 def _execute_internal(self) -> UnifiedTaskResult:
353 """
354 The primary workhorse of the executor system, this runs the task
355 on the specified host (which may be the delegated_to host) and handles
356 the retry/until and block rescue/always execution
357 """
358 task_ctx = TaskContext.current()
359
360 self._calculate_delegate_to()
361
362 context_validation_error = None
363
364 task_vars_with_magic_vars = task_ctx.task_vars.copy() # copy of task vars with connection vars erased/augmented for delegate_to
365
366 try:
367 # TODO: remove play_context as this does not take delegation nor loops correctly into account,
368 # the task itself should hold the correct values for connection/shell/become/terminal plugin options to finalize.
369 # Kept for now for backwards compatibility and a few functions that are still exclusive to it.
370
371 # apply the given task's information to the connection info,
372 # which may override some fields already set by the play or
373 # the options specified on the command line
374 self._play_context = self._play_context.set_task_and_variable_override(task=self._task, variables=task_ctx.task_vars, templar=task_ctx.task_templar)
375
376 # fields set from the play/task may be based on task vars, so we have to
377 # do the same kind of post validation step on it here before we use it.
378 self._play_context.post_validate(templar=task_ctx.task_templar)
379
380 # now that the play context is finalized, if the remote_addr is not set
381 # default to using the host's address field as the remote address
382 if not self._play_context.remote_addr:
383 self._play_context.remote_addr = self._host.address
384
385 # We also add "magic" variables back into the tempvars dict to make sure
386 self._play_context.update_vars(task_vars_with_magic_vars)
387
388 except AnsibleError as e:
389 # save the error, which we'll raise later if we don't end up
390 # skipping this task during the conditional evaluation step
391 context_validation_error = e
392
393 # Evaluate the conditional (if any) for this task, which we do before running
394 # the final task post-validation. We do this before the post validation due to
395 # the fact that the conditional may specify that the task be skipped due to a
396 # variable not being present which would otherwise cause validation to fail
397 try:
398 conditional_result, conditional_item = self._task._resolve_conditional_with_item(self._task.when, task_vars_with_magic_vars)
399
400 if not conditional_result:
401 return UnifiedTaskResult.record_conditional_false(conditional_item)
402 except AnsibleError as e:
403 # FUTURE: this error handling seems problematic; shouldn't a failed loop expression always be an error, rather than letting an item-oriented `when`
404 # expression be treated as a task-oriented one and sweeping the failure under the rug if it happens to be False? If so, this re-raise and the
405 # one just below it should be removed in favor of letting it fly from get_loop_items.
406 try:
407 # The original error's obj should contain the failed expression, which should be origin tagged.
408 # This error is intended to provide additional context (the message) for the original error.
409 # By repeating the original error's obj here, the error display will group the two errors together.
410 raise AnsibleError("A 'when' expression failed.", obj=e.obj) from e
411 except AnsibleError as ae:
412 if self._loop_eval_error is None:
413 raise
414
415 # Display the error from the conditional as well to prevent
416 # losing information useful for debugging.
417 display.error(ae)
418
419 raise self._loop_eval_error
420
421 # Not skipping, if we had loop error raised earlier we need to raise it now to halt the execution of this task
422 if self._loop_eval_error is not None:
423 raise self._loop_eval_error
424
425 # if we ran into an error while setting up the PlayContext, raise it now, unless is known issue with delegation
426 # and undefined vars (correct values are in cvars later on and connection plugins, if still error, blows up there)
427
428 # DTFIX-FUTURE: this should probably be declaratively handled in post_validate (or better, get rid of play_context)
429 if context_validation_error is not None:
430 raiseit = True
431 if self._task.delegate_to:
432 if isinstance(context_validation_error, AnsibleParserError):
433 # parser error, might be cause by undef too
434 if isinstance(context_validation_error.__cause__, AnsibleUndefinedVariable):
435 raiseit = False
436 elif isinstance(context_validation_error, AnsibleUndefinedVariable):
437 # DTFIX-FUTURE: should not be possible to hit this now (all are AnsibleFieldAttributeError)?
438 raiseit = False
439 if raiseit:
440 raise context_validation_error # pylint: disable=raising-bad-type
441
442 # Now we do final validation on the task, which sets all fields to their final values.
443 self._task.post_validate(templar=task_ctx.task_templar.extend(variables=task_vars_with_magic_vars)) # should be handled by a context!
444
445 # if this task is a TaskInclude, we just return now with a success code so the
446 # main thread can expand the task list for the given host
447 if self._task.action in C._ACTION_INCLUDE_TASKS:
448 include_args = self._task.args.copy()
449 include_file = include_args.pop('_raw_params', None)
450
451 with UnifiedTaskResult.create_and_record() as utr:
452 utr.include_file = include_file
453 utr.include_args = include_args
454 return utr
455
456 # if this task is a IncludeRole, we just return now with a success code so the main thread can expand the task list for the given host
457 elif self._task.action in C._ACTION_INCLUDE_ROLE:
458 include_args = self._task.args.copy()
459
460 with UnifiedTaskResult.create_and_record() as utr:
461 utr.include_args = include_args
462 return utr
463
464 # setup cvars copy, used for all connection related templating
465 if self._task.delegate_to:
466 # use vars from delegated host (which already include task vars) instead of original host
467 cvars = task_ctx.task_vars.get('ansible_delegated_vars', {}).get(self._task.delegate_to, {})
468 else:
469 # just use normal host vars
470 cvars = task_ctx.task_vars
471
472 connection_templar = task_ctx.task_templar.extend(variables=cvars) # should be managed by a context!
473
474 # use magic var if it exists, if not, let task inheritance do it's thing.
475 if cvars.get('ansible_connection') is not None:
476 current_connection = connection_templar.template(cvars['ansible_connection'])
477 else:
478 current_connection = self._task.connection
479
480 # get the connection and the handler for this execution
481 if (not self._connection or
482 not getattr(self._connection, 'connected', False) or
483 not self._connection.matches_name([current_connection]) or
484 # pc compare, left here for old plugins, but should be irrelevant for those
485 # using get_option, since they are cleared each iteration.
486 self._play_context.remote_addr != self._connection._play_context.remote_addr):
487 self._connection = self._get_connection(cvars, connection_templar, current_connection)
488 else:
489 # if connection is reused, its _play_context is no longer valid and needs
490 # to be replaced with the one templated above, in case other data changed
491 self._connection._play_context = self._play_context
492 self._set_become_plugin(cvars, connection_templar, self._connection)
493
494 plugin_vars = self._set_connection_options(cvars, connection_templar)
495
496 # update with connection info (i.e ansible_host/ansible_user)
497 self._connection.update_vars(task_ctx.task_vars)
498
499 # TODO: eventually remove as pc is taken out of the resolution path
500 # feed back into pc to ensure plugins not using get_option can get correct value
501 self._connection._play_context = self._play_context.set_task_and_variable_override(
502 task=self._task,
503 variables=task_ctx.task_vars,
504 templar=task_ctx.task_templar,
505 )
506
507 # TODO: eventually remove this block as this should be a 'consequence' of 'forced_local' modules, right now rely on remote_is_local connection
508 # special handling for python interpreter for network_os, default to ansible python unless overridden
509 if 'ansible_python_interpreter' not in cvars and 'ansible_network_os' in cvars and getattr(self._connection, '_remote_is_local', False):
510 # this also avoids 'python discovery'
511 cvars['ansible_python_interpreter'] = sys.executable
512
513 # get handler
514 self._handler, _module_context = self._get_action_handler_with_module_context(templar=task_ctx.task_templar)
515
516 # self._connection should have its final value for this task/loop-item by this point; record on the task object
517 self._update_task_connection()
518
519 retries = 1 # includes the default actual run + retries set by user/default
520 if self._task.retries is not None:
521 retries += max(0, self._task.retries)
522 elif self._task.until:
523 retries += 3 # the default is not set in FA because we need to differentiate "unset" value
524
525 delay = self._task.delay
526 if delay < 0:
527 delay = 1
528
529 display.debug("starting attempt loop")
530 for attempt in range(1, retries + 1):
531 display.debug("running the handler")
532 try:
533 # FUTURE: exceptions raised anywhere here bypass failed_when, `until` retries, intra-loop register/register-projections
534 with _task_timeout.TaskTimeoutError.alarm_timeout(self._task.timeout):
535 try:
536 task_ctx.pending_changes = _task.PendingChanges()
537
538 with UnifiedTaskResult.create_and_record(self._handler.run(task_vars=task_ctx.task_vars)) as utr:
539 utr.pending_changes = task_ctx.pending_changes
540 finally:
541 task_ctx.pending_changes = None
542
543 finally:
544 self._handler.cleanup()
545 display.debug("handler run complete")
546
547 if self._task.async_val > 0:
548 if self._task.poll > 0 and not utr.skipped and not utr.failed:
549 utr = self._poll_async_result(utr=utr, templar=task_ctx.task_templar, task_vars=task_ctx.task_vars)
550
551 if utr.failed:
552 self._final_q.send_callback('v2_runner_on_async_failed', self._host, self._task, utr)
553 else:
554 self._final_q.send_callback('v2_runner_on_async_ok', self._host, self._task, utr)
555
556 if utr.ansible_facts and _task.VariableLayer.CACHEABLE_FACT not in utr.pending_changes.register_host_variables:
557 # For backward compatibility, if the action provided ansible_facts, use that as the CACHEABLE_FACT layer if the action did not provide one.
558 utr.pending_changes.register_host_variables[_task.VariableLayer.CACHEABLE_FACT] = utr.ansible_facts
559
560 # Variable layers should be reflected on task vars in the same way they will be handled by variable manager.
561 # What occurs below is a partial re-implementation of variable manager, and thus does not fully reflect its behavior.
562 # These updates are only done for the current host.
563
564 if not self._task.delegate_to or not self._task.delegate_facts:
565 if cacheable_fact_layer := utr.pending_changes.register_host_variables.get(_task.VariableLayer.CACHEABLE_FACT):
566 task_ctx.update_task_vars(dict(
567 ansible_facts=combine_vars(
568 task_ctx.task_vars.get('ansible_facts', {}),
569 namespace_facts(cacheable_fact_layer)['ansible_facts'],
570 ),
571 ))
572
573 if _INJECT_FACTS:
574 task_ctx.update_task_vars(_clean_and_deprecate_top_level_facts(cacheable_fact_layer))
575
576 if include_vars_layer := utr.pending_changes.register_host_variables.get(_task.VariableLayer.INCLUDE_VARS):
577 task_ctx.update_task_vars(include_vars_layer)
578
579 if ephemeral_fact_layer := utr.pending_changes.register_host_variables.get(_task.VariableLayer.EPHEMERAL_FACT):
580 task_ctx.update_task_vars(ephemeral_fact_layer)
581
582 if register_vars_layer := utr.pending_changes.register_host_variables.get(_task.VariableLayer.REGISTER_VARS):
583 task_ctx.update_task_vars(register_vars_layer)
584
585 # Make attempts and retries available early to allow their use in changed/failed_when
586 if retries > 1:
587 utr.attempts = attempt
588
589 # if we didn't skip this task, use the helpers to evaluate the changed/
590 # failed_when properties
591 if not utr.skipped:
592 try:
593 if self._task.changed_when:
594 utr.set_changed_when_result(self._task._resolve_conditional(self._task.changed_when, task_ctx.task_vars))
595 except AnsibleError as e:
596 utr.set_changed_when_result(e)
597 else:
598 try:
599 if self._task.failed_when:
600 utr.set_failed_when_result(self._task._resolve_conditional(self._task.failed_when, task_ctx.task_vars))
601 except AnsibleError as e:
602 utr.set_failed_when_result(e)
603
604 if retries > 1:
605 try:
606 if self._task._resolve_conditional(self._task.until or [not utr.failed], task_ctx.task_vars):
607 break
608 except AnsibleError as e:
609 # The original error's obj should contain the failed expression, which should be origin tagged.
610 # This error is intended to provide additional context (the message) for the original error.
611 # By repeating the original error's obj here, the error display will group the two errors together.
612 raise AnsibleError("An 'until' expression failed.", obj=e.obj) from e
613
614 # no conditional check, or it failed, so sleep for the specified time
615 if attempt < retries:
616 utr.retries = retries
617 utr.attempts = attempt + 1
618 display.debug('Retrying task, attempt %d of %d' % (attempt, retries))
619 self._final_q.send_callback('v2_runner_retry', self._host, self._task, utr)
620 time.sleep(delay)
621 self._handler = self._get_action_handler(templar=task_ctx.task_templar)
622 else:
623 if retries > 1:
624 # we ran out of attempts, so mark the result as failed
625 utr.attempts = retries - 1
626 utr.failed = True
627
628 # save the notification target in the result, if it was specified, as
629 # this task may be running in a loop in which case the notification
630 # may be item-specific, ie. "notify: service {{item}}"
631 if self._task.notify is not None:
632 utr.notify = self._task.notify
633
634 # add the delegated vars to the result, so we can reference them
635 # on the results side without having to do any further templating
636 # also now add connection vars results when delegating
637 if self._task.delegate_to:
638 utr.delegated_host = self._task.delegate_to
639 utr.callback_delegated_vars_subset = dict(
640 ansible_delegated_host=self._task.delegate_to,
641 ansible_connection=current_connection,
642 )
643
644 # note: here for callbacks that rely on this info to display delegation
645 for plugin_var_name in plugin_vars:
646 if plugin_var_name not in _DELEGATED_CONNECTION_PLUGIN_VAR_NAMES:
647 continue
648
649 # FUTURE: this is horribly inefficient
650 for plugin_option_name in C.config.get_plugin_options_from_var("connection", current_connection, plugin_var_name):
651 utr.callback_delegated_vars_subset[plugin_var_name] = self._connection.get_option(plugin_option_name)
652
653 # and return
654 display.debug("attempt loop complete, returning result")
655 return utr
656
657 def _poll_async_result(self, utr: UnifiedTaskResult, templar: TemplateEngine, task_vars: dict[str, t.Any]) -> UnifiedTaskResult:
658 """
659 Polls for the specified JID to be complete
660 """
661 async_jid = utr.async_job_id
662
663 if async_jid is None:
664 # RPFIX-9: FUTURE: why not raise?
665 with UnifiedTaskResult.create_and_record() as utr:
666 utr.failed = True
667 utr.msg = "No job id was returned by the async task"
668
669 return utr
670
671 # Create a new pseudo-task to run the async_status module, and run
672 # that (with a sleep for "poll" seconds between each retry) until the
673 # async time limit is exceeded.
674
675 async_task = Task.load(dict(
676 action='async_status',
677 args={'jid': async_jid},
678 check_mode=self._task.check_mode,
679 environment=self._task.environment,
680 delegate_to=self._task.delegate_to,
681 ))
682
683 # ensure that the synthetic async task has the resolved connection recorded on it
684 self._update_task_connection(async_task)
685
686 # FIXME: this is no longer the case, normal takes care of all, see if this can just be generalized
687 # Because this is an async task, the action handler is async. However,
688 # we need the 'normal' action handler for the status check, so get it
689 # now via the action_loader
690 async_handler: ActionBase = self._shared_loader_obj.action_loader.get(
691 'ansible.legacy.async_status',
692 task=async_task,
693 connection=self._connection,
694 play_context=self._play_context,
695 loader=self._loader,
696 templar=Templar._from_template_engine(templar),
697 shared_loader_obj=self._shared_loader_obj,
698 )
699
700 time_left = self._task.async_val
701 while time_left > 0:
702 time.sleep(self._task.poll)
703
704 try:
705 with UnifiedTaskResult.create_and_record(async_handler.run(task_vars=task_vars)) as async_utr:
706 pass
707 # We do not bail out of the loop in cases where the failure
708 # is associated with a parsing error. The async_runner can
709 # have issues which result in a half-written/unparsable result
710 # file on disk, which manifests to the user as a timeout happening
711 # before it's time to timeout.
712 if async_utr.finished or (async_utr.failed and async_utr.ansible_parsed) or async_utr.skipped:
713 break
714 except Exception as e:
715 # Connections can raise exceptions during polling (eg, network bounce, reboot); these should be non-fatal.
716 # On an exception, call the connection's reset method if it has one
717 # (eg, drop/recreate WinRM connection; some reused connections are in a broken state)
718 display.vvvv("Exception during async poll, retrying... (%s)" % to_text(e))
719 display.debug("Async poll exception was:\n%s" % to_text(traceback.format_exc()))
720 try:
721 async_handler._connection.reset()
722 except AttributeError:
723 pass
724
725 # Little hack to raise the exception if we've exhausted the timeout period
726 time_left -= self._task.poll
727 if time_left <= 0:
728 raise
729 else:
730 time_left -= self._task.poll
731 self._final_q.send_callback('v2_runner_on_async_poll', self._host, async_task, async_utr)
732
733 if not async_utr.finished:
734 # RPFIX-9: FUTURE: why not raise?
735 with UnifiedTaskResult.create_and_record() as async_failed_utr:
736 async_failed_utr.failed = True
737 async_failed_utr.async_result = async_utr.as_result_dict()
738
739 if async_failed_utr.async_result.pop("ansible_parsed", None):
740 async_failed_utr.msg = "async task did not complete within the requested time - %ss" % self._task.async_val
741 else:
742 async_failed_utr.msg = "async task produced unparsable results"
743
744 async_utr = async_failed_utr # replace the actual async result with a synthesized failure
745 else:
746 # If the async task finished, automatically cleanup the temporary
747 # status file left behind.
748 cleanup_task = Task.load(
749 {
750 'async_status': {
751 'jid': async_jid,
752 'mode': 'cleanup',
753 },
754 'check_mode': self._task.check_mode,
755 'environment': self._task.environment,
756 'delegate_to': self._task.delegate_to,
757 }
758 )
759 cleanup_handler: ActionBase = self._shared_loader_obj.action_loader.get(
760 'ansible.legacy.async_status',
761 task=cleanup_task,
762 connection=self._connection,
763 play_context=self._play_context,
764 loader=self._loader,
765 templar=Templar._from_template_engine(templar),
766 shared_loader_obj=self._shared_loader_obj,
767 )
768 cleanup_handler.run(task_vars=task_vars)
769 cleanup_handler.cleanup(force=True)
770 async_handler.cleanup(force=True)
771
772 return async_utr
773
774 def _get_become(self, name):
775 become = become_loader.get(name)
776 if not become:
777 raise AnsibleError("Invalid become method specified, could not find matching plugin: '%s'. "
778 "Use `ansible-doc -t become -l` to list available plugins." % name)
779 return become
780
781 def _get_connection(self, cvars, templar, current_connection):
782 """
783 Reads the connection property for the host, and returns the
784 correct connection object from the list of connection plugins
785 """
786
787 self._play_context.connection = current_connection
788
789 conn_type = self._play_context.connection
790
791 connection, plugin_load_context = self._shared_loader_obj.connection_loader.get_with_context(
792 conn_type,
793 self._play_context,
794 new_stdin=None, # No longer used, kept for backwards compat for plugins that explicitly accept this as an arg
795 task_uuid=self._task._uuid,
796 ansible_playbook_pid=to_text(os.getppid())
797 )
798
799 if not connection:
800 raise AnsibleError("the connection plugin '%s' was not found" % conn_type)
801
802 self._set_become_plugin(cvars, templar, connection)
803
804 # Also backwards compat call for those still using play_context
805 self._play_context.set_attributes_from_plugin(connection)
806
807 return connection
808
809 def _set_become_plugin(self, cvars, templar, connection):
810 # load become plugin if needed
811 if cvars.get('ansible_become') is not None:
812 become = boolean(templar.template(cvars['ansible_become']))
813 else:
814 become = self._task.become
815
816 if become:
817 if cvars.get('ansible_become_method'):
818 become_plugin = self._get_become(templar.template(cvars['ansible_become_method']))
819 else:
820 become_plugin = self._get_become(self._task.become_method)
821
822 else:
823 # If become is not enabled on the task it needs to be removed from the connection plugin
824 # https://github.com/ansible/ansible/issues/78425
825 become_plugin = None
826
827 try:
828 connection.set_become_plugin(become_plugin)
829 except AttributeError:
830 # Older connection plugin that does not support set_become_plugin
831 pass
832
833 if become_plugin:
834 if getattr(connection.become, 'require_tty', False) and not getattr(connection, 'has_tty', False):
835 raise AnsibleError(
836 "The '%s' connection does not provide a TTY which is required for the selected "
837 "become plugin: %s." % (connection._load_name, become_plugin.name)
838 )
839
840 # Backwards compat for connection plugins that don't support become plugins
841 # Just do this unconditionally for now, we could move it inside of the
842 # AttributeError above later
843 self._play_context.set_become_plugin(become_plugin.name)
844
845 def _set_plugin_options(self, plugin_type, variables, templar, task_keys):
846 try:
847 plugin = getattr(self._connection, '_%s' % plugin_type)
848 except AttributeError:
849 # Some plugins are assigned to private attrs, ``become`` is not
850 plugin = getattr(self._connection, plugin_type)
851
852 # network_cli's "real" connection plugin is not named connection
853 # to avoid the confusion of having connection.connection
854 if plugin_type == "ssh_type_conn":
855 plugin_type = "connection"
856 option_vars = C.config.get_plugin_vars(plugin_type, plugin._load_name)
857 options = {}
858 for k in option_vars:
859 if k in variables:
860 try:
861 options[k] = templar.template(variables[k])
862 except AnsibleValueOmittedError:
863 pass
864
865 # TODO move to task method?
866 plugin.set_options(task_keys=task_keys, var_options=options)
867
868 return option_vars
869
870 def _set_connection_options(self, variables, templar):
871
872 # keep list of variable names possibly consumed
873 varnames = []
874
875 # grab list of usable vars for this plugin
876 option_vars = C.config.get_plugin_vars('connection', self._connection._load_name)
877 varnames.extend(option_vars)
878
879 task_keys = self._task.dump_attrs()
880
881 # The task_keys 'timeout' attr is the task's timeout, not the connection timeout.
882 # The connection timeout is threaded through the play_context for now.
883 task_keys['timeout'] = self._play_context.timeout
884
885 if self._play_context.password:
886 # The connection password is threaded through the play_context for
887 # now. This is something we ultimately want to avoid, but the first
888 # step is to get connection plugins pulling the password through the
889 # config system instead of directly accessing play_context.
890 task_keys['password'] = self._play_context.password
891
892 # Prevent task retries from overriding connection retries
893 del task_keys['retries']
894
895 # set options with 'templated vars' specific to this plugin and dependent ones
896 var_options = self._connection._resolve_option_variables(variables, templar)
897 self._connection.set_options(task_keys=task_keys, var_options=var_options)
898 varnames.extend(self._set_plugin_options('shell', variables, templar, task_keys))
899
900 if self._connection.become is not None:
901 if self._play_context.become_pass:
902 # FIXME: eventually remove from task and play_context, here for backwards compat
903 # keep out of play objects to avoid accidental disclosure, only become plugin should have
904 # The become pass is already in the play_context if given on
905 # the CLI (-K). Make the plugin aware of it in this case.
906 task_keys['become_pass'] = self._play_context.become_pass
907
908 varnames.extend(self._set_plugin_options('become', variables, templar, task_keys))
909
910 # FOR BACKWARDS COMPAT:
911 for option in ('become_user', 'become_flags', 'become_exe', 'become_pass'):
912 try:
913 setattr(self._play_context, option, self._connection.become.get_option(option))
914 except KeyError:
915 pass # some plugins don't support all base flags
916 self._play_context.prompt = self._connection.become.prompt
917
918 # deals with networking sub_plugins (network_cli/httpapi/netconf)
919 sub = getattr(self._connection, '_sub_plugin', None)
920 if sub and sub.get('type') != 'external':
921 plugin_type = get_plugin_class(sub.get("obj"))
922 varnames.extend(self._set_plugin_options(plugin_type, variables, templar, task_keys))
923 sub_conn = getattr(self._connection, 'ssh_type_conn', None)
924 if sub_conn is not None:
925 varnames.extend(self._set_plugin_options("ssh_type_conn", variables, templar, task_keys))
926
927 return varnames
928
929 def _get_action_handler(self, templar: TemplateEngine) -> ActionBase:
930 """
931 Returns the correct action plugin to handle the requestion task action
932 """
933 return self._get_action_handler_with_module_context(templar)[0]
934
935 def _get_action_handler_with_module_context(self, templar: TemplateEngine) -> tuple[ActionBase, PluginLoadContext]:
936 """
937 Returns the correct action plugin to handle the requestion task action and the module context
938 """
939 module_collection, separator, module_name = self._task.action.rpartition(".")
940 module_prefix = module_name.split('_')[0]
941 if module_collection:
942 # For network modules, which look for one action plugin per platform, look for the
943 # action plugin in the same collection as the module by prefixing the action plugin
944 # with the same collection.
945 network_action = "{0}.{1}".format(module_collection, module_prefix)
946 else:
947 network_action = module_prefix
948
949 collections = self._task.collections
950
951 # Check if the module has specified an action handler
952 module = self._shared_loader_obj.module_loader.find_plugin_with_context(
953 self._task.action, collection_list=collections
954 )
955 if not module.resolved or not module.action_plugin:
956 module = None
957 if module is not None:
958 handler_name = module.action_plugin
959 # let action plugin override module, fallback to 'normal' action plugin otherwise
960 elif self._shared_loader_obj.action_loader.has_plugin(self._task.action, collection_list=collections):
961 handler_name = self._task.action
962 elif module_prefix in C.NETWORK_GROUP_MODULES and self._shared_loader_obj.action_loader.has_plugin(network_action, collection_list=collections):
963 handler_name = network_action
964 display.vvvv("Using network group action {handler} for {action}".format(handler=handler_name,
965 action=self._task.action),
966 host=self._play_context.remote_addr)
967 else:
968 # use ansible.legacy.normal to allow (historic) local action_plugins/ override without collections search
969 handler_name = 'ansible.legacy.normal'
970 collections = None # until then, we don't want the task's collection list to be consulted; use the builtin
971
972 # networking/psersistent connections handling
973 if any(((self._connection.supports_persistence and C.USE_PERSISTENT_CONNECTIONS), self._connection.force_persistence)):
974
975 # check handler in case we dont need to do all the work to setup persistent connection
976 handler_class = self._shared_loader_obj.action_loader.get(handler_name, class_only=True)
977 if getattr(handler_class, '_requires_connection', True):
978 # for persistent connections, initialize socket path and start connection manager
979 self._play_context.timeout = self._connection.get_option('persistent_command_timeout')
980 display.vvvv('attempting to start connection', host=self._play_context.remote_addr)
981 display.vvvv('using connection plugin %s' % self._connection.transport, host=self._play_context.remote_addr)
982
983 options = self._connection.get_options()
984 socket_path = start_connection(self._play_context, options, self._task._uuid)
985 display.vvvv('local domain socket path is %s' % socket_path, host=self._play_context.remote_addr)
986 setattr(self._connection, '_socket_path', socket_path)
987 else:
988 # TODO: set self._connection to dummy/noop connection, using local for now
989 self._connection = self._get_connection({}, templar, 'local')
990
991 handler = self._shared_loader_obj.action_loader.get(
992 handler_name,
993 task=self._task,
994 connection=self._connection,
995 play_context=self._play_context,
996 loader=self._loader,
997 templar=Templar._from_template_engine(templar),
998 shared_loader_obj=self._shared_loader_obj,
999 collection_list=collections
1000 )
1001
1002 if not handler:
1003 raise AnsibleError("the handler '%s' was not found" % handler_name)
1004
1005 return handler, module
1006
1007
1008 CLI_STUB_NAME = 'ansible_connection_cli_stub.py'
1009
1010
1011 def start_connection(play_context, options, task_uuid):
1012 """
1013 Starts the persistent connection
1014 """
1015
1016 env = os.environ.copy()
1017 env.update({
1018 # HACK; most of these paths may change during the controller's lifetime
1019 # (eg, due to late dynamic role includes, multi-playbook execution), without a way
1020 # to invalidate/update, the persistent connection helper won't always see the same plugins the controller
1021 # can.
1022 'ANSIBLE_BECOME_PLUGINS': become_loader.print_paths(),
1023 'ANSIBLE_CLICONF_PLUGINS': cliconf_loader.print_paths(),
1024 'ANSIBLE_COLLECTIONS_PATH': to_native(os.pathsep.join(AnsibleCollectionConfig.collection_paths)),
1025 'ANSIBLE_CONNECTION_PLUGINS': connection_loader.print_paths(),
1026 'ANSIBLE_HTTPAPI_PLUGINS': httpapi_loader.print_paths(),
1027 'ANSIBLE_NETCONF_PLUGINS': netconf_loader.print_paths(),
1028 'ANSIBLE_TERMINAL_PLUGINS': terminal_loader.print_paths(),
1029 })
1030 verbosity = []
1031 if display.verbosity:
1032 verbosity.append('-%s' % ('v' * display.verbosity))
1033
1034 if not (cli_stub_path := C.config.get_config_value('_ANSIBLE_CONNECTION_PATH')):
1035 cli_stub_path = str(pathlib.Path(scripts.__file__).parent / CLI_STUB_NAME)
1036
1037 p = subprocess.Popen(
1038 [sys.executable, cli_stub_path, *verbosity, to_text(os.getppid()), to_text(task_uuid)],
1039 stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
1040 )
1041
1042 write_to_stream(p.stdin, options)
1043 write_to_stream(p.stdin, play_context.dump_attrs())
1044
1045 (stdout, stderr) = p.communicate()
1046
1047 if p.returncode == 0:
1048 result = json.loads(to_text(stdout, errors='surrogate_then_replace'))
1049 else:
1050 try:
1051 result = json.loads(to_text(stderr, errors='surrogate_then_replace'))
1052 except json.decoder.JSONDecodeError:
1053 result = {'error': to_text(stderr, errors='surrogate_then_replace')}
1054
1055 if 'messages' in result:
1056 for level, message in result['messages']:
1057 if level == 'log':
1058 display.display(message, log_only=True)
1059 elif level in ('debug', 'v', 'vv', 'vvv', 'vvvv', 'vvvvv', 'vvvvvv'):
1060 getattr(display, level)(message, host=play_context.remote_addr)
1061 else:
1062 if hasattr(display, level):
1063 getattr(display, level)(message)
1064 else:
1065 display.vvvv(message, host=play_context.remote_addr)
1066
1067 if 'error' in result:
1068 if display.verbosity > 2:
1069 if result.get('exception'):
1070 msg = "The full traceback is:\n" + result['exception']
1071 display.display(msg, color=C.COLOR_ERROR)
1072 raise AnsibleError(result['error'])
1073
1074 return result['socket_path']