使用 DTrace 和 SystemTap 檢測 CPython

作者:

David Malcolm

作者:

Łukasz Langa

DTrace 和 SystemTap 是監控工具,每個都提供了一種檢查計算機系統上程序正在執行的操作的方法。它們都使用領域特定語言,允許使用者編寫指令碼來

  • 過濾要觀察的程序

  • 從感興趣的程序收集資料

  • 生成資料報告

從 Python 3.6 開始,CPython 可以透過嵌入式“標記”(也稱為“探測”)構建,這些標記可以透過 DTrace 或 SystemTap 指令碼進行觀察,從而更容易監控系統上 CPython 程序正在執行的操作。

CPython 實現細節: DTrace 標記是 CPython 直譯器的實現細節。不保證 CPython 版本之間的探測相容性。更改 CPython 版本時,DTrace 指令碼可能會停止工作或出現錯誤,恕不另行通知。

啟用靜態標記

macOS 自帶 DTrace 支援。在 Linux 上,為了使用 SystemTap 的嵌入式標記構建 CPython,必須安裝 SystemTap 開發工具。

在 Linux 機器上,這可以透過以下方式完成

$ yum install systemtap-sdt-devel

$ sudo apt-get install systemtap-sdt-dev

CPython 必須 使用 --with-dtrace 選項進行配置

checking for --with-dtrace... yes

在 macOS 上,您可以透過在後臺執行 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 上,您可以透過檢視構建的二進位制檔案是否包含“.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

其中列是

  • 自指令碼開始以來的時間(微秒)

  • 可執行檔名

  • 程序 PID

其餘部分指示指令碼執行時的呼叫/返回層次結構。

對於 CPython 的 --enable-shared 構建,標記包含在 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 訪問

  • $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 是收集的物件數量。

import__find__load__start(str modulename)

importlib 嘗試查詢和載入模組之前觸發。arg0 是模組名。

在 3.7 版本加入。

import__find__load__done(str modulename, int found)

importlib 的 find_and_load 函式被呼叫後觸發。arg0 是模組名,arg1 指示模組是否成功載入。

在 3.7 版本加入。

audit(str event, void *tuple)

sys.audit()PySys_Audit() 被呼叫時觸發。arg0 是作為 C 字串的事件名,arg1 是指向元組物件的 PyObject 指標。

在 3.8 版本加入。

SystemTap Tapset

使用 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 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 函式呼叫層次結構的示例,而無需直接命名靜態標記

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 提供了一個類似 top 命令的檢視,顯示所有正在執行的 CPython 程式碼,每秒鐘在整個系統上顯示前 20 個最常進入的位元組碼幀

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;
}