Debian Codegraph @

lib/ansible/plugins/callback/__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 difflib
21 import functools
22 import inspect
23 import json
24 import re
25 import sys
26 import textwrap
27 import typing as t
28 import collections.abc as _c
29
30 from typing import TYPE_CHECKING
31
32 from copy import deepcopy
33
34 from ansible import constants as C
35 from ansible.module_utils._internal import _datatag
36 from ansible._internal._yaml import _dumper
37 from ansible.plugins import AnsiblePlugin
38 from ansible.utils.color import stringc
39 from ansible.utils.display import Display
40 from ansible.vars.clean import strip_internal_keys, module_response_deepcopy
41 from ansible.module_utils._internal._json._profiles import _fallback_to_str
42 from ansible._internal._templating import _engine
43 from ansible.module_utils._internal import _deprecator
44
45 import yaml
46
47 if TYPE_CHECKING:
48 from ansible.executor.task_result import CallbackTaskResult
49
50 global_display = Display()
51
52
53 __all__ = ["CallbackBase"]
54
55
56 _DEBUG_ALLOWED_KEYS = frozenset(('msg', 'exception', 'warnings', 'deprecations'))
57 # Characters that libyaml/pyyaml consider breaks
58 _YAML_BREAK_CHARS = '\n\x85\u2028\u2029' # NL, NEL, LS, PS
59 # regex representation of libyaml/pyyaml of a space followed by a break character
60 _SPACE_BREAK_RE = re.compile(fr' +([{_YAML_BREAK_CHARS}])')
61
62
63 class _AnsibleCallbackDumper(_dumper.AnsibleDumper):
64 def __init__(self, *args, lossy: bool = False, **kwargs):
65 super().__init__(*args, **kwargs)
66
67 self._lossy = lossy
68
69 def _pretty_represent_str(self, data):
70 """Uses block style for multi-line strings"""
71 data = _datatag.AnsibleTagHelper.as_native_type(data)
72
73 if _should_use_block(data):
74 style = '|'
75 if self._lossy:
76 data = _munge_data_for_lossy_yaml(data)
77 else:
78 style = self.default_style
79
80 node = yaml.representer.ScalarNode('tag:yaml.org,2002:str', data, style=style)
81
82 if self.alias_key is not None:
83 self.represented_objects[self.alias_key] = node
84
85 return node
86
87 @classmethod
88 def _register_representers(cls) -> None:
89 super()._register_representers()
90
91 # exact type checks occur first against representers, then subclasses against multi-representers
92 cls.add_representer(str, cls._pretty_represent_str)
93 cls.add_multi_representer(str, cls._pretty_represent_str)
94
95
96 def _should_use_block(scalar):
97 """Returns true if string should be in block format based on the existence of various newline separators"""
98 # This method of searching is faster than using a regex
99 for ch in _YAML_BREAK_CHARS:
100 if ch in scalar:
101 return True
102
103 return False
104
105
106 class _SpecialCharacterTranslator:
107 def __getitem__(self, ch):
108 # "special character" logic from pyyaml yaml.emitter.Emitter.analyze_scalar, translated to decimal
109 # for perf w/ str.translate
110 if (ch == 10 or
111 32 <= ch <= 126 or
112 ch == 133 or
113 160 <= ch <= 55295 or
114 57344 <= ch <= 65533 or
115 65536 <= ch < 1114111)\
116 and ch != 65279:
117 return ch
118 return None
119
120
121 def _filter_yaml_special(scalar: str) -> str:
122 """Filter a string removing any character that libyaml/pyyaml declare as special"""
123 return scalar.translate(_SpecialCharacterTranslator())
124
125
126 def _munge_data_for_lossy_yaml(scalar: str) -> str:
127 """Modify a string so that analyze_scalar in libyaml/pyyaml will allow block formatting"""
128 # we care more about readability than accuracy, so...
129 # ...libyaml/pyyaml does not permit trailing spaces for block scalars
130 scalar = scalar.rstrip()
131 # ...libyaml/pyyaml does not permit tabs for block scalars
132 scalar = scalar.expandtabs()
133 # ...libyaml/pyyaml only permits special characters for double quoted scalars
134 scalar = _filter_yaml_special(scalar)
135 # ...libyaml/pyyaml only permits spaces followed by breaks for double quoted scalars
136 return _SPACE_BREAK_RE.sub(r'\1', scalar)
137
138
139 class CallbackBase(AnsiblePlugin):
140 """
141 This is a base ansible callback class that does nothing. New callbacks should
142 use this class as a base and override any callback methods they wish to execute
143 custom actions.
144 """
145
146 # deprecated: description='Remove this attribute as it will be no-op' core_version='2.27'
147 ANSIBLE_SUPPORTS_MASKING = False
148
149 _implemented_callback_methods: frozenset[str] = frozenset()
150 """Set of callback methods overridden by each subclass; used by TQM to bypass callback dispatch on no-op methods."""
151
152 def __init_subclass__(cls, **kwargs) -> None:
153 super().__init_subclass__(**kwargs)
154
155 # deprecated: description='Remove this once the attr becomes a no-op' core_version='2.27'
156 # While we set a default of False in CallbackBase it is common for custom
157 # callback plugins to inherit default.py which we set to True. This ensures
158 # that if a subclass does not set the attribute it will always be False and
159 # not inherit the value from a parent class.
160 if 'ANSIBLE_SUPPORTS_MASKING' not in cls.__dict__:
161 cls.ANSIBLE_SUPPORTS_MASKING = False
162
163 def __init__(self, display: Display | None = None, options: dict[str, t.Any] | None = None) -> None:
164 super().__init__()
165
166 # deprecated: description='Enable deprecation and decide when to deprecate new attribute altogether' core_version='2.24'
167 # if not self.ANSIBLE_SUPPORTS_MASKING:
168 # callback_name = getattr(self, 'CALLBACK_NAME', type(self).__name__)
169 # global_display.deprecated(
170 # msg=f"The callback {callback_name!r} relies on the implicit task result masking which is deprecated.",
171 # help_text=(
172 # "Update callback to use the new secret masking API or change to a different callback that does. "
173 # "If not updated, secrets will no longer be redacted in future versions of Ansible."
174 # ),
175 # version="2.27",
176 # )
177
178 if display:
179 self._display = display
180 else:
181 self._display = global_display
182
183 # FUTURE: fix double-loading of non-collection stdout callback plugins that don't set CALLBACK_NEEDS_ENABLED
184
185 # FUTURE: this code is jacked for 2.x- it should just use the type names and always assume 2.0+ for normal cases
186 if self._display.verbosity >= 4:
187 name = getattr(self, 'CALLBACK_NAME', 'unnamed')
188 ctype = getattr(self, 'CALLBACK_TYPE', 'old')
189 version = getattr(self, 'CALLBACK_VERSION', '1.0')
190 self._display.vvvv('Loading callback plugin %s of type %s, v%s from %s' % (name, ctype, version, sys.modules[self.__module__].__file__))
191
192 self.disabled = False
193 self.wants_implicit_tasks = False
194
195 self._plugin_options: dict[str, t.Any] = {}
196
197 if options is not None:
198 self.set_options(options)
199
200 self._hide_in_debug = (
201 'changed', 'failed', 'skipped', 'invocation', 'skip_reason',
202 'ansible_loop_var', 'ansible_index_var', 'ansible_loop',
203 )
204
205 self._current_task_result: CallbackTaskResult | None = None
206
207 # helper for callbacks, so they don't all have to include deepcopy
208 _copy_result = deepcopy
209
210 def _init_callback_methods(self) -> None:
211 """Record analysis of callback methods on each callback instance for dispatch optimization and deprecation warnings."""
212 implemented_callback_methods: set[str] = set()
213 deprecated_v1_method_overrides: set[str] = set()
214 plugin_file = sys.modules[type(self).__module__].__file__
215
216 if plugin_info := _deprecator._path_as_plugininfo(plugin_file):
217 plugin_name = plugin_info.resolved_name
218 else:
219 plugin_name = plugin_file
220
221 for base_v2_method, base_v1_method in CallbackBase._v2_v1_method_map.items():
222 method_name = None
223
224 if not inspect.ismethod(method := getattr(self, (v2_method_name := base_v2_method.__name__))) or method.__func__ is not base_v2_method:
225 implemented_callback_methods.add(v2_method_name) # v2 method directly implemented by subclass
226 method_name = v2_method_name
227 elif base_v1_method is None:
228 pass # no corresponding v1 method
229 elif not inspect.ismethod(method := getattr(self, (v1_method_name := base_v1_method.__name__))) or method.__func__ is not base_v1_method:
230 implemented_callback_methods.add(v2_method_name) # v1 method directly implemented by subclass
231 deprecated_v1_method_overrides.add(v1_method_name)
232 method_name = v1_method_name
233
234 if method_name and v2_method_name == 'v2_on_any':
235 deprecated_v1_method_overrides.discard(method_name) # avoid including v1 on_any in the v1 deprecation below
236
237 global_display.deprecated(
238 msg=f'The {plugin_name!r} callback plugin implements deprecated method {method_name!r}.',
239 version='2.23',
240 help_text='Use event-specific callback methods instead.',
241 )
242
243 self._implemented_callback_methods = frozenset(implemented_callback_methods)
244
245 if deprecated_v1_method_overrides:
246 global_display.deprecated(
247 msg=f'The {plugin_name!r} callback plugin implements the following deprecated method(s): {", ".join(sorted(deprecated_v1_method_overrides))}',
248 version='2.23',
249 help_text='Implement the `v2_*` equivalent callback method(s) instead.',
250 )
251
252 def set_option(self, k, v):
253 self._plugin_options[k] = C.config.get_config_value(k, plugin_type=self.plugin_type, plugin_name=self._load_name, direct={k: v})
254 self._origins[k] = 'direct'
255
256 def get_option(self, k, hostvars=None):
257 return self._plugin_options[k]
258
259 def get_option_and_origin(self, k, hostvars=None):
260 return self._plugin_options[k], self._origins[k]
261
262 def has_option(self, option):
263 return (option in self._plugin_options)
264
265 def set_options(self, task_keys=None, var_options=None, direct=None):
266 """ This is different than the normal plugin method as callbacks get called early and really don't accept keywords.
267 Also _options was already taken for CLI args and callbacks use _plugin_options instead.
268 """
269
270 # load from config
271 self._plugin_options, self._origins = C.config.get_plugin_options_and_origins(self.plugin_type, self._load_name,
272 keys=task_keys, variables=var_options, direct=direct)
273
274 @staticmethod
275 def host_label(result: CallbackTaskResult) -> str:
276 """Return label for the hostname (& delegated hostname) of a task result."""
277 label = result.host.get_name()
278 if result.task.delegate_to and result.task.delegate_to != result.host.get_name():
279 # show delegated host
280 label += " -> %s" % result.task.delegate_to
281 # in case we have 'extra resolution'
282 ahost = result.result.get('_ansible_delegated_vars', {}).get('ansible_host', result.task.delegate_to)
283 if result.task.delegate_to != ahost:
284 label += "(%s)" % ahost
285 return label
286
287 def _run_is_verbose(self, result: CallbackTaskResult, verbosity: int = 0) -> bool:
288 return ((self._display.verbosity > verbosity or result.result.get('_ansible_verbose_always', False) is True)
289 and result.result.get('_ansible_verbose_override', False) is False)
290
291 def _get_yaml_width(self) -> t.Optional[int]:
292 try:
293 yaml_line_width = self.get_option('result_yaml_line_width')
294 except KeyError:
295 # Callback does not declare result_yaml_line_width nor extend result_format_callback
296 return None
297
298 match yaml_line_width:
299 case 'default':
300 return None
301 case 'no-break':
302 # Some very large value that effectively disables line breaks
303 return 0x7FFFFFFF
304 case 'terminal-width':
305 return self._display.columns
306 case _:
307 self._display.warn(f"Invalid value {yaml_line_width!r} for result_yaml_line_width")
308 return None
309
310 def _dump_results(
311 self,
312 result: _c.Mapping[str, t.Any],
313 indent: int | None = None,
314 sort_keys: bool = True,
315 keep_invocation: bool = False,
316 serialize: bool = True,
317 ) -> str:
318 try:
319 result_format = self.get_option('result_format')
320 except KeyError:
321 # Callback does not declare result_format nor extend result_format_callback
322 result_format = 'json'
323
324 try:
325 pretty_results = self.get_option('pretty_results')
326 except KeyError:
327 # Callback does not declare pretty_results nor extend result_format_callback
328 pretty_results = None
329
330 indent_conditions = (
331 result.get('_ansible_verbose_always'),
332 pretty_results is None and result_format != 'json',
333 pretty_results is True,
334 self._display.verbosity > 2,
335 )
336
337 if not indent and any(indent_conditions):
338 try:
339 indent = self.get_option('result_indentation')
340 except KeyError:
341 # Callback does not declare result_indentation nor extend result_format_callback
342 indent = 4
343 if pretty_results is False:
344 # pretty_results=False overrides any specified indentation
345 indent = None
346
347 # All result keys stating with _ansible_ are internal, so remove them from the result before we output anything.
348 abridged_result = strip_internal_keys(module_response_deepcopy(result))
349
350 # remove invocation unless specifically wanting it
351 if not keep_invocation and self._display.verbosity < 3 and 'invocation' in result:
352 del abridged_result['invocation']
353
354 # remove diff information from screen output
355 if self._display.verbosity < 3 and 'diff' in result:
356 del abridged_result['diff']
357
358 # remove error/warning values; the stdout callback should have already handled them
359 abridged_result.pop('exception', None)
360 abridged_result.pop('warnings', None)
361 abridged_result.pop('deprecations', None)
362
363 abridged_result = _engine.TemplateEngine().transform(abridged_result) # ensure the dumped view matches the transformed view a playbook sees
364
365 if not serialize:
366 # Just return ``abridged_result`` without going through serialization
367 # to permit callbacks to take advantage of ``_dump_results``
368 # that want to further modify the result, or use custom serialization
369 return abridged_result
370
371 if result_format == 'json':
372 return json.dumps(abridged_result, cls=_fallback_to_str.Encoder, indent=indent, ensure_ascii=False, sort_keys=sort_keys)
373
374 if result_format == 'yaml':
375 # None is a sentinel in this case that indicates default behavior
376 # default behavior for yaml is to prettify results
377 lossy = pretty_results in (None, True)
378 if lossy:
379 # if we already have stdout, we don't need stdout_lines
380 if 'stdout' in abridged_result and 'stdout_lines' in abridged_result:
381 abridged_result['stdout_lines'] = '<omitted>'
382
383 # if we already have stderr, we don't need stderr_lines
384 if 'stderr' in abridged_result and 'stderr_lines' in abridged_result:
385 abridged_result['stderr_lines'] = '<omitted>'
386
387 return '\n%s' % textwrap.indent(
388 yaml.dump(
389 abridged_result,
390 allow_unicode=True,
391 Dumper=functools.partial(_AnsibleCallbackDumper, lossy=lossy),
392 default_flow_style=False,
393 indent=indent,
394 width=self._get_yaml_width(),
395 # sort_keys=sort_keys # This requires PyYAML>=5.1
396 ),
397 ' ' * (indent or 4)
398 )
399
400 # DTFIX5: add test to exercise this case
401 raise ValueError(f'Unsupported result_format {result_format!r}.')
402
403 def _handle_warnings(self, res: _c.MutableMapping[str, t.Any]) -> None:
404 """Display warnings and deprecation warnings sourced by task execution."""
405 if res.pop('warnings', None) and self._current_task_result and (warnings := self._current_task_result.warnings):
406 # display warnings from the current task result if `warnings` was not removed from `result` (or made falsey)
407 for warning in warnings:
408 self._display._warning(warning)
409
410 if res.pop('deprecations', None) and self._current_task_result and (deprecations := self._current_task_result.deprecations):
411 # display deprecations from the current task result if `deprecations` was not removed from `result` (or made falsey)
412 for deprecation in deprecations:
413 self._display._deprecated(deprecation)
414
415 def _handle_exception(self, result: _c.MutableMapping[str, t.Any], use_stderr: bool = False) -> None:
416 if result.pop('exception', None) and self._current_task_result and (exception := self._current_task_result.exception):
417 # display exception from the current task result if `exception` was not removed from `result` (or made falsey)
418 self._display._error(exception, stderr=use_stderr)
419
420 def _handle_warnings_and_exception(self, result: CallbackTaskResult) -> None:
421 """Standardized handling of warnings/deprecations and exceptions from a task/item result."""
422 # DTFIX5: make/doc/porting-guide a public version of this method?
423 try:
424 use_stderr = self.get_option('display_failed_stderr')
425 except KeyError:
426 use_stderr = False
427
428 self._handle_warnings(result.result)
429 self._handle_exception(result.result, use_stderr=use_stderr)
430
431 def _serialize_diff(self, diff):
432 try:
433 result_format = self.get_option('result_format')
434 except KeyError:
435 # Callback does not declare result_format nor extend result_format_callback
436 result_format = 'json'
437
438 try:
439 pretty_results = self.get_option('pretty_results')
440 except KeyError:
441 # Callback does not declare pretty_results nor extend result_format_callback
442 pretty_results = None
443
444 try:
445 indent = self.get_option('result_indentation')
446 except KeyError:
447 # Callback does not declare result_indentation nor extend result_format_callback
448 indent = 4
449
450 if result_format == 'json':
451 return json.dumps(diff, sort_keys=True, indent=indent, separators=(u',', u': ')) + u'\n'
452
453 if result_format == 'yaml':
454 # None is a sentinel in this case that indicates default behavior
455 # default behavior for yaml is to prettify results
456 lossy = pretty_results in (None, True)
457 return '%s\n' % textwrap.indent(
458 yaml.dump(
459 diff,
460 allow_unicode=True,
461 Dumper=functools.partial(_AnsibleCallbackDumper, lossy=lossy),
462 default_flow_style=False,
463 indent=indent,
464 width=self._get_yaml_width(),
465 # sort_keys=sort_keys # This requires PyYAML>=5.1
466 ),
467 ' '
468 )
469
470 # DTFIX5: add test to exercise this case
471 raise ValueError(f'Unsupported result_format {result_format!r}.')
472
473 def _get_diff(self, difflist):
474
475 if not isinstance(difflist, list):
476 difflist = [difflist]
477
478 ret = []
479 for diff in difflist:
480 if 'dst_binary' in diff:
481 ret.append(u"diff skipped: destination file appears to be binary\n")
482 if 'src_binary' in diff:
483 ret.append(u"diff skipped: source file appears to be binary\n")
484 if 'dst_larger' in diff:
485 ret.append(u"diff skipped: destination file size is greater than %d\n" % diff['dst_larger'])
486 if 'src_larger' in diff:
487 ret.append(u"diff skipped: source file size is greater than %d\n" % diff['src_larger'])
488 if 'before' in diff and 'after' in diff:
489 # format complex structures into 'files'
490 for x in ['before', 'after']:
491 if isinstance(diff[x], _c.Mapping):
492 diff[x] = self._serialize_diff(diff[x])
493 elif diff[x] is None:
494 diff[x] = ''
495 if 'before_header' in diff:
496 before_header = u"before: %s" % diff['before_header']
497 else:
498 before_header = u'before'
499 if 'after_header' in diff:
500 after_header = u"after: %s" % diff['after_header']
501 else:
502 after_header = u'after'
503 before_lines = diff['before'].splitlines(True)
504 after_lines = diff['after'].splitlines(True)
505 if before_lines and not before_lines[-1].endswith(u'\n'):
506 before_lines[-1] += u'\n\\ No newline at end of file\n'
507 if after_lines and not after_lines[-1].endswith('\n'):
508 after_lines[-1] += u'\n\\ No newline at end of file\n'
509 differ = difflib.unified_diff(before_lines,
510 after_lines,
511 fromfile=before_header,
512 tofile=after_header,
513 fromfiledate=u'',
514 tofiledate=u'',
515 n=C.DIFF_CONTEXT)
516 difflines = list(differ)
517 has_diff = False
518 for line in difflines:
519 has_diff = True
520 if line.startswith(u'+'):
521 line = stringc(line, C.COLOR_DIFF_ADD)
522 elif line.startswith(u'-'):
523 line = stringc(line, C.COLOR_DIFF_REMOVE)
524 elif line.startswith(u'@@'):
525 line = stringc(line, C.COLOR_DIFF_LINES)
526 ret.append(line)
527 if has_diff:
528 ret.append('\n')
529 if 'prepared' in diff:
530 ret.append(diff['prepared'])
531 return u''.join(ret)
532
533 def _get_item_label(self, result: _c.Mapping[str, t.Any]) -> t.Any:
534 """ retrieves the value to be displayed as a label for an item entry from a result object"""
535 if result.get('_ansible_no_log', False):
536 item = "(censored due to no_log)"
537 else:
538 item = result.get('_ansible_item_label', result.get('item')) # RPFIX-9: FUTURE: this default shouldn't be here
539 return item
540
541 def _process_items(self, result: CallbackTaskResult) -> None:
542 # just remove them as now they get handled by individual callbacks
543 del result.result['results']
544
545 def _clean_results(self, result, task_name):
546 """ removes data from results for display """
547
548 # mostly controls that debug only outputs what it was meant to
549 # FIXME: this is a terrible heuristic to format debug's output- it masks exception detail
550 if task_name in C._ACTION_DEBUG:
551 if 'msg' in result:
552 # msg should be alone
553 for key in list(result.keys()):
554 if key not in _DEBUG_ALLOWED_KEYS and not key.startswith('_ansible_'):
555 result.pop(key)
556 else:
557 # 'var' value as field, so eliminate others and what is left should be varname
558 for hidme in self._hide_in_debug:
559 result.pop(hidme, None)
560
561 def _print_task_path(self, task, color=C.COLOR_DEBUG):
562 path = task.get_path()
563 if path:
564 self._display.display(u"task path: %s" % path, color=color)
565
566 def set_play_context(self, play_context):
567 pass
568
569 def on_any(self, *args, **kwargs):
570 pass
571
572 def runner_on_failed(self, host, res, ignore_errors=False):
573 pass
574
575 def runner_on_ok(self, host, res):
576 pass
577
578 def runner_on_skipped(self, host, item=None):
579 pass
580
581 def runner_on_unreachable(self, host, res):
582 pass
583
584 def runner_on_async_poll(self, host, res, jid, clock):
585 pass
586
587 def runner_on_async_ok(self, host, res, jid):
588 pass
589
590 def runner_on_async_failed(self, host, res, jid):
591 pass
592
593 def playbook_on_start(self):
594 pass
595
596 def playbook_on_notify(self, host, handler):
597 pass
598
599 def playbook_on_no_hosts_matched(self):
600 pass
601
602 def playbook_on_no_hosts_remaining(self):
603 pass
604
605 def playbook_on_task_start(self, name, is_conditional):
606 pass
607
608 def playbook_on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None, unsafe=None):
609 pass
610
611 def playbook_on_play_start(self, name):
612 pass
613
614 def playbook_on_stats(self, stats):
615 pass
616
617 def on_file_diff(self, host, diff):
618 pass
619
620 # V2 METHODS, by default they call v1 counterparts if possible
621 def v2_on_any(self, *args, **kwargs):
622 self.on_any(args, kwargs)
623
624 def v2_runner_on_failed(self, result: CallbackTaskResult, ignore_errors: bool = False) -> None:
625 """Process results of a failed task.
626
627 Note: The value of 'ignore_errors' tells Ansible whether to
628 continue running tasks on the host where this task failed.
629 But the 'ignore_errors' directive only works when the task can
630 run and returns a value of 'failed'. It does not make Ansible
631 ignore undefined variable errors, connection failures, execution
632 issues (for example, missing packages), or syntax errors.
633
634 :param result: The parameters of the task and its results.
635 :type result: CallbackTaskResult
636 :param ignore_errors: Whether Ansible should continue \
637 running tasks on the host where the task failed.
638 :type ignore_errors: bool
639
640 :return: None
641 :rtype: None
642 """
643 host = result.host.get_name()
644 self.runner_on_failed(host, result.result, ignore_errors)
645
646 def v2_runner_on_ok(self, result: CallbackTaskResult) -> None:
647 """Process results of a successful task.
648
649 :param result: The parameters of the task and its results.
650 :type result: CallbackTaskResult
651
652 :return: None
653 :rtype: None
654 """
655 host = result.host.get_name()
656 self.runner_on_ok(host, result.result)
657
658 def v2_runner_on_skipped(self, result: CallbackTaskResult) -> None:
659 """Process results of a skipped task.
660
661 :param result: The parameters of the task and its results.
662 :type result: CallbackTaskResult
663
664 :return: None
665 :rtype: None
666 """
667 if C.DISPLAY_SKIPPED_HOSTS:
668 host = result.host.get_name()
669 self.runner_on_skipped(host, self._get_item_label(getattr(result.result, 'results', {})))
670
671 def v2_runner_on_unreachable(self, result: CallbackTaskResult) -> None:
672 """Process results of a task if a target node is unreachable.
673
674 :param result: The parameters of the task and its results.
675 :type result: CallbackTaskResult
676
677 :return: None
678 :rtype: None
679 """
680 host = result.host.get_name()
681 self.runner_on_unreachable(host, result.result)
682
683 def v2_runner_on_async_poll(self, result: CallbackTaskResult) -> None:
684 """Get details about an unfinished task running in async mode.
685
686 Note: The value of the `poll` keyword in the task determines
687 the interval at which polling occurs and this method is run.
688
689 :param result: The parameters of the task and its status.
690 :type result: CallbackTaskResult
691
692 :rtype: None
693 :rtype: None
694 """
695 host = result.host.get_name()
696 jid = result.result.get('ansible_job_id')
697 # FIXME, get real clock
698 clock = 0
699 self.runner_on_async_poll(host, result.result, jid, clock)
700
701 def v2_runner_on_async_ok(self, result: CallbackTaskResult) -> None:
702 """Process results of a successful task that ran in async mode.
703
704 :param result: The parameters of the task and its results.
705 :type result: CallbackTaskResult
706
707 :return: None
708 :rtype: None
709 """
710 host = result.host.get_name()
711 jid = result.result.get('ansible_job_id')
712 self.runner_on_async_ok(host, result.result, jid)
713
714 def v2_runner_on_async_failed(self, result: CallbackTaskResult) -> None:
715 host = result.host.get_name()
716 # Attempt to get the async job ID. If the job does not finish before the
717 # async timeout value, the ID may be within the unparsed 'async_result' dict.
718 jid = result.result.get('ansible_job_id')
719 if not jid and 'async_result' in result.result:
720 jid = result.result['async_result'].get('ansible_job_id')
721 self.runner_on_async_failed(host, result.result, jid)
722
723 def v2_playbook_on_start(self, playbook):
724 self.playbook_on_start()
725
726 def v2_playbook_on_notify(self, handler, host):
727 self.playbook_on_notify(host, handler)
728
729 def v2_playbook_on_no_hosts_matched(self):
730 self.playbook_on_no_hosts_matched()
731
732 def v2_playbook_on_no_hosts_remaining(self):
733 self.playbook_on_no_hosts_remaining()
734
735 def v2_playbook_on_task_start(self, task, is_conditional):
736 self.playbook_on_task_start(task.name, is_conditional)
737
738 def v2_playbook_on_handler_task_start(self, task):
739 pass # no v1 correspondence
740
741 def v2_playbook_on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False, salt_size=None, salt=None, default=None, unsafe=None):
742 self.playbook_on_vars_prompt(varname, private, prompt, encrypt, confirm, salt_size, salt, default, unsafe)
743
744 def v2_playbook_on_play_start(self, play):
745 self.playbook_on_play_start(play.name)
746
747 def v2_playbook_on_stats(self, stats):
748 self.playbook_on_stats(stats)
749
750 def v2_on_file_diff(self, result: CallbackTaskResult) -> None:
751 if 'diff' in result.result:
752 host = result.host.get_name()
753 self.on_file_diff(host, result.result['diff'])
754
755 def v2_playbook_on_include(self, included_file):
756 pass # no v1 correspondence
757
758 def v2_runner_item_on_ok(self, result: CallbackTaskResult) -> None:
759 pass
760
761 def v2_runner_item_on_failed(self, result: CallbackTaskResult) -> None:
762 pass
763
764 def v2_runner_item_on_skipped(self, result: CallbackTaskResult) -> None:
765 pass
766
767 def v2_runner_retry(self, result: CallbackTaskResult) -> None:
768 pass
769
770 def v2_runner_on_start(self, host, task):
771 """Event used when host begins execution of a task
772
773 .. versionadded:: 2.8
774 """
775 pass
776
777 _v2_v1_method_map = {
778 v2_on_any: on_any,
779 v2_on_file_diff: on_file_diff,
780 v2_playbook_on_handler_task_start: None,
781 v2_playbook_on_include: None,
782 v2_playbook_on_no_hosts_matched: playbook_on_no_hosts_matched,
783 v2_playbook_on_no_hosts_remaining: playbook_on_no_hosts_remaining,
784 v2_playbook_on_notify: playbook_on_notify,
785 v2_playbook_on_play_start: playbook_on_play_start,
786 v2_playbook_on_start: playbook_on_start,
787 v2_playbook_on_stats: playbook_on_stats,
788 v2_playbook_on_task_start: playbook_on_task_start,
789 v2_playbook_on_vars_prompt: playbook_on_vars_prompt,
790 v2_runner_item_on_failed: None,
791 v2_runner_item_on_ok: None,
792 v2_runner_item_on_skipped: None,
793 v2_runner_on_async_failed: runner_on_async_failed,
794 v2_runner_on_async_ok: runner_on_async_ok,
795 v2_runner_on_async_poll: runner_on_async_poll,
796 v2_runner_on_failed: runner_on_failed,
797 v2_runner_on_ok: runner_on_ok,
798 v2_runner_on_skipped: runner_on_skipped,
799 v2_runner_on_start: None,
800 v2_runner_on_unreachable: runner_on_unreachable,
801 v2_runner_retry: None,
802 }
803 """Internal mapping of v2 callback methods with v1 counterparts; populated after type init for deprecation warnings and bypass calculation."""