Debian Codegraph @

lib/ansible/executor/task_queue_manager.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 dataclasses
21 import errno
22 import os
23 import sys
24 import signal
25 import tempfile
26 import threading
27 import time
28 import typing as t
29 import multiprocessing.queues
30
31 from pathlib import Path
32
33 from ansible import constants as C
34 from ansible import context
35 from ansible.errors import AnsibleError, ExitCode, AnsibleCallbackError
36 from ansible._internal._errors._handler import ErrorHandler
37 from ansible._internal import _rpc_host
38 from ansible.executor.play_iterator import PlayIterator
39 from ansible.executor.stats import AggregateStats
40 from ansible.executor.task_result import CallbackTaskResult
41 from ansible.inventory.manager import InventoryManager
42 from ansible.module_utils._internal import _debug
43 from ansible.module_utils.common.text.converters import to_native
44 from ansible.module_utils.secrets import register_secrets
45 from ansible.parsing.dataloader import DataLoader
46 from ansible.playbook.play_context import PlayContext
47 from ansible.playbook.task import Task
48 from ansible.plugins.callback import CallbackBase
49 from ansible.plugins.loader import callback_loader, strategy_loader, module_loader
50 from ansible._internal._plugins import _strategy
51 from ansible._internal._templating._engine import TemplateEngine
52 from ansible._internal._task import UnifiedTaskResult, WireTaskResult, HostTaskResult, TaskContext
53 from ansible.vars.hostvars import HostVars
54 from ansible.vars.manager import VariableManager
55 from ansible.utils.display import Display
56 from ansible.utils.lock import lock_decorator
57 from ansible.utils.multiprocessing import context as multiprocessing_context
58
59 if t.TYPE_CHECKING:
60 from ansible.executor.process.worker import WorkerProcess
61 from ansible.inventory.host import Host
62
63 __all__ = ['TaskQueueManager']
64
65 STDIN_FILENO = 0
66 STDOUT_FILENO = 1
67 STDERR_FILENO = 2
68
69 display = Display()
70
71
72 @dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
73 class _Envelope:
74 secrets: frozenset[str] | None = None
75 message: CallbackSend | DisplaySend | PromptSend | WireTaskResult
76
77
78 @dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
79 class CallbackSend:
80 method_name: str
81 wire_task_result: WireTaskResult
82
83
84 class DisplaySend:
85 def __init__(self, method, *args, **kwargs):
86 self.method = method
87 self.args = args
88 self.kwargs = kwargs
89
90
91 @dataclasses.dataclass
92 class PromptSend:
93 worker_id: int
94 prompt: str
95 private: bool = True
96 seconds: int = None
97 interrupt_input: t.Iterable[bytes] = None
98 complete_input: t.Iterable[bytes] = None
99
100
101 class FinalQueue(multiprocessing.queues.SimpleQueue):
102 def __init__(self, *args, **kwargs):
103 kwargs['ctx'] = multiprocessing_context
104 super().__init__(*args, **kwargs)
105
106 def put(self, obj):
107 super().put(
108 _Envelope(
109 secrets=tc.flush_new_secrets() if (tc := TaskContext.current(optional=True)) else None,
110 message=obj
111 ),
112 )
113
114 def get(self):
115 envelope = super().get()
116 if envelope.secrets:
117 register_secrets(envelope.secrets)
118 return envelope.message
119
120 def send_callback(self, method_name: str, host: Host, task: Task, utr: UnifiedTaskResult) -> None:
121 self.put(CallbackSend(method_name=method_name, wire_task_result=WireTaskResult.create(host=host, task=task, utr=utr)))
122
123 def send_task_result(self, host: Host, task: Task, utr: UnifiedTaskResult) -> None:
124 self.put(WireTaskResult.create(host=host, task=task, utr=utr))
125
126 def send_display(self, method, *args, **kwargs):
127 self.put(
128 DisplaySend(method, *args, **kwargs),
129 )
130
131 def send_prompt(self, **kwargs):
132 self.put(
133 PromptSend(**kwargs),
134 )
135
136
137 class AnsibleEndPlay(Exception):
138 def __init__(self, result):
139 self.result = result
140
141
142 def _resolve_callback_option_variables(callback: CallbackBase, variables: dict[str, object], templar: TemplateEngine) -> None:
143 """Set callback plugin options using documented variables."""
144 callback_variables = {
145 var_name: variables[var_name]
146 for var_name in C.config.get_plugin_vars(callback.plugin_type, callback._load_name)
147 if var_name in variables
148 }
149 callback.set_options(var_options=templar.template(callback_variables))
150
151
152 class TaskQueueManager:
153
154 """
155 This class handles the multiprocessing requirements of Ansible by
156 creating a pool of worker forks, a result handler fork, and a
157 manager object with shared datastructures/queues for coordinating
158 work between all processes.
159
160 The queue manager is responsible for loading the play strategy plugin,
161 which dispatches the Play's tasks to hosts.
162 """
163
164 RUN_OK = ExitCode.SUCCESS
165 RUN_ERROR = ExitCode.GENERIC_ERROR
166 RUN_FAILED_HOSTS = ExitCode.HOST_FAILED
167 RUN_UNREACHABLE_HOSTS = ExitCode.HOST_UNREACHABLE
168 RUN_FAILED_BREAK_PLAY = 8 # never leaves PlaybookExecutor.run
169 RUN_UNKNOWN_ERROR = 255 # never leaves PlaybookExecutor.run, intentionally includes the bit value for 8
170
171 _callback_dispatch_error_handler = ErrorHandler.from_config('_CALLBACK_DISPATCH_ERROR_BEHAVIOR')
172
173 def __init__(
174 self,
175 inventory: InventoryManager,
176 variable_manager: VariableManager,
177 loader: DataLoader,
178 passwords: dict[str, str | None],
179 stdout_callback_name: str | None = None,
180 run_additional_callbacks: bool = True,
181 run_tree: bool = False,
182 forks: int | None = None,
183 ) -> None:
184 self._inventory = inventory
185 self._variable_manager = variable_manager
186 self._loader = loader
187 self._stats = AggregateStats()
188 self.passwords = passwords
189 self._stdout_callback_name: str | None = stdout_callback_name or C.DEFAULT_STDOUT_CALLBACK
190 self._run_additional_callbacks = run_additional_callbacks
191 self._run_tree = run_tree
192 self._forks = forks or 5
193
194 self._callback_plugins: list[CallbackBase] = []
195 self._start_at_done = False
196
197 _rpc_host.LocalManager.shared_instance() # ensure the RPC host is available
198
199 # make sure any module paths (if specified) are added to the module_loader
200 if context.CLIARGS.get('module_path', False):
201 for path in context.CLIARGS['module_path']:
202 if path:
203 module_loader.add_directory(path)
204
205 # a special flag to help us exit cleanly
206 self._terminated = False
207
208 # dictionaries to keep track of failed/unreachable hosts
209 self._failed_hosts: dict[str, t.Literal[True]] = dict()
210 self._unreachable_hosts: dict[str, t.Literal[True]] = dict()
211
212 try:
213 self._final_q = FinalQueue()
214 except OSError as e:
215 raise AnsibleError("Unable to use multiprocessing, this is normally caused by lack of access to /dev/shm: %s" % to_native(e))
216
217 try:
218 # Done in tqm, and not display, because this is only needed for commands that execute tasks
219 for fd in (STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO):
220 os.set_inheritable(fd, False)
221 except Exception as ex:
222 display.error_as_warning("failed to set stdio as non inheritable", exception=ex)
223
224 self._callback_lock = threading.Lock()
225
226 # A temporary file (opened pre-fork) used by connection
227 # plugins for inter-process locking.
228 self._connection_lockfile = tempfile.TemporaryFile()
229
230 self._workers: list[WorkerProcess | None] = []
231
232 # signal handlers to propagate signals to workers
233 signal.signal(signal.SIGTERM, self._signal_handler)
234 signal.signal(signal.SIGINT, self._signal_handler)
235
236 # Location of our stacktrace dump directory. Pre-create so Workers don't have to.
237 trace_dir = Path(C.ANSIBLE_HOME).expanduser() / 'debug'
238 try:
239 trace_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
240 except Exception as e:
241 display.warning(f"Unable to create debug directory {trace_dir}: {e}")
242 self.stacktrace_dir = None
243 else:
244 display.debug(f"Using stacktrace dump directory {trace_dir}")
245 self.stacktrace_dir = str(trace_dir)
246 _debug.register_for_stacktrace(self.stacktrace_dir)
247
248 def _initialize_processes(self, num: int) -> None:
249 # mutable update to ensure the reference stays the same
250 self._workers[:] = [None] * num
251
252 def _signal_handler(self, signum, frame) -> None:
253 """
254 terminate all running process groups created as a result of calling
255 setsid from within a WorkerProcess.
256
257 Since the children become process leaders, signals will not
258 automatically propagate to them.
259 """
260 signal.signal(signum, signal.SIG_DFL)
261
262 for worker in self._workers:
263 if worker is None or not worker.is_alive():
264 continue
265 if worker.pid:
266 try:
267 # notify workers
268 os.kill(worker.pid, signum)
269 except OSError as e:
270 if e.errno != errno.ESRCH:
271 signame = signal.strsignal(signum)
272 display.error(f'Unable to send {signame} to child[{worker.pid}]: {e}')
273
274 if signum == signal.SIGINT:
275 # Defer to CLI handling
276 raise KeyboardInterrupt()
277
278 pid = os.getpid()
279 try:
280 os.kill(pid, signum)
281 except OSError as e:
282 signame = signal.strsignal(signum)
283 display.error(f'Unable to send {signame} to {pid}: {e}')
284
285 def load_callbacks(self):
286 """
287 Loads all available callbacks, with the exception of those which
288 utilize the CALLBACK_TYPE option. When CALLBACK_TYPE is set to 'stdout',
289 only one such callback plugin will be loaded.
290 """
291
292 if self._callback_plugins:
293 return
294
295 if not self._stdout_callback_name:
296 raise AnsibleError("No stdout callback name provided.")
297
298 stdout_callback = callback_loader.get(self._stdout_callback_name)
299
300 if not stdout_callback:
301 raise AnsibleError(f"Could not load {self._stdout_callback_name!r} callback plugin.")
302
303 templar = TemplateEngine(loader=self._loader, variables=self._variable_manager._extra_vars)
304
305 stdout_callback._init_callback_methods()
306 _resolve_callback_option_variables(stdout_callback, self._variable_manager._extra_vars, templar)
307
308 self._callback_plugins.append(stdout_callback)
309
310 # get all configured loadable callbacks (adjacent, builtin)
311 plugin_types = {plugin_type.ansible_name: plugin_type for plugin_type in callback_loader.all(class_only=True)}
312
313 # add enabled callbacks that refer to collections, which might not appear in normal listing
314 for c in C.CALLBACKS_ENABLED:
315 # load all, as collection ones might be using short/redirected names and not a fqcn
316 plugin = callback_loader.get(c, class_only=True)
317
318 if plugin:
319 # avoids incorrect and dupes possible due to collections
320 plugin_types.setdefault(plugin.ansible_name, plugin)
321 else:
322 display.warning("Skipping callback plugin '%s', unable to load" % c)
323
324 plugin_types.pop(stdout_callback.ansible_name, None)
325
326 # for each callback in the list see if we should add it to 'active callbacks' used in the play
327 for callback_plugin in plugin_types.values():
328 callback_type = getattr(callback_plugin, 'CALLBACK_TYPE', '')
329 callback_needs_enabled = getattr(callback_plugin, 'CALLBACK_NEEDS_ENABLED', getattr(callback_plugin, 'CALLBACK_NEEDS_WHITELIST', False))
330
331 # try to get collection world name first
332 cnames = getattr(callback_plugin, '_redirected_names', [])
333 if cnames:
334 # store the name the plugin was loaded as, as that's what we'll need to compare to the configured callback list later
335 callback_name = cnames[0]
336 else:
337 # fallback to 'old loader name'
338 (callback_name, ext) = os.path.splitext(os.path.basename(callback_plugin._original_path))
339
340 display.vvvvv("Attempting to use '%s' callback." % (callback_name))
341 if callback_type == 'stdout':
342 # we only allow one callback of type 'stdout' to be loaded,
343 display.vv("Skipping callback '%s', as we already have a stdout callback." % (callback_name))
344 continue
345 elif callback_name == 'tree' and self._run_tree:
346 # TODO: remove special case for tree, which is an adhoc cli option --tree
347 pass
348 elif not self._run_additional_callbacks or (callback_needs_enabled and (
349 # only run if not adhoc, or adhoc was specifically configured to run + check enabled list
350 C.CALLBACKS_ENABLED is None or callback_name not in C.CALLBACKS_ENABLED)):
351 # 2.x plugins shipped with ansible should require enabling, older or non shipped should load automatically
352 continue
353
354 try:
355 callback_obj = callback_plugin()
356 # avoid bad plugin not returning an object, only needed cause we do class_only load and bypass loader checks,
357 # really a bug in the plugin itself which we ignore as callback errors are not supposed to be fatal.
358 if callback_obj:
359 callback_obj._init_callback_methods()
360 _resolve_callback_option_variables(callback_obj, self._variable_manager._extra_vars, templar)
361 self._callback_plugins.append(callback_obj)
362 else:
363 display.warning("Skipping callback '%s', as it does not create a valid plugin instance." % callback_name)
364 continue
365 except Exception as ex:
366 display.error_as_warning(f"Failed to load callback plugin {callback_name!r}.", exception=ex)
367 continue
368
369 def run(self, play):
370 """
371 Iterates over the roles/tasks in a play, using the given (or default)
372 strategy for queueing tasks. The default is the linear strategy, which
373 operates like classic Ansible by keeping all hosts in lock-step with
374 a given task (meaning no hosts move on to the next task until all hosts
375 are done with the current task).
376 """
377
378 self.load_callbacks()
379
380 all_vars = self._variable_manager.get_vars(play=play)
381 templar = TemplateEngine(loader=self._loader, variables=all_vars)
382
383 new_play = play.copy()
384 new_play.post_validate(templar)
385 new_play.handlers = new_play.compile_roles_handlers() + new_play.handlers
386
387 self.hostvars = HostVars(
388 inventory=self._inventory,
389 variable_manager=self._variable_manager,
390 loader=self._loader,
391 )
392
393 play_context = PlayContext(new_play, self.passwords, self._connection_lockfile.fileno())
394
395 for callback_plugin in self._callback_plugins:
396 callback_plugin.set_play_context(play_context)
397
398 self.send_callback('v2_playbook_on_play_start', new_play)
399
400 # build the iterator
401 iterator = PlayIterator(
402 inventory=self._inventory,
403 play=new_play,
404 play_context=play_context,
405 variable_manager=self._variable_manager,
406 all_vars=all_vars,
407 start_at_done=self._start_at_done,
408 )
409
410 # adjust to # of workers to configured forks or size of batch, whatever is lower
411 self._initialize_processes(min(self._forks, iterator.batch_size))
412
413 # load the specified strategy (or the default linear one)
414 strategy = strategy_loader.get(new_play.strategy, self)
415 if strategy is None:
416 raise AnsibleError("Invalid play strategy specified: %s" % new_play.strategy, obj=play._ds)
417
418 # Because the TQM may survive multiple play runs, we start by marking
419 # any hosts as failed in the iterator here which may have been marked
420 # as failed in previous runs. Then we clear the internal list of failed
421 # hosts so we know what failed this round.
422 for host_name in self._failed_hosts.keys():
423 host = self._inventory.get_host(host_name)
424 iterator.mark_host_failed(host)
425 for host_name in self._unreachable_hosts.keys():
426 iterator._play._removed_hosts.append(host_name)
427
428 self.clear_failed_hosts()
429
430 # during initialization, the PlayContext will clear the start_at_task
431 # field to signal that a matching task was found, so check that here
432 # and remember it so we don't try to skip tasks on future plays
433 if context.CLIARGS.get('start_at_task') is not None and play_context.start_at_task is None:
434 self._start_at_done = True
435
436 # and run the play using the strategy and cleanup on way out
437 try:
438 with _strategy.StrategyContext(strategy=strategy, tqm=self).activate():
439 play_return = strategy.run(iterator, play_context)
440 finally:
441 strategy.cleanup()
442 self._cleanup_processes()
443
444 # now re-save the hosts that failed from the iterator to our internal list
445 for host_name in iterator.get_failed_hosts():
446 self._failed_hosts[host_name] = True
447
448 if iterator.end_play:
449 raise AnsibleEndPlay(play_return)
450
451 return play_return
452
453 def cleanup(self):
454 display.debug("RUNNING CLEANUP")
455 self.terminate()
456 self._final_q.close()
457 self._cleanup_processes()
458 # We no longer flush on every write in ``Display.display``
459 # just ensure we've flushed during cleanup
460 sys.stdout.flush()
461 sys.stderr.flush()
462
463 def _cleanup_processes(self):
464 if hasattr(self, '_workers'):
465 for attempts_remaining in range(C.WORKER_SHUTDOWN_POLL_COUNT - 1, -1, -1):
466 if not any(worker_prc and worker_prc.is_alive() for worker_prc in self._workers):
467 break
468
469 if attempts_remaining:
470 time.sleep(C.WORKER_SHUTDOWN_POLL_DELAY)
471 else:
472 display.warning('One or more worker processes are still running and will be terminated.')
473
474 for worker_prc in self._workers:
475 if worker_prc and worker_prc.is_alive():
476 try:
477 worker_prc.terminate()
478 except AttributeError:
479 pass
480
481 def clear_failed_hosts(self) -> None:
482 self._failed_hosts = dict()
483
484 def get_inventory(self) -> InventoryManager:
485 return self._inventory
486
487 def get_variable_manager(self) -> VariableManager:
488 return self._variable_manager
489
490 def get_loader(self) -> DataLoader:
491 return self._loader
492
493 def get_workers(self):
494 return self._workers[:]
495
496 def terminate(self) -> None:
497 self._terminated = True
498
499 def has_dead_workers(self) -> bool:
500
501 # [<WorkerProcess(WorkerProcess-2, stopped[SIGKILL])>,
502 # <WorkerProcess(WorkerProcess-2, stopped[SIGTERM])>
503
504 defunct = False
505 for x in self._workers:
506 if getattr(x, 'exitcode', None):
507 defunct = True
508 return defunct
509
510 @staticmethod
511 def _first_arg_of_type[T](value_type: t.Type[T], args: t.Sequence) -> T | None:
512 return next((arg for arg in args if isinstance(arg, value_type)), None)
513
514 @lock_decorator(attr='_callback_lock')
515 def send_callback(self, method_name, *args, **kwargs):
516 # We always send events to stdout callback first, rest should follow config order
517 for callback_plugin in self._callback_plugins:
518 # a plugin that set self.disabled to True will not be called
519 # see osx_say.py example for such a plugin
520 if callback_plugin.disabled:
521 continue
522
523 # a plugin can opt in to implicit tasks (such as meta). It does this
524 # by declaring self.wants_implicit_tasks = True.
525 if not callback_plugin.wants_implicit_tasks and (task_arg := self._first_arg_of_type(Task, args)) and task_arg.implicit:
526 continue
527
528 methods = []
529
530 if method_name in callback_plugin._implemented_callback_methods:
531 methods.append(getattr(callback_plugin, method_name))
532
533 if 'v2_on_any' in callback_plugin._implemented_callback_methods:
534 methods.append(getattr(callback_plugin, 'v2_on_any'))
535
536 for method in methods:
537 # send clean copies
538 new_args = []
539
540 for arg in args:
541 # FIXME: add play/task cleaners
542 if isinstance(arg, HostTaskResult):
543 mask_result = not callback_plugin.ANSIBLE_SUPPORTS_MASKING
544 copied_tr = CallbackTaskResult(host=arg.host, task=arg.task, utr=arg.utr, mask_result=mask_result)
545 new_args.append(copied_tr)
546 # this state hack requires that no callback ever accepts > 1 TaskResult object
547 callback_plugin._current_task_result = copied_tr
548 else:
549 new_args.append(arg)
550
551 with self._callback_dispatch_error_handler.handle(AnsibleCallbackError):
552 try:
553 method(*new_args, **kwargs)
554 except AssertionError:
555 # Using an `assert` in integration tests is useful.
556 # Production code should never use `assert` or raise `AssertionError`.
557 raise
558 except Exception as ex:
559 raise AnsibleCallbackError(f"Callback dispatch {method_name!r} failed for plugin {callback_plugin._load_name!r}.") from ex
560
561 callback_plugin._current_task_result = None # clear temporary instance storage hack