使用 DTrace 和 SystemTap 检测CPython

  • 作者:
  • David Malcolm

  • 作者:

  • Łukasz Langa

DTrace和SystemTap是监控工具,它们都提供了一种检查计算机系统上的进程的方法。 它们都使用特定领域的语言,允许用户编写脚本,其中:

  • 进程监视的过滤器

  • 从感兴趣的进程中收集数据

  • 生成有关数据的报告

从Python 3.6开始,CPython可以使用嵌入式“标记”构建,也称为“探测器”,可以通过DTrace或SystemTap脚本观察,从而更容易监视系统上的CPython进程正在做什么。

DTrace标记是CPython解释器的实现细节。 不保证CPython版本之间的探针兼容性。 更改CPython版本时,DTrace脚本可能会停止工作或无法正常工作而不会发出警告。

启用静态标记

macOS内置了对DTrace的支持。 在Linux上,为了使用SystemTap的嵌入式标记构建CPython,必须安装SystemTap开发工具。

在Linux机器上,这可以通过:

  1. $ yum install systemtap-sdt-devel

或者:

  1. $ sudo apt-get install systemtap-sdt-dev

之后 CPython 必须 配置 --with-dtrace 选项:

  1. checking for --with-dtrace... yes

在macOS上,您可以通过在后台运行Python进程列出可用的DTrace探测器,并列出Python程序提供的所有探测器:

  1. $ python3.6 -q &
  2. $ sudo dtrace -l -P python$! # or: dtrace -l -m python3.6
  3.  
  4. ID PROVIDER MODULE FUNCTION NAME
  5. 29564 python18035 python3.6 PyEvalEvalFrameDefault function-entry
  6. 29565 python18035 python3.6 dtrace_function_entry function-entry
  7. 29566 python18035 python3.6 PyEvalEvalFrameDefault function-return
  8. 29567 python18035 python3.6 dtrace_function_return function-return
  9. 29568 python18035 python3.6 collect gc-done
  10. 29569 python18035 python3.6 collect gc-start
  11. 29570 python18035 python3.6 PyEvalEvalFrameDefault line
  12. 29571 python18035 python3.6 maybe_dtrace_line line

在Linux上,您可以通过查看是否包含“.note.stapsdt”部分来验证构建的二进制文件中是否存在SystemTap静态标记。

  1. $ readelf -S ./python | grep .note.stapsdt
  2. [30] .note.stapsdt NOTE 0000000000000000 00308d78

如果你将 Python 编译为共享库(使用 --enable-shared 配置选项),那么你需要改为在共享库内部查看。 例如:

  1. $ readelf -S libpython3.3dm.so.1.0 | grep .note.stapsdt
  2. [29] .note.stapsdt NOTE 0000000000000000 00365b68

足够现代的readelf命令可以打印元数据:

  1. $ readelf -n ./python
  2.  
  3. Displaying notes found at file offset 0x00000254 with length 0x00000020:
  4. Owner Data size Description
  5. GNU 0x00000010 NT_GNU_ABI_TAG (ABI version tag)
  6. OS: Linux, ABI: 2.6.32
  7.  
  8. Displaying notes found at file offset 0x00000274 with length 0x00000024:
  9. Owner Data size Description
  10. GNU 0x00000014 NT_GNU_BUILD_ID (unique build ID bitstring)
  11. Build ID: df924a2b08a7e89f6e11251d4602022977af2670
  12.  
  13. Displaying notes found at file offset 0x002d6c30 with length 0x00000144:
  14. Owner Data size Description
  15. stapsdt 0x00000031 NT_STAPSDT (SystemTap probe descriptors)
  16. Provider: python
  17. Name: gc__start
  18. Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf6
  19. Arguments: -4@%ebx
  20. stapsdt 0x00000030 NT_STAPSDT (SystemTap probe descriptors)
  21. Provider: python
  22. Name: gc__done
  23. Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf8
  24. Arguments: -8@%rax
  25. stapsdt 0x00000045 NT_STAPSDT (SystemTap probe descriptors)
  26. Provider: python
  27. Name: function__entry
  28. Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6be8
  29. Arguments: 8@%rbp 8@%r12 -4@%eax
  30. stapsdt 0x00000046 NT_STAPSDT (SystemTap probe descriptors)
  31. Provider: python
  32. Name: function__return
  33. Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bea
  34. Arguments: 8@%rbp 8@%r12 -4@%eax

上述元数据包含 SystemTap 信息,它描述了如何修补策略性放置的机器码指令以启用 SystemTap 脚本所使用的跟踪钩子。

静态DTrace探针

下面的 DTrace 脚本示例可以用来显示一个 Python 脚本的调用/返回层次结构,只在调用名为 "start" 的函数内进行跟踪。换句话说,导入时的函数调用不会被列出。

  1. self int indent;
  2.  
  3. python$target:::function-entry
  4. copyinstr(arg1) == "start"
  5. {
  6. self->trace = 1;
  7. }
  8.  
  9. python$target:::function-entry
  10. self->trace
  11. {
  12. printf("%d\t%*s:", timestamp, 15, probename);
  13. printf("%*s", self->indent, "");
  14. printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
  15. self->indent++;
  16. }
  17.  
  18. python$target:::function-return
  19. self->trace
  20. {
  21. self->indent--;
  22. printf("%d\t%*s:", timestamp, 15, probename);
  23. printf("%*s", self->indent, "");
  24. printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
  25. }
  26.  
  27. python$target:::function-return
  28. copyinstr(arg1) == "start"
  29. {
  30. self->trace = 0;
  31. }

它可以这样调用:

  1. $ sudo dtrace -q -s call_stack.d -c "python3.6 script.py"

输出结果会像这样:

  1. 156641360502280 function-entry:call_stack.py:start:23
  2. 156641360518804 function-entry: call_stack.py:function_1:1
  3. 156641360532797 function-entry: call_stack.py:function_3:9
  4. 156641360546807 function-return: call_stack.py:function_3:10
  5. 156641360563367 function-return: call_stack.py:function_1:2
  6. 156641360578365 function-entry: call_stack.py:function_2:5
  7. 156641360591757 function-entry: call_stack.py:function_1:1
  8. 156641360605556 function-entry: call_stack.py:function_3:9
  9. 156641360617482 function-return: call_stack.py:function_3:10
  10. 156641360629814 function-return: call_stack.py:function_1:2
  11. 156641360642285 function-return: call_stack.py:function_2:6
  12. 156641360656770 function-entry: call_stack.py:function_3:9
  13. 156641360669707 function-return: call_stack.py:function_3:10
  14. 156641360687853 function-entry: call_stack.py:function_4:13
  15. 156641360700719 function-return: call_stack.py:function_4:14
  16. 156641360719640 function-entry: call_stack.py:function_5:18
  17. 156641360732567 function-return: call_stack.py:function_5:21
  18. 156641360747370 function-return:call_stack.py:start:28

静态SystemTap标记

使用 SystemTap 集成的底层方法是直接使用静态标记。 这需要你显式地说明包含它们的二进制文件。

例如,这个SystemTap脚本可以用来显示Python脚本的调用/返回层次结构:

  1. probe process("python").mark("function__entry") {
  2. filename = user_string($arg1);
  3. funcname = user_string($arg2);
  4. lineno = $arg3;
  5.  
  6. printf("%s => %s in %s:%d\\n",
  7. thread_indent(1), funcname, filename, lineno);
  8. }
  9.  
  10. probe process("python").mark("function__return") {
  11. filename = user_string($arg1);
  12. funcname = user_string($arg2);
  13. lineno = $arg3;
  14.  
  15. printf("%s <= %s in %s:%d\\n",
  16. thread_indent(-1), funcname, filename, lineno);
  17. }

它可以这样调用:

  1. $ stap \ show-call-hierarchy.stp \ -c "./python test.py"

输出结果会像这样:

  1. 11408 python(8274): => __contains__ in Lib/_abcoll.py:362
  2. 11414 python(8274): => __getitem__ in Lib/os.py:425
  3. 11418 python(8274): => encode in Lib/os.py:490
  4. 11424 python(8274): <= encode in Lib/os.py:493
  5. 11428 python(8274): <= __getitem__ in Lib/os.py:426
  6. 11433 python(8274): <= __contains__ in Lib/_abcoll.py:366

其中的列是:

  • 脚本开始后经过的微秒数

  • 可执行文件的名字

  • 进程的PID

其余部分则表示脚本执行时的调用/返回层次结构。

对于 CPython 的 --enable-shared 编译版,这些标记包含在 libpython 共享库内部,并且 probe 的加点路径需要反映这个。 例如,上述示例的这一行:

  1. probe process("python").mark("function__entry") {

应改为:

  1. probe process("python").library("libpython3.6dm.so.1.0").mark("function__entry") {

(假定为 CPython 3.6 的 调试编译版)

可用的静态标记

  • function__entry(str filename, str funcname, int lineno)
  • 这个标记表示一个Python函数的执行已经开始。它只对纯 Python (字节码)函数触发。

文件名、函数名和行号作为位置参数提供给跟踪脚本,必须使用 $arg1, $arg2, $arg3 访问:

  • $arg1 : (const char *) 文件名,使用 user_string($arg1) 访问

  • $arg2 : (const char *) 函数名,使用 user_string($arg2) 访问

  • $arg3 : int 行号

  • function__return(str filename, str funcname, int lineno)
  • 这个标记与 function__entry() 相反,表示 Python 函数的执行已经结束(通过 return,或者通过异常)。 它只会为纯 Python(字节码)函数触发。

参数与 function__entry() 的相同

  • line(str filename, str funcname, int lineno)
  • 这个标记表示一个 Python 行即将被执行。它相当于用 Python 分析器逐行追踪。它不会在C函数中触发。

参数与 function__entry() 的相同。

  • gc__start(int generation)
  • 当 Python 解释器启动一个垃圾回收循环时触发。 arg0 是要扫描的代,与 gc.collect() 一样。
  • gc__done(long collected)
  • 当Python解释器完成一个垃圾回收循环时被触发。arg0 是收集到的对象的数量。
  • importfindload__start(str modulename)
  • importlib 试图查找并加载模块之前被触发。arg0 是模块名称。

Added in version 3.7.

  • importfindload__done(str modulename, int found)
  • importlib 的 find_and_load 函数被调用后被触发 。arg0 是模块名称, arg1 表示模块是否成功加载。

Added in version 3.7.

  • audit(str event, void *tuple)
  • sys.audit()PySys_Audit() 被调用时启动。 arg0 是事件名称的 C 字符串,arg1 是一个指向元组对象的 PyObject 指针。

Added in version 3.8.

SystemTap Tapsets

使用SystemTap集成的更高层次的方法是使用 "tapset" 。SystemTap 的等效库,它隐藏了静态标记的一些底层细节。

这里是一个基于 CPython 的非共享构建的 tapset 文件。

  1. /*
  2. 提供对 function__entry 和 function__return 标记的高级封装
  3. \*/
  4. probe python.function.entry = process("python").mark("function__entry")
  5. {
  6. filename = user_string($arg1);
  7. funcname = user_string($arg2);
  8. lineno = $arg3;
  9. frameptr = $arg4
  10. }
  11. probe python.function.return = process("python").mark("function__return")
  12. {
  13. filename = user_string($arg1);
  14. funcname = user_string($arg2);
  15. lineno = $arg3;
  16. frameptr = $arg4
  17. }

如果这个文件安装在 SystemTap 的 tapset 目录下(例如 usrshare/systemtap/tapset ),那么这些额外的探测点就会变得可用。

  • python.function.entry(str filename, str funcname, int lineno, frameptr)
  • 这个探针点表示一个Python函数的执行已经开始。它只对纯Python (字节码)函数触发。
  • python.function.return(str filename, str funcname, int lineno, frameptr)
  • 这个探针点是 python.function.return 的反义操作,表示一个 Python 函数的执行已经结束(或是通过 return,或是通过异常)。 它只会针对纯 Python(字节码)函数触发。

例子

这个SystemTap脚本使用上面的tapset来更清晰地实现上面给出的跟踪Python函数调用层次结构的例子,而不需要直接命名静态标记。

  1. probe python.function.entry
  2. {
  3. printf("%s => %s in %s:%d\n",
  4. thread_indent(1), funcname, filename, lineno);
  5. }
  6.  
  7. probe python.function.return
  8. {
  9. printf("%s <= %s in %s:%d\n",
  10. thread_indent(-1), funcname, filename, lineno);
  11. }

下面的脚本使用上面的 tapset 来提供所有运行中的 CPython 代码的类似 top 的视图,显示了整个系统中每一秒内前 20 个最频繁进入的字节码帧:

  1. global fn_calls;
  2.  
  3. probe python.function.entry
  4. {
  5. fn_calls[pid(), filename, funcname, lineno] += 1;
  6. }
  7.  
  8. probe timer.ms(1000) {
  9. printf("\033[2J\033[1;1H") /* clear screen \*/
  10. printf("%6s %80s %6s %30s %6s\n",
  11. "PID", "FILENAME", "LINE", "FUNCTION", "CALLS")
  12. foreach ([pid, filename, funcname, lineno] in fn_calls-limit 20) {
  13. printf("%6d %80s %6d %30s %6d\n",
  14. pid, filename, lineno, funcname,
  15. fn_calls[pid, filename, funcname, lineno]);
  16. }
  17. delete fn_calls;
  18. }