Debian Codegraph @

lib/ansible/module_utils/_internal/_traceback.py

raw
1 # Copyright (c) 2024 Ansible Project
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3
4 """Internal utility code for supporting traceback reporting."""
5
6 from __future__ import annotations
7
8 import enum
9 import traceback
10
11 from . import _stack
12
13
14 class TracebackEvent(enum.Enum):
15 """The events for which tracebacks can be enabled."""
16
17 ERROR = enum.auto()
18 WARNING = enum.auto()
19 DEPRECATED = enum.auto()
20 DEPRECATED_VALUE = enum.auto() # implies DEPRECATED
21
22
23 def traceback_for() -> list[str]:
24 """Return a list of traceback event names (not enums) which are enabled."""
25 return [value.name.lower() for value in TracebackEvent if is_traceback_enabled(value)]
26
27
28 def is_traceback_enabled(event: TracebackEvent) -> bool:
29 """Return True if tracebacks are enabled for the specified event, otherwise return False."""
30 return _is_traceback_enabled(event)
31
32
33 def maybe_capture_traceback(msg: str, event: TracebackEvent) -> str | None:
34 """
35 Optionally capture a traceback for the current call stack, formatted as a string, if the specified traceback event is enabled.
36 Frames marked with the `_skip_stackwalk` local are omitted.
37 """
38 _skip_stackwalk = True
39
40 if not is_traceback_enabled(event):
41 return None
42
43 tb_lines = []
44
45 if frame_info := _stack.caller_frame():
46 # DTFIX-FUTURE: rewrite target-side tracebacks to point at controller-side paths?
47 tb_lines.append('Traceback (most recent call last):\n')
48 tb_lines.extend(traceback.format_stack(frame_info.frame))
49 tb_lines.append(f'Message: {msg}\n')
50 else:
51 tb_lines.append('(frame not found)\n') # pragma: nocover
52
53 return ''.join(tb_lines)
54
55
56 def maybe_extract_traceback(exception: BaseException, event: TracebackEvent) -> str | None:
57 """Optionally extract a formatted traceback from the given exception, if the specified traceback event is enabled."""
58
59 if not is_traceback_enabled(event):
60 return None
61
62 # deprecated: description='use the single-arg version of format_traceback' python_version='3.9'
63 tb_lines = traceback.format_exception(type(exception), exception, exception.__traceback__)
64
65 return ''.join(tb_lines)
66
67
68 _module_tracebacks_enabled_events: frozenset[TracebackEvent] | None = None
69 """Cached enabled TracebackEvent values extracted from `_ansible_tracebacks_for` module arg."""
70
71
72 def _is_module_traceback_enabled(event: TracebackEvent) -> bool:
73 """Module utility function to lazily load traceback config and determine if traceback collection is enabled for the specified event."""
74 global _module_tracebacks_enabled_events
75
76 if _module_tracebacks_enabled_events is None:
77 try:
78 # Suboptimal error handling, but since import order can matter, and this is a critical error path, better to fail silently
79 # than to mask the triggering error by issuing a new error/warning here.
80 from ..basic import _PARSED_MODULE_ARGS
81
82 _module_tracebacks_enabled_events = frozenset(
83 TracebackEvent[value.upper()] for value in _PARSED_MODULE_ARGS.get('_ansible_tracebacks_for', [])
84 ) # type: ignore[union-attr]
85 except BaseException:
86 return True # if things failed early enough that we can't figure this out, assume we want a traceback for troubleshooting
87
88 return event in _module_tracebacks_enabled_events
89
90
91 _is_traceback_enabled = _is_module_traceback_enabled
92 """Callable to determine if tracebacks are enabled. Overridden on the controller by display. Use `is_traceback_enabled` instead of calling this directly."""