Debian Codegraph @

lib/ansible/module_utils/_internal/_debug.py

raw
1 # Copyright: Contributors to the Ansible project
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3
4 from __future__ import annotations
5
6 import contextlib
7 import faulthandler
8 import os
9 import pathlib
10 import platform
11 import signal
12 import tempfile
13 import traceback
14
15 from datetime import datetime
16
17 from ansible.module_utils._internal._logging import log_to_system
18
19
20 def _write_stacktraces(stacktrace_dir: str | None = None):
21 """
22 Signal handler to write debug stacktrace information to a file located in `stacktrace_dir` or to the
23 system's temp directory (the default).
24 """
25
26 def inner(_signum, _frame):
27 now = datetime.now()
28 pid = os.getpid()
29 trace_dir = stacktrace_dir if stacktrace_dir is not None else tempfile.gettempdir()
30 file = pathlib.Path(trace_dir) / f'ansible-{pid}.debug'
31
32 with contextlib.suppress(Exception):
33 # Drop a breadcrumb to help identify where the stacktrace was saved.
34 log_to_system(f"Writing debug stacktrace to {file}", module_name="stacktrace", syslog_facility="LOG_USER")
35
36 # Use O_NOFOLLOW to prevent following a pre-planted symlink at this predictable
37 # path (e.g. in a world-writable temp dir), which would otherwise let a local
38 # attacker redirect the append to an arbitrary file.
39 flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW
40 fd = os.open(file, flags, 0o600)
41 with os.fdopen(fd, 'a') as trace_file:
42 trace_file.write(f'=== {now.isoformat()} on {platform.node()} ===\n\n')
43
44 # The `faulthandler` output will also contain the main process stacktrace (as current thread),
45 # but it won't be as detailed as the `traceback` output.
46 trace_file.write(f'*** Process {pid} stacktrace\n\n')
47 traceback.print_stack(f=_frame, file=trace_file)
48
49 # Let `faulthandler` handle the threads since it can handle those more efficiently/correctly.
50 trace_file.write('\n\n*** Thread stacktraces\n\n')
51 faulthandler.dump_traceback(file=trace_file)
52
53 return inner
54
55
56 def register_for_stacktrace(stacktrace_dir: str | None = None):
57 """Register a signal handler to write debug stacktrace information to a file."""
58 signal.signal(signal.SIGUSR1, _write_stacktraces(stacktrace_dir))