使用 DTrace 和 SystemTap 检测 CPython

  • author

    • David Malcolm
  • author

    • Łukasz Langa

DTrace 和 SystemTap 是监视工具,每个工具都提供一种检查计算机系统上的进程正在执行的方式。它们都使用特定于域的语言,允许用户编写以下脚本:

Note

  • 筛选要观察的过程

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

  • 生成数据报告

从 Python 3.6 开始,CPython 可以使用嵌入的“标记”(也称为“探针”)构建,可以pass DTrace 或 SystemTap 脚本观察到这些标记,从而可以更轻松地监视系统上 CPython 进程的运行情况。

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

启用静态标记

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

在 Linux 机器上,这可以pass以下方式完成:

$ yum install systemtap-sdt-devel

or:

$ sudo apt-get install systemtap-sdt-dev

然后必须将 CPython 配置为--with-dtrace

checking for --with-dtrace... yes

在 macOS 上,您可以pass在后台运行 Python 进程并列出 Python 提供程序提供的所有探针来列出可用的 DTrace 探针:

$ python3.6 -q &
$ sudo dtrace -l -P python$!  # or: dtrace -l -m python3.6

   ID   PROVIDER            MODULE                          FUNCTION NAME
29564 python18035        python3.6          _PyEval_EvalFrameDefault function-entry
29565 python18035        python3.6             dtrace_function_entry function-entry
29566 python18035        python3.6          _PyEval_EvalFrameDefault function-return
29567 python18035        python3.6            dtrace_function_return function-return
29568 python18035        python3.6                           collect gc-done
29569 python18035        python3.6                           collect gc-start
29570 python18035        python3.6          _PyEval_EvalFrameDefault line
29571 python18035        python3.6                 maybe_dtrace_line line

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

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

如果您已将 Python 构建为共享库(带有–enable-shared),则需要在共享库中查找。例如:

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

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

$ readelf -n ./python

Displaying notes found at file offset 0x00000254 with length 0x00000020:
    Owner                 Data size          Description
    GNU                  0x00000010          NT_GNU_ABI_TAG (ABI version tag)
        OS: Linux, ABI: 2.6.32

Displaying notes found at file offset 0x00000274 with length 0x00000024:
    Owner                 Data size          Description
    GNU                  0x00000014          NT_GNU_BUILD_ID (unique build ID bitstring)
        Build ID: df924a2b08a7e89f6e11251d4602022977af2670

Displaying notes found at file offset 0x002d6c30 with length 0x00000144:
    Owner                 Data size          Description
    stapsdt              0x00000031          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: gc__start
        Location: 0x00000000004371c3, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf6
        Arguments: -4@%ebx
    stapsdt              0x00000030          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: gc__done
        Location: 0x00000000004374e1, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bf8
        Arguments: -8@%rax
    stapsdt              0x00000045          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: function__entry
        Location: 0x000000000053db6c, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6be8
        Arguments: 8@%rbp 8@%r12 -4@%eax
    stapsdt              0x00000046          NT_STAPSDT (SystemTap probe descriptors)
        Provider: python
        Name: function__return
        Location: 0x000000000053dba8, Base: 0x0000000000630ce2, Semaphore: 0x00000000008d6bea
        Arguments: 8@%rbp 8@%r12 -4@%eax

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

DTrace 静态探针

以下示例 DTrace 脚本可用于显示 Python 脚本的调用/返回层次结构,仅在称为“ start”的函数调用内进行跟踪。换句话说,导入时间函数调用将不会列出:

self int indent;

python$target:::function-entry
/copyinstr(arg1) == "start"/
{
        self->trace = 1;
}

python$target:::function-entry
/self->trace/
{
        printf("%d\t%*s:", timestamp, 15, probename);
        printf("%*s", self->indent, "");
        printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
        self->indent++;
}

python$target:::function-return
/self->trace/
{
        self->indent--;
        printf("%d\t%*s:", timestamp, 15, probename);
        printf("%*s", self->indent, "");
        printf("%s:%s:%d\n", basename(copyinstr(arg0)), copyinstr(arg1), arg2);
}

python$target:::function-return
/copyinstr(arg1) == "start"/
{
        self->trace = 0;
}

可以这样调用:

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

输出如下所示:

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

静态 SystemTap 标记

使用 SystemTap 集成的底层方法是直接使用静态标记。这要求您明确语句包含它们的二进制文件。

例如,此 SystemTap 脚本可用于显示 Python 脚本的调用/返回层次结构:

probe process("python").mark("function__entry") {
     filename = user_string($arg1);
     funcname = user_string($arg2);
     lineno = $arg3;

     printf("%s => %s in %s:%d\\n",
            thread_indent(1), funcname, filename, lineno);
}

probe process("python").mark("function__return") {
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;

    printf("%s <= %s in %s:%d\\n",
           thread_indent(-1), funcname, filename, lineno);
}

可以这样调用:

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

输出如下所示:

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

列在哪里:

Note

  • 自脚本开始以来的时间(以微秒为单位)

  • 可执行文件的名称

  • 过程的 PID

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

对于 Cenable 共享的内部版本,标记包含在 libpython 共享库中,并且探针的虚线路径需要反映这一点。例如,以上示例中的这一行:

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

应该改为:

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进行访问:

Note

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

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

  • $arg3int行号

  • function__return(str * filename *,str * funcname *,int * lineno *)
    • 该标记与function__entry()相反,表示 Python 函数的执行已结束(passreturn或pass异常)。仅针对纯 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((已收集)*

    • 当 Python 解释器完成垃圾收集周期时触发。 arg0是收集的对象数。
  • import__find__load__start(str 模块名称)

    • importlibtry查找和加载模块之前触发。 arg0是模块名称。

3.7 版中的新Function。

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

3.7 版中的新Function。

  • audit(str * event *,void ** tuple *)

3.8 版的新Function。

SystemTap Tapsets

使用 SystemTap 集成的高级方法是使用“ tapset”:SystemTap 相当于库,它隐藏了静态标记的一些低级详细信息。

这是一个基于非共享 CPython 版本的 tapset 文件:

/*
   Provide a higher-level wrapping around the function__entry and
   function__return markers:
 \*/
probe python.function.entry = process("python").mark("function__entry")
{
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;
    frameptr = $arg4
}
probe python.function.return = process("python").mark("function__return")
{
    filename = user_string($arg1);
    funcname = user_string($arg2);
    lineno = $arg3;
    frameptr = $arg4
}

如果此文件安装在 SystemTap 的 tapset 目录中(例如/usr/share/systemtap/tapset),则这些其他探测点将变为可用:

  • python.function.entry(str 文件名,str Function名,int * lineno *,frameptr)

    • 该探测点指示 Python 函数的执行已开始。仅针对纯 Python(字节码)函数触发。
  • python.function.return(str 文件名,str Function名,int * lineno *,frameptr)

    • 该探测点与python.function.return()相反,它指示 Python 函数的执行已结束(passreturn或pass异常)。仅针对纯 Python(字节码)函数触发。

Examples

此 SystemTap 脚本使用上面的 tapset 来更干净地实现上面给出的跟踪 Python 函数调用层次结构的示例,而无需直接命名静态标记:

probe python.function.entry
{
  printf("%s => %s in %s:%d\n",
         thread_indent(1), funcname, filename, lineno);
}

probe python.function.return
{
  printf("%s <= %s in %s:%d\n",
         thread_indent(-1), funcname, filename, lineno);
}

下面的脚本使用上面的 tapset 提供所有正在运行的 CPython 代码的俯视图,显示整个系统中排名前 20 位的最频繁 Importing 的字节码帧:

global fn_calls;

probe python.function.entry
{
    fn_calls[pid(), filename, funcname, lineno] += 1;
}

probe timer.ms(1000) {
    printf("\033[2J\033[1;1H") /* clear screen \*/
    printf("%6s %80s %6s %30s %6s\n",
           "PID", "FILENAME", "LINE", "FUNCTION", "CALLS")
    foreach ([pid, filename, funcname, lineno] in fn_calls- limit 20) {
        printf("%6d %80s %6d %30s %6d\n",
            pid, filename, lineno, funcname,
            fn_calls[pid, filename, funcname, lineno]);
    }
    delete fn_calls;
}