|
| 1 | +import sys |
| 2 | +import os |
| 3 | +import time |
| 4 | +import weakref |
| 5 | +import sysconfig |
| 6 | +from ..tracer import PyftraceBase |
| 7 | +from ..utils import get_site_packages_modules, resolve_filename, get_line_number |
| 8 | + |
| 9 | +class PyftraceMonitoring(PyftraceBase): |
| 10 | + """ |
| 11 | + sys.monitoring based tracer. |
| 12 | + """ |
| 13 | + def setup_tracing(self): |
| 14 | + self.tool_id = 1 |
| 15 | + sys.monitoring.use_tool_id(self.tool_id, "pyftrace") |
| 16 | + sys.monitoring.register_callback(self.tool_id, sys.monitoring.events.CALL, self.monitor_call) |
| 17 | + sys.monitoring.register_callback(self.tool_id, sys.monitoring.events.PY_RETURN, self.monitor_py_return) |
| 18 | + sys.monitoring.register_callback(self.tool_id, sys.monitoring.events.C_RETURN, self.monitor_c_return) |
| 19 | + sys.monitoring.register_callback(self.tool_id, sys.monitoring.events.C_RAISE, self.monitor_c_raise) |
| 20 | + sys.monitoring.set_events( |
| 21 | + self.tool_id, |
| 22 | + sys.monitoring.events.CALL | |
| 23 | + sys.monitoring.events.PY_RETURN | |
| 24 | + sys.monitoring.events.C_RETURN | |
| 25 | + sys.monitoring.events.C_RAISE |
| 26 | + ) |
| 27 | + |
| 28 | + def cleanup_tracing(self): |
| 29 | + sys.monitoring.free_tool_id(self.tool_id) |
| 30 | + self.output_stream = None |
| 31 | + |
| 32 | + def run_python_script(self, script_path, script_args): |
| 33 | + if self.output_stream: |
| 34 | + print(f"Running script: {script_path}", file=self.output_stream) |
| 35 | + |
| 36 | + self.script_name = os.path.abspath(script_path) |
| 37 | + self.script_dir = os.path.dirname(self.script_name) |
| 38 | + |
| 39 | + with open(script_path, "r") as file: |
| 40 | + script_code = file.read() |
| 41 | + code_object = compile(script_code, script_path, 'exec') |
| 42 | + |
| 43 | + old_sys_path = sys.path.copy() |
| 44 | + old_sys_argv = sys.argv.copy() |
| 45 | + sys.path.insert(0, self.script_dir) |
| 46 | + sys.argv = [script_path] + script_args |
| 47 | + |
| 48 | + self.tracing_started = False |
| 49 | + |
| 50 | + self.setup_tracing() |
| 51 | + |
| 52 | + try: |
| 53 | + exec(code_object, {"__file__": script_path, "__name__": "__main__"}) |
| 54 | + finally: |
| 55 | + self.cleanup_tracing() |
| 56 | + sys.path = old_sys_path |
| 57 | + sys.argv = old_sys_argv |
| 58 | + |
| 59 | + def monitor_call(self, code, instruction_offset, callable_obj, arg0): |
| 60 | + self.handle_call_event(code, instruction_offset, callable_obj) |
| 61 | + |
| 62 | + def monitor_py_return(self, code, instruction_offset, retval): |
| 63 | + self.handle_py_return_event(code, instruction_offset, retval) |
| 64 | + |
| 65 | + def monitor_c_return(self, code, instruction_offset, callable_obj, arg0): |
| 66 | + self.handle_c_return_event(code, instruction_offset, callable_obj) |
| 67 | + |
| 68 | + def monitor_c_raise(self, code, instruction_offset, callable_obj, arg0): |
| 69 | + pass # Placeholder for handling C_RAISE events |
| 70 | + |
| 71 | + def handle_call_event(self, code, instruction_offset, callable_obj): |
| 72 | + if not self.tracing_started: |
| 73 | + # Start tracing when enter script's '<module>' code |
| 74 | + if code and os.path.abspath(code.co_filename) == os.path.abspath(self.script_name) and code.co_name == '<module>': |
| 75 | + self.tracing_started = True |
| 76 | + else: |
| 77 | + return |
| 78 | + |
| 79 | + call_lineno = get_line_number(code, instruction_offset) |
| 80 | + call_filename = resolve_filename(code, None) |
| 81 | + if call_filename: |
| 82 | + call_filename = os.path.abspath(call_filename) |
| 83 | + |
| 84 | + if isinstance(callable_obj, weakref.ReferenceType): |
| 85 | + callable_obj = callable_obj() |
| 86 | + |
| 87 | + func_name = getattr(callable_obj, '__name__', str(callable_obj)) |
| 88 | + module_name = getattr(callable_obj, '__module__', None) |
| 89 | + is_builtin = module_name in (None, 'builtins') |
| 90 | + |
| 91 | + # Exclude stdlib and frozen modules |
| 92 | + def_filename = '' |
| 93 | + func_def_lineno = '' |
| 94 | + trace_this = False |
| 95 | + |
| 96 | + if hasattr(callable_obj, '__code__'): |
| 97 | + func_def_lineno = callable_obj.__code__.co_firstlineno |
| 98 | + def_filename = os.path.abspath(callable_obj.__code__.co_filename) |
| 99 | + if not self.is_stdlib_code(def_filename): |
| 100 | + trace_this = self.should_trace(def_filename) or self.verbose |
| 101 | + else: |
| 102 | + trace_this = False # Exclude stdlib |
| 103 | + else: |
| 104 | + def_filename = resolve_filename(None, callable_obj) |
| 105 | + if def_filename: |
| 106 | + def_filename = os.path.abspath(def_filename) |
| 107 | + if is_builtin: |
| 108 | + # Only trace built-in functions for `verbose` |
| 109 | + if self.verbose and self.should_trace(call_filename): |
| 110 | + trace_this = True |
| 111 | + else: |
| 112 | + trace_this = False |
| 113 | + else: |
| 114 | + if self.verbose and self.should_trace(def_filename): |
| 115 | + trace_this = True |
| 116 | + |
| 117 | + if trace_this and not self.is_tracer_code(call_filename): |
| 118 | + indent = " " * self.current_depth() |
| 119 | + if self.show_path: |
| 120 | + if is_builtin or not def_filename: |
| 121 | + func_location = f"{func_name}@{module_name or '<builtin>'}" |
| 122 | + else: |
| 123 | + func_location = f"{func_name}@{def_filename}:{func_def_lineno}" |
| 124 | + call_location = f"from {call_filename}:{call_lineno}" |
| 125 | + else: |
| 126 | + func_location = func_name |
| 127 | + call_location = f"from line {call_lineno}" |
| 128 | + if not self.report_mode and self.output_stream: |
| 129 | + print(f"{indent}Called {func_location} {call_location}", file=self.output_stream) |
| 130 | + self.call_stack.append((func_name, is_builtin)) |
| 131 | + if self.report_mode: |
| 132 | + start_time = time.time() |
| 133 | + if func_name in self.execution_report: |
| 134 | + _, total_time, call_count = self.execution_report[func_name] |
| 135 | + self.execution_report[func_name] = (start_time, total_time, call_count + 1) |
| 136 | + else: |
| 137 | + self.execution_report[func_name] = (start_time, 0, 1) |
| 138 | + |
| 139 | + def handle_py_return_event(self, code, instruction_offset, retval): |
| 140 | + if not self.tracing_started: |
| 141 | + return |
| 142 | + |
| 143 | + filename = resolve_filename(code, None) |
| 144 | + if filename: |
| 145 | + filename = os.path.abspath(filename) |
| 146 | + func_name = code.co_name if code else "<unknown>" |
| 147 | + |
| 148 | + # Skip tracing the '<module>' function's return event |
| 149 | + if func_name == '<module>': |
| 150 | + return |
| 151 | + |
| 152 | + trace_this = self.should_trace(filename) or self.verbose |
| 153 | + |
| 154 | + if trace_this and not self.is_tracer_code(filename): |
| 155 | + if self.call_stack: |
| 156 | + stack_func_name, _ = self.call_stack[-1] |
| 157 | + else: |
| 158 | + stack_func_name = "<unknown>" |
| 159 | + |
| 160 | + indent = " " * (self.current_depth() - 1) |
| 161 | + |
| 162 | + if self.show_path: |
| 163 | + file_info = f" @ {filename}" if filename else "" |
| 164 | + else: |
| 165 | + file_info = "" |
| 166 | + |
| 167 | + if stack_func_name == func_name: |
| 168 | + if not self.report_mode and self.output_stream: |
| 169 | + print(f"{indent}Returning {func_name}-> {retval}{file_info}", file=self.output_stream) |
| 170 | + |
| 171 | + if self.report_mode and func_name in self.execution_report: |
| 172 | + start_time, total_time, call_count = self.execution_report[func_name] |
| 173 | + exec_time = time.time() - start_time |
| 174 | + self.execution_report[func_name] = (start_time, total_time + exec_time, call_count) |
| 175 | + |
| 176 | + if self.call_stack and self.call_stack[-1][0] == func_name: |
| 177 | + self.call_stack.pop() |
| 178 | + |
| 179 | + def handle_c_return_event(self, code, instruction_offset, callable_obj): |
| 180 | + if not self.tracing_started: |
| 181 | + return |
| 182 | + |
| 183 | + func_name = getattr(callable_obj, '__name__', str(callable_obj)) |
| 184 | + module_name = getattr(callable_obj, '__module__', None) |
| 185 | + is_builtin = module_name in (None, 'builtins') |
| 186 | + filename = resolve_filename(code, callable_obj) |
| 187 | + if filename: |
| 188 | + filename = os.path.abspath(filename) |
| 189 | + |
| 190 | + # Exclude stdlib and frozen modules |
| 191 | + if self.is_stdlib_code(filename): |
| 192 | + return |
| 193 | + |
| 194 | + trace_this = False |
| 195 | + if is_builtin: |
| 196 | + # Only trace built-in functions if verbose and called from script |
| 197 | + if self.verbose and self.call_stack: |
| 198 | + # Check if the caller is from script |
| 199 | + caller_filename = filename |
| 200 | + if caller_filename and self.should_trace(caller_filename): |
| 201 | + trace_this = True |
| 202 | + else: |
| 203 | + if self.verbose and self.should_trace(filename): |
| 204 | + trace_this = True |
| 205 | + |
| 206 | + if trace_this and not self.is_tracer_code(filename): |
| 207 | + if self.call_stack: |
| 208 | + stack_func_name, _ = self.call_stack[-1] |
| 209 | + else: |
| 210 | + stack_func_name = "<unknown>" |
| 211 | + |
| 212 | + indent = " " * (self.current_depth() - 1) |
| 213 | + |
| 214 | + if self.show_path: |
| 215 | + file_info = f" @ {filename}" if filename else "" |
| 216 | + else: |
| 217 | + file_info = "" |
| 218 | + |
| 219 | + if stack_func_name == func_name: |
| 220 | + if not self.report_mode and self.output_stream: |
| 221 | + print(f"{indent}Returning {func_name}{file_info}", file=self.output_stream) |
| 222 | + if self.report_mode and func_name in self.execution_report: |
| 223 | + start_time, total_time, call_count = self.execution_report[func_name] |
| 224 | + exec_time = time.time() - start_time |
| 225 | + self.execution_report[func_name] = (start_time, total_time + exec_time, call_count) |
| 226 | + if self.call_stack and self.call_stack[-1][0] == func_name: |
| 227 | + self.call_stack.pop() |
| 228 | + |
0 commit comments