Debian Codegraph @

lib/ansible/plugins/strategy/__init__.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import cmd
21 import functools
22 import os
23 import pprint
24 import queue
25 import sys
26 import threading
27 import time
28 import typing as t
29 import collections.abc as _c
30
31 from collections import deque
32
33 from ansible import constants as C, constants
34 from ansible import context
35 from ansible.errors import AnsibleError, AnsibleTemplateError
36 from ansible.executor.play_iterator import IteratingStates, PlayIterator
37 from ansible.executor.process.worker import WorkerProcess
38 from ansible._internal._task import WireTaskResult, HostTaskResult
39 from ansible.executor.task_queue_manager import CallbackSend, DisplaySend, PromptSend, TaskQueueManager
40 from ansible.module_utils.common.text.converters import to_text
41 from ansible.module_utils.connection import Connection, ConnectionError
42 from ansible.playbook.handler import Handler
43 from ansible.playbook.helpers import load_list_of_blocks
44 from ansible.playbook.included_file import IncludedFile
45 from ansible.playbook.play_context import PlayContext
46 from ansible.playbook.task import Task
47 from ansible.playbook.task_include import TaskInclude
48 from ansible.plugins import loader as plugin_loader
49 from ansible._internal._templating._engine import TemplateEngine
50 from ansible.utils.display import Display
51 from ansible.utils.fqcn import add_internal_fqcns
52 from ansible.utils.sentinel import Sentinel
53 from ansible._internal import _task, _rpc_host
54
55 if t.TYPE_CHECKING:
56 from ansible.playbook.role_include import IncludeRole
57
58 display = Display()
59
60 __all__ = ['StrategyBase']
61
62
63 class StrategySentinel:
64 pass
65
66
67 _sentinel = StrategySentinel()
68
69 if t.TYPE_CHECKING:
70 from ansible.inventory.host import Host
71
72
73 def _get_item_vars(utr: _task.UnifiedTaskResult, task: Task) -> dict[str, object]:
74 # RPFIX-9: FUTURE: need a more consistent way to reconstitute/replay loop state controller-side (may be resolved when RPC is implemented)
75 item_vars = {}
76
77 if task.loop or task.loop_with:
78 if utr.loop_var is not None:
79 item_vars[utr.loop_var] = utr.loop_item
80 if utr.loop_index_var is not None:
81 item_vars[utr.loop_index_var] = utr.loop_index
82 if utr.loop_item_label is not None:
83 item_vars['_ansible_item_label'] = utr.loop_item_label
84 if utr.loop_extended is not None:
85 item_vars['ansible_loop'] = utr.loop_extended
86
87 return item_vars
88
89
90 def results_thread_main(strategy: StrategyBase) -> None:
91 value: object
92
93 while True:
94 try:
95 result = strategy._final_q.get()
96 if isinstance(result, StrategySentinel):
97 break
98 elif isinstance(result, DisplaySend):
99 dmethod = getattr(display, result.method)
100 dmethod(*result.args, **result.kwargs)
101 elif isinstance(result, CallbackSend):
102 task_result = strategy._convert_wire_task_result_to_host_task_result(result.wire_task_result)
103 strategy._tqm.send_callback(result.method_name, task_result)
104 elif isinstance(result, WireTaskResult):
105 result = strategy._convert_wire_task_result_to_host_task_result(result)
106 with strategy._results_lock:
107 strategy._results.append(result)
108 elif isinstance(result, PromptSend):
109 try:
110 value = display.prompt_until(
111 result.prompt,
112 private=result.private,
113 seconds=result.seconds,
114 complete_input=result.complete_input,
115 interrupt_input=result.interrupt_input,
116 )
117 except AnsibleError as e:
118 value = e
119 except BaseException as e:
120 # relay unexpected errors so bugs in display are reported and don't cause workers to hang
121 try:
122 raise AnsibleError(f"{e}") from e
123 except AnsibleError as e:
124 value = e
125 strategy._workers[result.worker_id].worker_queue.put(value)
126 else:
127 display.warning('Received an invalid object (%s) in the result queue: %r' % (type(result), result))
128 except (OSError, EOFError):
129 break
130 except queue.Empty:
131 pass
132
133
134 def debug_closure(func):
135 """Closure to wrap ``StrategyBase._process_pending_results`` and invoke the task debugger"""
136 @functools.wraps(func)
137 def inner(self, iterator: PlayIterator, one_pass: bool = False, max_passes: int | None = None) -> list[HostTaskResult]:
138 status_to_stats_map = (
139 ('failed', 'failures'),
140 ('unreachable', 'dark'),
141 ('changed', 'changed'),
142 ('skipped', 'skipped'),
143 )
144
145 # We don't know the host yet, copy the previous states, for lookup after we process new results
146 prev_host_states = iterator.host_states.copy()
147
148 results: list[HostTaskResult] = func(self, iterator, one_pass=one_pass, max_passes=max_passes)
149 _processed_results: list[HostTaskResult] = []
150
151 for result in results:
152 task = result.task
153 host = result.host
154 _queued_task_args = self._queued_task_cache.pop((host.name, task._uuid), None)
155 task_vars = _queued_task_args['task_vars']
156 play_context = _queued_task_args['play_context']
157 # Try to grab the previous host state, if it doesn't exist use get_host_state to generate an empty state
158 try:
159 prev_host_state = prev_host_states[host.name]
160 except KeyError:
161 prev_host_state = iterator.get_host_state(host)
162
163 while _needs_debugger(task=result.task, utr=result.utr, globally_enabled=self.debugger_active):
164 next_action = NextAction()
165 dbg = Debugger(task, host, task_vars, play_context, result, next_action)
166 dbg.cmdloop()
167
168 if next_action.result == NextAction.REDO:
169 # rollback host state
170 self._tqm.clear_failed_hosts()
171 if task.run_once and iterator._play.strategy in add_internal_fqcns(('linear',)) and result.utr.failed:
172 for host_name, state in prev_host_states.items():
173 if host_name == host.name:
174 continue
175 iterator.set_state_for_host(host_name, state)
176 iterator._play._removed_hosts.remove(host_name)
177 iterator.set_state_for_host(host.name, prev_host_state)
178 for attr, what in status_to_stats_map:
179 if getattr(result.utr, attr):
180 self._tqm._stats.decrement(what, host.name)
181 self._tqm._stats.decrement('ok', host.name)
182
183 # redo
184 self._queue_task(host, task, task_vars, play_context)
185
186 _processed_results.extend(debug_closure(func)(self, iterator, one_pass))
187 break
188 elif next_action.result == NextAction.CONTINUE:
189 _processed_results.append(result)
190 break
191 elif next_action.result == NextAction.EXIT:
192 # Matches KeyboardInterrupt from bin/ansible
193 sys.exit(99)
194 else:
195 _processed_results.append(result)
196
197 return _processed_results
198 return inner
199
200
201 def _needs_debugger(task: Task, utr: _task.UnifiedTaskResult, globally_enabled: bool = False) -> bool:
202 ignore_errors: bool = constants.config.get_config_value('TASK_DEBUGGER_IGNORE_ERRORS') and utr.ignore_errors
203 ret = globally_enabled and ((utr.failed and not ignore_errors) or bool(utr.unreachable))
204
205 match task.debugger:
206 case 'always':
207 ret = True
208 case 'never':
209 ret = False
210 case 'on_failed' if utr.failed and not ignore_errors:
211 ret = True
212 case 'on_unreachable' if utr.unreachable:
213 ret = True
214 case 'on_skipped' if utr.skipped:
215 ret = True
216
217 return ret
218
219
220 class StrategyBase:
221
222 """
223 This is the base class for strategy plugins, which contains some common
224 code useful to all strategies like running handlers, cleanup actions, etc.
225 """
226
227 # by default, strategies should support throttling but we allow individual
228 # strategies to disable this and either forego supporting it or managing
229 # the throttling internally (as `free` does)
230 ALLOW_BASE_THROTTLING = True
231
232 def __init__(self, tqm: TaskQueueManager) -> None:
233 self._tqm = tqm
234 self._inventory = tqm.get_inventory()
235 self._workers = tqm._workers
236 self._variable_manager = tqm.get_variable_manager()
237 self._loader = tqm.get_loader()
238 self._final_q = tqm._final_q
239 self._step = context.CLIARGS.get('step', False)
240 self._diff = context.CLIARGS.get('diff', False)
241 self._rpc_queue: queue.Queue[_rpc_host.AsyncRPCOperation] = queue.Queue()
242 """Pending worker AsyncRPCOperations that need to be serviced under the result thread."""
243
244 # the task cache is a dictionary of tuples of (host.name, task._uuid)
245 # used to find the original task object of in-flight tasks and to store
246 # the task args/vars and play context info used to queue the task.
247 self._queued_task_cache: dict[tuple[str, str], dict[str, t.Any]] = {}
248
249 # Backwards compat: self._display isn't really needed, just import the global display and use that.
250 self._display = display
251
252 # internal counters
253 self._pending_results = 0
254 self._cur_worker = 0
255
256 # this dictionary is used to keep track of hosts that have
257 # outstanding tasks still in queue
258 self._blocked_hosts: dict[str, bool] = dict()
259
260 self._results: deque[HostTaskResult] = deque()
261 self._results_lock = threading.Condition(threading.Lock())
262
263 # create the result processing thread for reading results in the background
264 self._results_thread = threading.Thread(target=results_thread_main, args=(self,))
265 self._results_thread.daemon = True
266 self._results_thread.start()
267
268 # holds the list of active (persistent) connections to be shutdown at
269 # play completion
270 self._active_connections: dict[Host, str] = dict()
271
272 # Caches for get_host calls, to avoid calling excessively
273 # These values should be set at the top of the ``run`` method of each
274 # strategy plugin. Use ``_set_hosts_cache`` to set these values
275 self._hosts_cache: list[str] = []
276 self._hosts_cache_all: list[str] = []
277
278 self.debugger_active = C.ENABLE_TASK_DEBUGGER
279
280 def _set_hosts_cache(self, play, refresh=True):
281 """Responsible for setting _hosts_cache and _hosts_cache_all
282
283 See comment in ``__init__`` for the purpose of these caches
284 """
285 if not refresh and all((self._hosts_cache, self._hosts_cache_all)):
286 return
287
288 if not play.finalized and TemplateEngine().is_template(play.hosts):
289 _pattern = 'all'
290 else:
291 _pattern = play.hosts or 'all'
292 self._hosts_cache_all = [h.name for h in self._inventory.get_hosts(pattern=_pattern, ignore_restrictions=True)]
293 self._hosts_cache = [h.name for h in self._inventory.get_hosts(play.hosts, order=play.order)]
294
295 def cleanup(self):
296 # close active persistent connections
297 for sock in self._active_connections.values():
298 try:
299 conn = Connection(sock)
300 conn.reset()
301 except ConnectionError as e:
302 # most likely socket is already closed
303 display.debug("got an error while closing persistent connection: %s" % e)
304 self._final_q.put(_sentinel)
305 self._results_thread.join()
306
307 def run(self, iterator: PlayIterator, play_context: PlayContext, result=0):
308 # execute one more pass through the iterator without peeking, to
309 # make sure that all of the hosts are advanced to their final task.
310 # This should be safe, as everything should be IteratingStates.COMPLETE by
311 # this point, though the strategy may not advance the hosts itself.
312
313 for host in self._hosts_cache:
314 if host not in self._tqm._unreachable_hosts:
315 try:
316 iterator.get_next_task_for_host(self._inventory.hosts[host])
317 except KeyError:
318 iterator.get_next_task_for_host(self._inventory.get_host(host))
319
320 # return the appropriate code, depending on the status hosts after the run
321 if not isinstance(result, bool) and result != self._tqm.RUN_OK:
322 return result
323 elif len(self._tqm._unreachable_hosts.keys()) > 0:
324 return self._tqm.RUN_UNREACHABLE_HOSTS
325 elif len(iterator.get_failed_hosts()) > 0:
326 return self._tqm.RUN_FAILED_HOSTS
327 else:
328 return self._tqm.RUN_OK
329
330 def get_hosts_remaining(self, play):
331 self._set_hosts_cache(play, refresh=False)
332 ignore = set(self._tqm._failed_hosts).union(self._tqm._unreachable_hosts)
333 return [host for host in self._hosts_cache if host not in ignore]
334
335 def get_failed_hosts(self, play):
336 self._set_hosts_cache(play, refresh=False)
337 return [host for host in self._hosts_cache if host in self._tqm._failed_hosts]
338
339 def add_tqm_variables(self, vars, play):
340 """
341 Base class method to add extra variables/information to the list of task
342 vars sent through the executor engine regarding the task queue manager state.
343 """
344 vars['ansible_current_hosts'] = self.get_hosts_remaining(play)
345 vars['ansible_failed_hosts'] = self.get_failed_hosts(play)
346
347 def _queue_task(self, host, task, task_vars, play_context):
348 """ handles queueing the task up to be sent to a worker """
349
350 display.debug("entering _queue_task() for %s/%s" % (host.name, task.action))
351
352 # create a templar and template things we need later for the queuing process
353 templar = TemplateEngine(loader=self._loader, variables=task_vars)
354
355 try:
356 throttle = int(templar.template(task.throttle))
357 except Exception as ex:
358 raise AnsibleError("Failed to convert the throttle value to an integer.", obj=task.throttle) from ex
359
360 # and then queue the new task
361 try:
362 # Determine the "rewind point" of the worker list. This means we start
363 # iterating over the list of workers until the end of the list is found.
364 # Normally, that is simply the length of the workers list (as determined
365 # by the forks or serial setting), however a task/block/play may "throttle"
366 # that limit down.
367 rewind_point = len(self._workers)
368 if throttle > 0 and self.ALLOW_BASE_THROTTLING:
369 if task.run_once:
370 display.debug("Ignoring 'throttle' as 'run_once' is also set for '%s'" % task.get_name())
371 else:
372 if throttle <= rewind_point:
373 display.debug("task: %s, throttle: %d" % (task.get_name(), throttle))
374 rewind_point = throttle
375
376 queued = False
377 starting_worker = self._cur_worker
378 while True:
379 self._process_rpc_queue()
380
381 if self._cur_worker >= rewind_point:
382 self._cur_worker = 0
383
384 worker_prc = self._workers[self._cur_worker]
385 if worker_prc is None or not worker_prc.is_alive():
386 if worker_prc:
387 worker_prc.close()
388
389 self._blocked_hosts[host.name] = True
390 self._queued_task_cache[(host.name, task._uuid)] = {
391 'host': host,
392 'task': task,
393 'task_vars': task_vars,
394 'play_context': play_context
395 }
396
397 # Pass WorkerProcess its strategy worker number so it can send an identifier along with intra-task requests
398 worker_prc = WorkerProcess(
399 final_q=self._final_q,
400 task_vars=task_vars,
401 host=host,
402 task=task,
403 play_context=play_context,
404 loader=self._loader,
405 variable_manager=self._variable_manager,
406 shared_loader_obj=plugin_loader.get_plugin_loader_namespace(),
407 worker_id=self._cur_worker,
408 cliargs=context.CLIARGS,
409 stacktrace_dir=self._tqm.stacktrace_dir
410 )
411 self._workers[self._cur_worker] = worker_prc
412 self._tqm.send_callback('v2_runner_on_start', host, task)
413 worker_prc.start()
414 display.debug("worker is %d (out of %d available)" % (self._cur_worker + 1, len(self._workers)))
415 queued = True
416
417 self._cur_worker += 1
418
419 if self._cur_worker >= rewind_point:
420 self._cur_worker = 0
421
422 if queued:
423 break
424 elif self._cur_worker == starting_worker:
425 time.sleep(0.0001)
426
427 self._pending_results += 1
428 except (EOFError, OSError, AssertionError) as ex:
429 # most likely an abort
430 display.debug(f"got an error while queuing: {ex}")
431 return
432 display.debug("exiting _queue_task() for %s/%s" % (host.name, task.action))
433
434 def get_task_hosts(self, iterator, task_host, task):
435 if task.run_once:
436 host_list = [host for host in self._hosts_cache if host not in self._tqm._unreachable_hosts]
437 else:
438 host_list = [task_host.name]
439 return host_list
440
441 def _convert_wire_task_result_to_host_task_result(self, wire_task_result: WireTaskResult) -> HostTaskResult:
442 """Rehydrate a `HostTaskResult` from a serialized `WireTaskResult`."""
443 host = self._inventory.get_host(wire_task_result.host_name)
444 queue_cache_entry = (host.name, wire_task_result.task_uuid)
445
446 try:
447 found_task = self._queued_task_cache[queue_cache_entry]['task']
448 except KeyError:
449 # This should only happen due to an implicit task created by the
450 # TaskExecutor, restrict this behavior to the explicit use case
451 # of an implicit async_status task
452 if wire_task_result.task_fields.get('action') != 'async_status':
453 raise
454
455 task = Task()
456 else:
457 task = found_task.copy(exclude_parent=True, exclude_tasks=True)
458 task._parent = found_task._parent
459
460 task.from_attrs(wire_task_result.task_fields)
461
462 return HostTaskResult(
463 host=host,
464 task=task,
465 utr=wire_task_result.utr,
466 )
467
468 def search_handlers_by_notification(self, notification: str, iterator: PlayIterator) -> t.Generator[Handler, None, None]:
469 handlers = [h for b in reversed(iterator._play.handlers) for h in b.block]
470 # iterate in reversed order since last handler loaded with the same name wins
471 for handler in handlers:
472 if not handler.name:
473 continue
474
475 if not handler.cached_name:
476 def variables_factory() -> dict[str, t.Any]:
477 return self._variable_manager.get_vars(
478 play=iterator._play,
479 task=handler,
480 _hosts=self._hosts_cache,
481 _hosts_all=self._hosts_cache_all
482 )
483
484 templar = TemplateEngine(variables_factory=variables_factory)
485
486 try:
487 handler.name = templar.template(handler.name)
488 except AnsibleTemplateError as e:
489 # We skip this handler due to the fact that it may be using
490 # a variable in the name that was conditionally included via
491 # set_fact or some other method, and we don't want to error
492 # out unnecessarily
493 if not handler.listen:
494 display.warning(
495 "Handler '%s' is unusable because it has no listen topics and "
496 "the name could not be templated (host-specific variables are "
497 "not supported in handler names). The error: %s" % (handler.name, to_text(e))
498 )
499 continue
500
501 handler.cached_name = True
502
503 # first we check with the full result of get_name(), which may
504 # include the role name (if the handler is from a role). If that
505 # is not found, we resort to the simple name field, which doesn't
506 # have anything extra added to it.
507 if notification in {
508 handler.name,
509 handler.get_name(include_role_fqcn=False),
510 handler.get_name(include_role_fqcn=True),
511 }:
512 yield handler
513 break
514
515 seen = set()
516 for handler in handlers:
517 if notification in handler.listen:
518 if handler.name and handler.name in seen:
519 continue
520 seen.add(handler.name)
521 yield handler
522
523 def _process_rpc_queue(self) -> None:
524 try:
525 while True:
526 rpc_request = self._rpc_queue.get(block=False)
527 rpc_request.dispatch()
528 except queue.Empty:
529 pass
530
531 @debug_closure
532 def _process_pending_results(self, iterator: PlayIterator, one_pass: bool = False, max_passes: int | None = None) -> list[HostTaskResult]:
533 """
534 Reads results off the final queue and takes appropriate action
535 based on the result (executing callbacks, updating state, etc.).
536 """
537 ret_results = []
538 cur_pass = 0
539
540 while True:
541 self._process_rpc_queue()
542
543 try:
544 self._results_lock.acquire()
545 task_result = self._results.popleft()
546 except IndexError:
547 break
548 finally:
549 self._results_lock.release()
550
551 original_host = task_result.host
552 original_task: Task = task_result.task
553
554 # all host status messages contain 2 entries: (msg, task_result)
555 role_ran = False
556
557 if task_result.utr.failed:
558 role_ran = True
559 ignore_errors = task_result.utr.ignore_errors
560
561 if not ignore_errors:
562 # save the current state before failing it for later inspection
563 state_when_failed = iterator.get_state_for_host(original_host.name)
564 display.debug("marking %s as failed" % original_host.name)
565
566 if original_task.run_once:
567 # if we're using run_once, we have to fail every host here
568 for h in self._inventory.get_hosts(iterator._play.hosts):
569 if h.name not in self._tqm._unreachable_hosts:
570 iterator.mark_host_failed(h)
571 else:
572 iterator.mark_host_failed(original_host)
573
574 state, dummy = iterator.get_next_task_for_host(original_host, peek=True)
575
576 if iterator.is_failed(original_host) and state and state.run_state == IteratingStates.COMPLETE:
577 self._tqm._failed_hosts[original_host.name] = True
578
579 # if we're iterating on the rescue portion of a block then
580 # we save the failed task in a special var for use
581 # within the rescue/always
582 if iterator.is_any_block_rescuing(state_when_failed):
583 self._tqm._stats.increment('rescued', original_host.name)
584
585 iterator._play._removed_hosts.remove(original_host.name)
586
587 self._variable_manager.set_nonpersistent_facts(
588 original_host.name,
589 dict(
590 ansible_failed_task=original_task.dump_attrs(),
591 ansible_failed_result=task_result.utr.as_result_dict(),
592 ),
593 )
594 else:
595 self._tqm._stats.increment('failures', original_host.name)
596 else:
597 self._tqm._stats.increment('ok', original_host.name)
598 self._tqm._stats.increment('ignored', original_host.name)
599
600 if task_result.utr.changed:
601 self._tqm._stats.increment('changed', original_host.name)
602
603 self._tqm.send_callback('v2_runner_on_failed', task_result, ignore_errors=ignore_errors)
604 elif task_result.utr.unreachable:
605 if not task_result.utr.ignore_unreachable:
606 self._tqm._unreachable_hosts[original_host.name] = True
607
608 iterator._play._removed_hosts.append(original_host.name)
609
610 self._tqm._stats.increment('dark', original_host.name)
611 else:
612 self._tqm._stats.increment('ok', original_host.name)
613 self._tqm._stats.increment('ignored', original_host.name)
614
615 self._tqm.send_callback('v2_runner_on_unreachable', task_result)
616 elif task_result.utr.skipped:
617 self._tqm._stats.increment('skipped', original_host.name)
618 self._tqm.send_callback('v2_runner_on_skipped', task_result)
619 else:
620 role_ran = True
621
622 result_utrs: list[_task.UnifiedTaskResult]
623
624 if original_task.loop:
625 # this task had a loop, and has more than one result, so
626 # loop over all of them instead of a single result
627 result_utrs = task_result.utr.loop_results
628 else:
629 result_utrs = [task_result.utr]
630
631 for result_utr in result_utrs:
632 if result_utr.notify and task_result.utr.changed:
633 # only ensure that notified handlers exist, if so save the notifications for when
634 # handlers are actually flushed so the last defined handlers are executed,
635 # otherwise depending on the setting either error or warn
636 host_state = iterator.get_state_for_host(original_host.name)
637
638 for notification in result_utr.notify:
639 handler: type[Sentinel] | Handler = Sentinel
640
641 for handler in self.search_handlers_by_notification(notification, iterator):
642 if host_state.run_state == IteratingStates.HANDLERS:
643 # we're currently iterating handlers, so we need to expand this now
644 if handler.notify_host(original_host):
645 # NOTE even with notifications deduplicated this can still happen in case of handlers being
646 # notified multiple times using different names, like role name or fqcn
647 self._tqm.send_callback('v2_playbook_on_notify', handler, original_host)
648 else:
649 iterator.add_notification(original_host.name, notification)
650 display.vv(f"Notification for handler {notification} has been saved.")
651 break
652
653 if handler is Sentinel:
654 msg = (
655 f"The requested handler '{notification}' was not found in either the main handlers"
656 " list nor in the listening handlers list"
657 )
658
659 if C.ERROR_ON_MISSING_HANDLER:
660 raise AnsibleError(msg)
661
662 display.warning(msg)
663
664 if result_utr.pending_changes.register_host_variables:
665 original_host_list = self.get_task_hosts(iterator, original_host, original_task)
666
667 if original_task.delegate_to and original_task.delegate_facts:
668 potentially_delegated_host_list = [result_utr.delegated_host or original_task.delegate_to]
669 else:
670 potentially_delegated_host_list = original_host_list
671
672 # Apply changes from register_host_variables to variable manager in sorted order,
673 # to ensure consistent variable precedence based on layer.
674 for variable_layer, variables in sorted(result_utr.pending_changes.register_host_variables.items()):
675 match variable_layer:
676 case _task.VariableLayer.REGISTER_VARS:
677 for target_host in original_host_list:
678 self._variable_manager.set_nonpersistent_facts(target_host, variables)
679 case _task.VariableLayer.CACHEABLE_FACT:
680 for target_host in potentially_delegated_host_list:
681 self._variable_manager.set_host_facts(target_host, variables)
682 case _task.VariableLayer.EPHEMERAL_FACT:
683 for target_host in potentially_delegated_host_list:
684 self._variable_manager.set_nonpersistent_facts(target_host, variables)
685 case _task.VariableLayer.INCLUDE_VARS:
686 for target_host in potentially_delegated_host_list:
687 for var_name, var_value in variables.items():
688 self._variable_manager.set_host_variable(target_host, var_name, var_value)
689 case _:
690 raise NotImplementedError(f"Unsupported variable layer: {variable_layer}")
691
692 if result_utr.stats is not None:
693 stats_data = result_utr.stats['data']
694
695 if result_utr.stats.get('per_host'):
696 host_list = self.get_task_hosts(iterator, original_host, original_task)
697 else:
698 host_list = [None]
699
700 aggregate = result_utr.stats.get('aggregate')
701
702 for myhost in host_list:
703 for k in stats_data.keys():
704 if aggregate:
705 self._tqm._stats.update_custom_stats(k, stats_data[k], myhost)
706 else:
707 self._tqm._stats.set_custom_stats(k, stats_data[k], myhost)
708
709 if task_result.utr.diff is not None:
710 # this case is only for non-loops; loop item diff callbacks are dispatched directly by TaskExecutor
711 if self._diff or getattr(original_task, 'diff', False):
712 self._tqm.send_callback('v2_on_file_diff', task_result)
713
714 if not isinstance(original_task, TaskInclude):
715 self._tqm._stats.increment('ok', original_host.name)
716
717 if task_result.utr.changed:
718 self._tqm._stats.increment('changed', original_host.name)
719
720 # finally, send the ok for this task
721 self._tqm.send_callback('v2_runner_on_ok', task_result)
722
723 # register final results
724 if task_result.utr.registered_values:
725 host_list = self.get_task_hosts(iterator, original_host, original_task)
726
727 for target_host in host_list:
728 self._variable_manager.set_nonpersistent_facts(target_host, task_result.utr.registered_values)
729
730 self._pending_results -= 1
731
732 if original_host.name in self._blocked_hosts:
733 del self._blocked_hosts[original_host.name]
734
735 # If this is a role task, mark the parent role as being run (if
736 # the task was ok or failed, but not skipped or unreachable)
737 if original_task._role is not None and role_ran: # TODO: and original_task.action not in C._ACTION_INCLUDE_ROLE:?
738 # lookup the role in the role cache to make sure we're dealing
739 # with the correct object and mark it as executed
740 role_obj = self._get_cached_role(original_task, iterator._play)
741 role_obj._had_task_run[original_host.name] = True
742
743 ret_results.append(task_result)
744
745 if one_pass or max_passes is not None and (cur_pass + 1) >= max_passes:
746 break
747
748 cur_pass += 1
749
750 return ret_results
751
752 def _wait_on_pending_results(self, iterator):
753 """
754 Wait for the shared counter to drop to zero, using a short sleep
755 between checks to ensure we don't spin lock
756 """
757
758 ret_results = []
759
760 display.debug("waiting for pending results...")
761 while self._pending_results > 0 and not self._tqm._terminated:
762
763 if self._tqm.has_dead_workers():
764 raise AnsibleError("A worker was found in a dead state")
765
766 results = self._process_pending_results(iterator)
767 ret_results.extend(results)
768 if self._pending_results > 0:
769 time.sleep(C.DEFAULT_INTERNAL_POLL_INTERVAL)
770
771 display.debug("no more pending results, returning what we have")
772
773 return ret_results
774
775 def _copy_included_file(self, included_file: IncludedFile) -> TaskInclude | IncludeRole:
776 """
777 A proven safe and performant way to create a copy of an included file
778 """
779 ti_copy = included_file._task.copy(exclude_parent=True)
780 ti_copy._parent = included_file._task._parent
781
782 temp_vars = ti_copy.vars | included_file._vars
783
784 ti_copy.vars = temp_vars
785
786 return ti_copy
787
788 def _load_included_file(self, included_file: IncludedFile, iterator, is_handler=False):
789 """
790 Loads an included YAML file of tasks, applying the optional set of variables.
791
792 Raises AnsibleError exception in case of a failure during including a file,
793 in such case the caller is responsible for marking the host(s) as failed
794 using PlayIterator.mark_host_failed().
795 """
796 display.debug("loading included file: %s" % included_file._filename)
797 data = self._loader.load_from_file(included_file._filename, trusted_as_template=True)
798 if data is None:
799 return []
800 elif not isinstance(data, list):
801 raise AnsibleError("included task files must contain a list of tasks", obj=data)
802
803 ti_copy = self._copy_included_file(included_file)
804
805 block_list = load_list_of_blocks(
806 data,
807 play=iterator._play,
808 parent_block=ti_copy.build_parent_block(),
809 role=included_file._task._role,
810 use_handlers=is_handler,
811 loader=self._loader,
812 variable_manager=self._variable_manager,
813 )
814
815 display.debug("done processing included file")
816 return block_list
817
818 def _take_step(self, task, host=None):
819
820 ret = False
821 msg = u'Perform task: %s ' % task
822 if host:
823 msg += u'on %s ' % host
824 msg += u'(N)o/(y)es/(c)ontinue: '
825 resp = display.prompt(msg)
826
827 if resp.lower() in ['y', 'yes']:
828 display.debug("User ran task")
829 ret = True
830 elif resp.lower() in ['c', 'continue']:
831 display.debug("User ran task and canceled step mode")
832 self._step = False
833 ret = True
834 else:
835 display.debug("User skipped task")
836
837 display.banner(msg)
838
839 return ret
840
841 def _cond_not_supported_warn(self, task_name):
842 display.warning("%s task does not support when conditional" % task_name)
843
844 def _execute_meta(self, task: Task, play_context, iterator, target_host: Host):
845 task._resolved_action = 'ansible.builtin.meta' # _post_validate_args is never called for meta actions, so resolved_action hasn't been set
846
847 # meta tasks store their args in the _raw_params field of args,
848 # since they do not use k=v pairs, so get that
849 meta_action = task._get_meta()
850
851 def _evaluate_conditional(conditional_host: Host) -> bool:
852 if not task.when:
853 return True
854
855 # FUTURE: If this when fails it will take down the process.
856 return task._resolve_conditional(task.when, self._variable_manager.get_vars(
857 play=iterator._play, host=conditional_host, task=task, _hosts=self._hosts_cache, _hosts_all=self._hosts_cache_all))
858
859 skipped = False
860 msg = meta_action
861 skip_reason = '%s conditional evaluated to False' % meta_action
862 if isinstance(task, Handler):
863 self._tqm.send_callback('v2_playbook_on_handler_task_start', task)
864 else:
865 self._tqm.send_callback('v2_playbook_on_task_start', task, is_conditional=False)
866
867 # These don't support "when" conditionals
868 if meta_action in ('noop', 'refresh_inventory', 'reset_connection') and task.when:
869 self._cond_not_supported_warn(meta_action)
870
871 if meta_action == 'noop':
872 msg = "noop"
873 elif meta_action == 'flush_handlers':
874 if _evaluate_conditional(target_host):
875 host_state = iterator.get_state_for_host(target_host.name)
876 # actually notify proper handlers based on all notifications up to this point
877 for notification in list(host_state.handler_notifications):
878 for handler in self.search_handlers_by_notification(notification, iterator):
879 if handler.notify_host(target_host):
880 # NOTE even with notifications deduplicated this can still happen in case of handlers being
881 # notified multiple times using different names, like role name or fqcn
882 self._tqm.send_callback('v2_playbook_on_notify', handler, target_host)
883 iterator.clear_notification(target_host.name, notification)
884
885 if host_state.run_state == IteratingStates.HANDLERS:
886 raise AnsibleError('flush_handlers cannot be used as a handler')
887 if target_host.name not in self._tqm._unreachable_hosts:
888 host_state.pre_flushing_run_state = host_state.run_state
889 host_state.run_state = IteratingStates.HANDLERS
890 msg = "triggered running handlers for %s" % target_host.name
891 else:
892 skipped = True
893 skip_reason += ', not running handlers for %s' % target_host.name
894 elif meta_action == 'refresh_inventory':
895 self._inventory.refresh_inventory()
896 self._set_hosts_cache(iterator._play)
897 msg = "inventory successfully refreshed"
898 elif meta_action == 'clear_facts':
899 if _evaluate_conditional(target_host):
900 for host in self._inventory.get_hosts(iterator._play.hosts):
901 hostname = host.get_name()
902 self._variable_manager.clear_facts(hostname)
903 msg = "facts cleared"
904 else:
905 skipped = True
906 skip_reason += ', not clearing facts and fact cache for %s' % target_host.name
907 elif meta_action == 'clear_host_errors':
908 if _evaluate_conditional(target_host):
909 for host in self._inventory.get_hosts(iterator._play.hosts):
910 self._tqm._failed_hosts.pop(host.name, False)
911 self._tqm._unreachable_hosts.pop(host.name, False)
912 iterator.clear_host_errors(host)
913 msg = "cleared host errors"
914 else:
915 skipped = True
916 skip_reason += ', not clearing host error state for %s' % target_host.name
917 elif meta_action == 'end_batch':
918 if _evaluate_conditional(target_host):
919 for host in self._inventory.get_hosts(iterator._play.hosts):
920 if host.name not in self._tqm._unreachable_hosts:
921 iterator.end_host(host.name)
922 msg = "ending batch"
923 else:
924 skipped = True
925 skip_reason += ', continuing current batch'
926 elif meta_action == 'end_play':
927 if _evaluate_conditional(target_host):
928 for host in self._inventory.get_hosts(iterator._play.hosts):
929 if host.name not in self._tqm._unreachable_hosts:
930 iterator.end_host(host.name)
931 # end_play is used in PlaybookExecutor/TQM to indicate that
932 # the whole play is supposed to be ended as opposed to just a batch
933 iterator.end_play = True
934 msg = "ending play"
935 else:
936 skipped = True
937 skip_reason += ', continuing play'
938 elif meta_action == 'end_host':
939 if _evaluate_conditional(target_host):
940 iterator.end_host(target_host.name)
941 msg = "ending play for %s" % target_host.name
942 else:
943 skipped = True
944 skip_reason += ", continuing execution for %s" % target_host.name
945 # TODO: Nix msg here? Left for historical reasons, but skip_reason exists now.
946 msg = "end_host conditional evaluated to false, continuing execution for %s" % target_host.name
947 elif meta_action == 'role_complete':
948 if task.implicit:
949 role_obj = self._get_cached_role(task, iterator._play)
950 if target_host.name in role_obj._had_task_run:
951 role_obj._completed[target_host.name] = True
952 msg = 'role_complete for %s' % target_host.name
953 elif meta_action == 'end_role':
954 if _evaluate_conditional(target_host):
955 while True:
956 state, task = iterator.get_next_task_for_host(target_host, peek=True)
957 if task._get_meta() == "role_complete":
958 break
959 iterator.set_state_for_host(target_host.name, state)
960 display.debug("'%s' skipped because role has been ended via 'end_role'" % task)
961 msg = 'ending role %s for %s' % (task._role.get_name(), target_host.name)
962 else:
963 skipped = True
964 skip_reason += ', continuing role %s for %s' % (task._role.get_name(), target_host.name)
965 elif meta_action == 'reset_connection':
966 all_vars = self._variable_manager.get_vars(play=iterator._play, host=target_host, task=task,
967 _hosts=self._hosts_cache, _hosts_all=self._hosts_cache_all)
968 templar = TemplateEngine(loader=self._loader, variables=all_vars)
969
970 # apply the given task's information to the connection info,
971 # which may override some fields already set by the play or
972 # the options specified on the command line
973 play_context = play_context.set_task_and_variable_override(task=task, variables=all_vars, templar=templar)
974
975 # fields set from the play/task may be based on variables, so we have to
976 # do the same kind of post validation step on it here before we use it.
977 play_context.post_validate(templar=templar)
978
979 # now that the play context is finalized, if the remote_addr is not set
980 # default to using the host's address field as the remote address
981 if not play_context.remote_addr:
982 play_context.remote_addr = target_host.address
983
984 # We also add "magic" variables back into the variables dict to make sure
985 # a certain subset of variables exist. This 'mostly' works here cause meta
986 # disregards the loop, but should not really use play_context at all
987 play_context.update_vars(all_vars)
988
989 if target_host in self._active_connections:
990 connection = Connection(self._active_connections[target_host])
991 del self._active_connections[target_host]
992 else:
993 connection = plugin_loader.connection_loader.get(play_context.connection, play_context, os.devnull)
994 var_options = connection._resolve_option_variables(all_vars, templar)
995 connection.set_options(task_keys=task.dump_attrs(), var_options=var_options)
996 play_context.set_attributes_from_plugin(connection)
997
998 if connection:
999 try:
1000 connection.reset()
1001 msg = 'reset connection'
1002 except ConnectionError as e:
1003 # most likely socket is already closed
1004 display.debug("got an error while closing persistent connection: %s" % e)
1005 else:
1006 msg = 'no connection, nothing to reset'
1007 else:
1008 raise AnsibleError("invalid meta action requested: %s" % meta_action, obj=task._ds)
1009
1010 utr = _task.UnifiedTaskResult.from_action_result_dict({})
1011 utr.msg = msg
1012
1013 if skipped:
1014 utr.set_skipped(skip_reason)
1015
1016 header = skip_reason if skipped else msg
1017 if task.implicit:
1018 display.debug(f"META: {header}")
1019 else:
1020 display.vv(f"META: {header}")
1021
1022 htr = HostTaskResult(host=target_host, task=task, utr=utr)
1023
1024 if skipped:
1025 self._tqm.send_callback('v2_runner_on_skipped', htr)
1026
1027 return [htr]
1028
1029 def _get_cached_role(self, task, play):
1030 return play._get_cached_role(task._role)
1031
1032 def get_hosts_left(self, iterator):
1033 """ returns list of available hosts for this iterator by filtering out unreachables """
1034
1035 hosts_left = []
1036 for host in self._hosts_cache:
1037 if host not in self._tqm._unreachable_hosts:
1038 try:
1039 hosts_left.append(self._inventory.hosts[host])
1040 except KeyError:
1041 hosts_left.append(self._inventory.get_host(host))
1042 return hosts_left
1043
1044 def update_active_connections(self, results: _c.Iterable[HostTaskResult]) -> None:
1045 """ updates the current active persistent connections """
1046 for result in results:
1047 if socket_path := result.task.args.get('_ansible_socket'):
1048 if result.host not in self._active_connections:
1049 self._active_connections[result.host] = socket_path
1050
1051
1052 class NextAction(object):
1053 """ The next action after an interpreter's exit. """
1054 REDO = 1
1055 CONTINUE = 2
1056 EXIT = 3
1057
1058 def __init__(self, result=EXIT):
1059 self.result = result
1060
1061
1062 class Debugger(cmd.Cmd):
1063 prompt_continuous = '> ' # multiple lines
1064
1065 def __init__(self, task, host, task_vars, play_context, result, next_action):
1066 # cmd.Cmd is old-style class
1067 cmd.Cmd.__init__(self)
1068
1069 self.prompt = '[%s] %s (debug)> ' % (host, task)
1070 self.intro = None
1071 self.scope = {}
1072 self.scope['task'] = task
1073 self.scope['task_vars'] = task_vars
1074 self.scope['host'] = host
1075 self.scope['play_context'] = play_context
1076 self.scope['result'] = result
1077 self.next_action = next_action
1078
1079 def cmdloop(self):
1080 try:
1081 cmd.Cmd.cmdloop(self)
1082 except KeyboardInterrupt:
1083 pass
1084
1085 do_h = cmd.Cmd.do_help
1086
1087 def do_EOF(self, args):
1088 """Quit"""
1089 return self.do_quit(args)
1090
1091 def do_quit(self, args):
1092 """Quit"""
1093 display.display('User interrupted execution')
1094 self.next_action.result = NextAction.EXIT
1095 return True
1096
1097 do_q = do_quit
1098
1099 def do_continue(self, args):
1100 """Continue to next result"""
1101 self.next_action.result = NextAction.CONTINUE
1102 return True
1103
1104 do_c = do_continue
1105
1106 def do_redo(self, args):
1107 """Schedule task for re-execution. The re-execution may not be the next result"""
1108 self.next_action.result = NextAction.REDO
1109 return True
1110
1111 do_r = do_redo
1112
1113 def do_update_task(self, args):
1114 """Recreate the task from ``task._ds``, and template with updated ``task_vars``"""
1115 templar = TemplateEngine(variables=self.scope['task_vars'])
1116 task = self.scope['task']
1117 task = task.load_data(task._ds)
1118 task.post_validate(templar)
1119 self.scope['task'] = task
1120
1121 do_u = do_update_task
1122
1123 def evaluate(self, args):
1124 try:
1125 return eval(args, globals(), self.scope)
1126 except Exception:
1127 t, v = sys.exc_info()[:2]
1128 if isinstance(t, str):
1129 exc_type_name = t
1130 else:
1131 exc_type_name = t.__name__
1132 display.display('***%s:%s' % (exc_type_name, repr(v)))
1133 raise
1134
1135 def do_pprint(self, args):
1136 """Pretty Print"""
1137 try:
1138 result = self.evaluate(args)
1139 display.display(pprint.pformat(result))
1140 except Exception:
1141 pass
1142
1143 do_p = do_pprint
1144
1145 def execute(self, args):
1146 try:
1147 code = compile(args + '\n', '<stdin>', 'single')
1148 exec(code, globals(), self.scope)
1149 except Exception:
1150 t, v = sys.exc_info()[:2]
1151 if isinstance(t, str):
1152 exc_type_name = t
1153 else:
1154 exc_type_name = t.__name__
1155 display.display('***%s:%s' % (exc_type_name, repr(v)))
1156 raise
1157
1158 def default(self, line):
1159 try:
1160 self.execute(line)
1161 except Exception:
1162 pass