Files
bpf-developer-tutorial/bcc-documents/tutorial_bcc_python_developer.html

835 lines
51 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE HTML>
<html lang="en" class="light" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>bcc Python Developer Tutorial - bpf-developer-tutorial</title>
<!-- Custom HTML head -->
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="../favicon.svg">
<link rel="shortcut icon" href="../favicon.png">
<link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/general.css">
<link rel="stylesheet" href="../css/chrome.css">
<link rel="stylesheet" href="../css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="../fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" href="../highlight.css">
<link rel="stylesheet" href="../tomorrow-night.css">
<link rel="stylesheet" href="../ayu-highlight.css">
<!-- Custom theme stylesheets -->
</head>
<body class="sidebar-visible no-js">
<div id="body-container">
<!-- Provide site root to javascript -->
<script>
var path_to_root = "../";
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
</script>
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
var theme = localStorage.getItem('mdbook-theme');
var sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
var theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
var html = document.querySelector('html');
html.classList.remove('light')
html.classList.add(theme);
var body = document.querySelector('body');
body.classList.remove('no-js')
body.classList.add('js');
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
var body = document.querySelector('body');
var sidebar = null;
var sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
body.classList.remove('sidebar-visible');
body.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<div class="sidebar-scrollbox">
<ol class="chapter"><li class="chapter-item expanded affix "><a href="../https://github.com/eunomia-bpf/bpf-developer-tutorial.html">https://github.com/eunomia-bpf/bpf-developer-tutorial</a></li><li class="chapter-item expanded affix "><li class="part-title">入门文档</li><li class="chapter-item expanded "><a href="../0-introduce/index.html"><strong aria-hidden="true">1.</strong> lesson 0-introduce</a></li><li class="chapter-item expanded "><a href="../1-helloworld/index.html"><strong aria-hidden="true">2.</strong> lesson 1-helloworld</a></li><li class="chapter-item expanded "><a href="../2-kprobe-unlink/index.html"><strong aria-hidden="true">3.</strong> lesson 2-kprobe-unlink</a></li><li class="chapter-item expanded "><a href="../3-fentry-unlink/index.html"><strong aria-hidden="true">4.</strong> lesson 3-fentry-unlink</a></li><li class="chapter-item expanded "><a href="../4-opensnoop/index.html"><strong aria-hidden="true">5.</strong> lesson 4-opensnoop</a></li><li class="chapter-item expanded "><a href="../5-uprobe-bashreadline/index.html"><strong aria-hidden="true">6.</strong> lesson 5-uprobe-bashreadline</a></li><li class="chapter-item expanded "><a href="../6-sigsnoop/index.html"><strong aria-hidden="true">7.</strong> lesson 6-sigsnoop</a></li><li class="chapter-item expanded "><a href="../7-execsnoop/index.html"><strong aria-hidden="true">8.</strong> lesson 7-execsnoop</a></li><li class="chapter-item expanded "><a href="../8-exitsnoop/index.html"><strong aria-hidden="true">9.</strong> lesson 8-execsnoop</a></li><li class="chapter-item expanded "><a href="../9-runqlat/index.html"><strong aria-hidden="true">10.</strong> lesson 9-runqlat</a></li><li class="chapter-item expanded "><a href="../10-hardirqs/index.html"><strong aria-hidden="true">11.</strong> lesson 10-hardirqs</a></li><li class="chapter-item expanded affix "><li class="part-title">进阶文档和示例</li><li class="chapter-item expanded "><a href="../11-bootstrap/index.html"><strong aria-hidden="true">12.</strong> lesson 11-bootstrap</a></li><li class="chapter-item expanded "><a href="../12-profile/index.html"><strong aria-hidden="true">13.</strong> lesson 12-profile</a></li><li class="chapter-item expanded "><a href="../13-tcpconnlat/index.html"><strong aria-hidden="true">14.</strong> lesson 13-tcpconnlat</a></li><li class="chapter-item expanded "><a href="../14-tcpstates/index.html"><strong aria-hidden="true">15.</strong> lesson 14-tcpstates</a></li><li class="chapter-item expanded "><a href="../15-javagc/index.html"><strong aria-hidden="true">16.</strong> lesson 15-javagc</a></li><li class="chapter-item expanded "><a href="../16-memleak/index.html"><strong aria-hidden="true">17.</strong> lesson 16-memleak</a></li><li class="chapter-item expanded "><a href="../17-biopattern/index.html"><strong aria-hidden="true">18.</strong> lesson 17-biopattern</a></li><li class="chapter-item expanded "><a href="../18-further-reading/index.html"><strong aria-hidden="true">19.</strong> lesson 18-further-reading</a></li><li class="chapter-item expanded "><a href="../19-lsm-connect/index.html"><strong aria-hidden="true">20.</strong> lesson 19-lsm-connect</a></li><li class="chapter-item expanded "><a href="../20-tc/index.html"><strong aria-hidden="true">21.</strong> lesson 20-tc</a></li><li class="chapter-item expanded "><a href="../21-xdp/index.html"><strong aria-hidden="true">22.</strong> lesson 21-xdp</a></li><li class="chapter-item expanded affix "><li class="part-title">高级主题</li><li class="chapter-item expanded "><a href="../22-android/index.html"><strong aria-hidden="true">23.</strong> 在 Android 上使用 eBPF 程序</a></li><li class="chapter-item expanded "><a href="../30-sslsniff/index.html"><strong aria-hidden="true">24.</strong> 使用 uprobe 捕获多种库的 SSL/TLS 明文数据</a></li><li class="chapter-item expanded "><a href="../23-http/index.html"><strong aria-hidden="true">25.</strong> 使用 eBPF socket filter 或 syscall trace 追踪 HTTP 请求和其他七层协议</a></li><li class="chapter-item expanded "><a href="../29-sockops/index.html"><strong aria-hidden="true">26.</strong> 使用 sockops 加速网络请求转发</a></li><li class="chapter-item expanded "><a href="../34-syscall/index.html"><strong aria-hidden="true">27.</strong> 使用 eBPF 修改系统调用参数</a></li><li class="chapter-item expanded "><a href="../24-hide/index.html"><strong aria-hidden="true">28.</strong> 使用 eBPF 隐藏进程或文件信息</a></li><li class="chapter-item expanded "><a href="../25-signal/index.html"><strong aria-hidden="true">29.</strong> 使用 bpf_send_signal 发送信号终止进程</a></li><li class="chapter-item expanded "><a href="../26-sudo/index.html"><strong aria-hidden="true">30.</strong> 使用 eBPF 添加 sudo 用户</a></li><li class="chapter-item expanded "><a href="../27-replace/index.html"><strong aria-hidden="true">31.</strong> 使用 eBPF 替换任意程序读取或写入的文本</a></li><li class="chapter-item expanded "><a href="../28-detach/index.html"><strong aria-hidden="true">32.</strong> BPF 的生命周期:使用 Detached 模式在用户态应用退出后持续运行 eBPF 程序</a></li><li class="chapter-item expanded "><a href="../18-further-reading/ebpf-security.zh.html"><strong aria-hidden="true">33.</strong> eBPF 运行时的安全性与面临的挑战</a></li><li class="chapter-item expanded "><a href="../src/36-userspace-ebpf/README.html"><strong aria-hidden="true">34.</strong> 用户空间 eBPF 运行时:深度解析与应用实践</a></li><li class="chapter-item expanded affix "><li class="part-title">bcc 教程与文档</li><li class="chapter-item expanded "><a href="../bcc-documents/kernel-versions.html"><strong aria-hidden="true">35.</strong> BPF Features by Linux Kernel Version</a></li><li class="chapter-item expanded "><a href="../bcc-documents/kernel_config.html"><strong aria-hidden="true">36.</strong> Kernel Configuration for BPF Features</a></li><li class="chapter-item expanded "><a href="../bcc-documents/reference_guide.html"><strong aria-hidden="true">37.</strong> bcc Reference Guide</a></li><li class="chapter-item expanded "><a href="../bcc-documents/special_filtering.html"><strong aria-hidden="true">38.</strong> Special Filtering</a></li><li class="chapter-item expanded "><a href="../bcc-documents/tutorial.html"><strong aria-hidden="true">39.</strong> bcc Tutorial</a></li><li class="chapter-item expanded "><a href="../bcc-documents/tutorial_bcc_python_developer.html" class="active"><strong aria-hidden="true">40.</strong> bcc Python Developer Tutorial</a></li></ol>
</div>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<!-- Track and set sidebar scroll position -->
<script>
var sidebarScrollbox = document.querySelector('#sidebar .sidebar-scrollbox');
sidebarScrollbox.addEventListener('click', function(e) {
if (e.target.tagName === 'A') {
sessionStorage.setItem('sidebar-scroll', sidebarScrollbox.scrollTop);
}
}, { passive: true });
var sidebarScrollTop = sessionStorage.getItem('sidebar-scroll');
sessionStorage.removeItem('sidebar-scroll');
if (sidebarScrollTop) {
// preserve sidebar scroll position when navigating via links within sidebar
sidebarScrollbox.scrollTop = sidebarScrollTop;
} else {
// scroll sidebar to current active section when navigating via "next/previous chapter" buttons
var activeSection = document.querySelector('#sidebar .active');
if (activeSection) {
activeSection.scrollIntoView({ block: 'center' });
}
}
</script>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">bpf-developer-tutorial</h1>
<div class="right-buttons">
<a href="../print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="bcc-python-开发者教程"><a class="header" href="#bcc-python-开发者教程">bcc Python 开发者教程</a></h1>
<p>本教程介绍使用 Python 接口开发 <a href="https://github.com/iovisor/bcc">bcc</a> 工具和程序。分为两个部分:可观测性和网络。代码片段取自 bcc 的各个程序,请查阅其文件以了解许可证情况。</p>
<p>还请参阅 bcc 开发者的<a href="reference_guide.html">参考指南</a>,以及针对工具的用户的教程:<a href="tutorial.html">教程</a>。还有适用于 bcc 的 lua 接口。</p>
<h2 id="可观测性"><a class="header" href="#可观测性">可观测性</a></h2>
<p>这个可观测性教程包含17个课程和46个要学习的枚举事项。</p>
<h3 id="第1课-你好世界"><a class="header" href="#第1课-你好世界">第1课. 你好,世界</a></h3>
<p>首先运行 <a href="https://github.com/iovisor/bcc/tree/master/examples/hello_world.py">examples/hello_world.py</a>同时在另一个会话中运行一些命令例如“ls”。它应该会为新进程打印“Hello, World!”。如果没有打印请先修复bcc请参阅 <a href="https://github.com/iovisor/bcc/tree/master/INSTALL.md">INSTALL.md</a></p>
<pre><code class="language-sh"># ./examples/hello_world.py
bash-13364 [002] d... 24573433.052937: : Hello, World!
bash-13364 [003] d... 24573436.642808: : Hello, World!
[...]
</code></pre>
<p>以下是 hello_world.py 的代码示例:</p>
<pre><code class="language-Python">from bcc import BPF
BPF(text='int kprobe__sys_clone(void *ctx) { bpf_trace_printk(&quot;Hello, World!\\n&quot;); return 0; }').trace_print()
</code></pre>
<p>从中可以学到六件事情:</p>
<ol>
<li>
<p><code>text='...'</code>:这定义了内联的 BPF 程序。该程序是用 C 编写的。</p>
</li>
<li>
<p><code>kprobe__sys_clone()</code>:这是通过 kprobes 动态跟踪内核的一种快捷方式。如果 C 函数以 <code>kprobe__</code> 开头,其余部分将被视为要定位的内核函数名称,本例中为 <code>sys_clone()</code></p>
</li>
<li>
<p><code>void *ctx</code>ctx 是参数,但由于我们在此处未使用它们,所以我们将其转换为 <code>void*</code> 类型。</p>
</li>
<li>
<p><code>bpf_trace_printk()</code>: 用于将 printf() 打印到通用 trace_pipe (/sys/kernel/debug/tracing/trace_pipe) 的简单内核工具。 这对于一些快速示例是可以的,但有一些限制:最多只有 3 个参数,只能有一个 %s并且 trace_pipe 是全局共享的,所以并发程序会有冲突的输出。更好的接口是通过 BPF_PERF_OUTPUT() 实现的,稍后会介绍。</p>
</li>
<li>
<p><code>return 0;</code>: 必要的规范性代码(如果想知道原因,请参见 <a href="https://github.com/iovisor/bcc/issues/139">#139</a>)。</p>
</li>
<li>
<p><code>.trace_print()</code>: 一个读取 trace_pipe 并打印输出的 bcc 程序。</p>
</li>
</ol>
<h3 id="第二课-sys_sync"><a class="header" href="#第二课-sys_sync">第二课 sys_sync()</a></h3>
<p>编写一个跟踪 sys_sync() 内核函数的程序。运行时打印 &quot;sys_sync() called&quot;。在跟踪时,在另一个会话中运行 <code>sync</code> 进行测试。hello_world.py 程序中包含了这一切所需的内容。</p>
<p>通过在程序刚启动时打印 &quot;Tracing sys_sync()... Ctrl-C to end.&quot; 来改进它。提示:它只是 Python 代码。</p>
<h3 id="第三课-hello_fieldspy"><a class="header" href="#第三课-hello_fieldspy">第三课 hello_fields.py</a></h3>
<p>该程序位于 <a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/hello_fields.py">examples/tracing/hello_fields.py</a>。样本输出(在另一个会话中运行命令):</p>
<pre><code class="language-sh"># examples/tracing/hello_fields.py
时间(s) 进程名 进程 ID 消息
24585001.174885999 sshd 1432 你好,世界!
24585001.195710000 sshd 15780 你好,世界!
24585001.991976000 systemd-udevd 484 你好,世界!
24585002.276147000 bash 15787 你好,世界!
</code></pre>
<p>代码:</p>
<pre><code class="language-Python">from bcc import BPF
# 定义 BPF 程序
prog = &quot;&quot;&quot;
int hello(void *ctx) {
bpf_trace_printk(&quot;你好,世界!\\n&quot;);
return 0;
}
&quot;&quot;&quot;
# 加载 BPF 程序
b = BPF(text=prog)
b.attach_kprobe(event=b.get_syscall_fnname(&quot;clone&quot;), fn_name=&quot;hello&quot;)
# 头部
print(&quot;%-18s %-16s %-6s %s&quot; % (&quot;时间(s)&quot;, &quot;进程名&quot;, &quot;进程 ID&quot;, &quot;消息&quot;))
# 格式化输出
while 1:
try:
(task, pid, cpu, flags, ts, msg) = b.trace_fields()
except ValueError:
continue
print(&quot;%-18.9f %-16s %-6d %s&quot; % (ts, task, pid, msg))
</code></pre>
<p>这与hello_world.py类似并通过sys_clone()再次跟踪新进程,但是还有一些要学习的内容:</p>
<ol>
<li>
<p><code>prog =</code>这次我们将C程序声明为变量然后引用它。如果您想根据命令行参数添加一些字符串替换这将非常有用。</p>
</li>
<li>
<p><code>hello()</code>现在我们只是声明了一个C函数而不是使用<code>kprobe__</code>的快捷方式。我们稍后会引用它。在BPF程序中声明的所有C函数都希望在探测器上执行因此它们都需要以<code>pt_reg* ctx</code>作为第一个参数。如果您需要定义一些不会在探测器上执行的辅助函数,则需要将其定义为<code>static inline</code>,以便由编译器内联。有时您还需要为其添加<code>_always_inline</code>函数属性。</p>
</li>
<li>
<p><code>b.attach_kprobe(event=b.get_syscall_fnname(&quot;clone&quot;), fn_name=&quot;hello&quot;)</code>为内核clone系统调用函数创建一个kprobe该函数将执行我们定义的hello()函数。您可以多次调用attach_kprobe()并将您的C函数附加到多个内核函数上。</p>
</li>
<li>
<p><code>b.trace_fields()</code>从trace_pipe中返回一组固定的字段。与trace_print()类似它对于编写脚本很方便但是对于实际的工具化需求我们应该切换到BPF_PERF_OUTPUT()。</p>
</li>
</ol>
<h3 id="lesson-4-sync_timingpy"><a class="header" href="#lesson-4-sync_timingpy">Lesson 4. sync_timing.py</a></h3>
<p>还记得以前系统管理员在缓慢的控制台上输入<code>sync</code>三次然后才重启吗?后来有人认为<code>sync;sync;sync</code>很聪明将它们都写在一行上运行尽管这违背了最初的目的然后sync变成了同步操作所以更加愚蠢。无论如何。</p>
<p>以下示例计算了<code>do_sync</code>函数被调用的速度,并且如果它在一秒钟之内被调用,则输出信息。<code>sync;sync;sync</code>将为第2个和第3个sync打印输出</p>
<pre><code class="language-sh"># examples/tracing/sync_timing.py
追踪快速sync... 按Ctrl-C结束&quot;
</code></pre>
<p>在时间0.00秒时检测到多个同步上次发生在95毫秒前
在时间0.10秒时检测到多个同步上次发生在96毫秒前</p>
<p>此程序是<a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/sync_timing.py">examples/tracing/sync_timing.py</a></p>
<pre><code class="language-Python">from __future__ import print_function
from bcc import BPF
# 加载BPF程序
b = BPF(text=&quot;&quot;&quot;
#include &lt;uapi/linux/ptrace.h&gt;
BPF_HASH(last);
int do_trace(struct pt_regs *ctx) {
u64 ts, *tsp, delta, key = 0;
// 尝试读取存储的时间戳
tsp = last.lookup(&amp;key);
if (tsp != NULL) {
delta = bpf_ktime_get_ns() - *tsp;
if (delta &lt; 1000000000) {
// 时间小于1秒则输出
bpf_trace_printk(&quot;%d\\n&quot;, delta / 1000000);
}
last.delete(&amp;key);
}
// 更新存储的时间戳
ts = bpf_ktime_get_ns();
last.update(&amp;key, &amp;ts);
return 0;
}
&quot;&quot;&quot;)
b.attach_kprobe(event=b.get_syscall_fnname(&quot;sync&quot;), fn_name=&quot;do_trace&quot;)
print(&quot;跟踪快速同步... 按Ctrl-C结束&quot;)
# 格式化输出
start = 0
while 1:
(task, pid, cpu, flags, ts, ms) = b.trace_fields()
if start == 0:
start = ts
ts = ts - start
print(&quot;在时间%.2f秒处:检测到多个同步,上次发生在%s毫秒前&quot; % (ts, ms))
</code></pre>
<p>学习内容:</p>
<ol>
<li><code>bpf_ktime_get_ns()</code>: 返回时间,单位为纳秒。</li>
<li><code>BPF_HASH(last)</code>: 创建一个BPF映射对象类型为哈希关联数组名为&quot;last&quot;。我们没有指定其他参数因此默认的键和值类型为u64。</li>
<li><code>key = 0</code>: 我们只会在哈希中存储一个键值对,其中键被硬编码为零。</li>
<li><code>last.lookup(&amp;key)</code>: 在哈希中查找键并如果存在则返回其值的指针否则返回NULL。我们将键作为指针的地址传递给该函数。</li>
<li><code>if (tsp != NULL) {</code>: 验证器要求在将从映射查找得到的指针值解引用使用之前必须先检查其是否为null。1. <code>last.delete(&amp;key)</code>: 从哈希表中删除key。目前需要这样做是因为<a href="https://git.kernel.org/cgit/linux/kernel/git/davem/net.git/commit/?id=a6ed3ea65d9868fdf9eff84e6fe4f666b8d14b02"><code>.update()</code>中存在一个内核错误</a>在4.8.10中已经修复)。</li>
<li><code>last.update(&amp;key, &amp;ts)</code>: 将第二个参数的值与key关联起来覆盖之前的任何值。这会记录时间戳。</li>
</ol>
<h3 id="第5课-sync_countpy"><a class="header" href="#第5课-sync_countpy">第5课. sync_count.py</a></h3>
<p>修改sync_timing.py程序前一课以存储所有内核同步系统调用包括快速和慢速的计数并将其与输出一起打印出来。可以通过向现有哈希表添加一个新的键索引来在BPF程序中记录此计数。</p>
<h3 id="第6课-disksnooppy"><a class="header" href="#第6课-disksnooppy">第6课. disksnoop.py</a></h3>
<p>浏览<a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/disksnoop.py">examples/tracing/disksnoop.py</a>程序以了解新内容。以下是一些示例输出:</p>
<pre><code class="language-sh"># disksnoop.py
时间(s) T 字节 延迟(ms)
16458043.436012 W 4096 3.13
16458043.437326 W 4096 4.44
16458044.126545 R 4096 42.82
16458044.129872 R 4096 3.24
[...]
</code></pre>
<p>以及代码片段:</p>
<pre><code class="language-Python">[...]
REQ_WRITE = 1 # 来自include/linux/blk_types.h
# 加载BPF程序
b = BPF(text=&quot;&quot;&quot;
#include &lt;uapi/linux/ptrace.h&gt;
#include &lt;linux/blk-mq.h&gt;
BPF_HASH(start, struct request *);
void trace_start(struct pt_regs *ctx, struct request *req) {
// 使用请求指针存储开始时间戳
u64 ts = bpf_ktime_get_ns();
start.update(&amp;req, &amp;ts);
}
void trace_completion(struct pt_regs *ctx, struct request *req) {
u64 *tsp, delta;
tsp = start.lookup(&amp;req);
if (tsp != 0) {
delta = bpf_ktime_get_ns() - *tsp;
bpf_trace_printk(&quot;%d %x %d\\n&quot;, req-&gt;__data_len,
req-&gt;cmd_flags, delta / 1000);
start.delete(&amp;req);
}
}
&quot;&quot;&quot;)
if BPF.get_kprobe_functions(b'blk_start_request'):
b.attach_kprobe(event=&quot;blk_start_request&quot;, fn_name=&quot;trace_start&quot;)
b.attach_kprobe(event=&quot;blk_mq_start_request&quot;, fn_name=&quot;trace_start&quot;)
if BPF.get_kprobe_functions(b'__blk_account_io_done'):
b.attach_kprobe(event=&quot;__blk_account_io_done&quot;, fn_name=&quot;trace_completion&quot;) else: b.attach_kprobe(event=&quot;blk_account_io_done&quot;, fn_name=&quot;trace_completion&quot;)
[...]
</code></pre>
<p>学习内容:</p>
<ol>
<li><code>REQ_WRITE</code>: 我们在Python程序中定义了一个内核常量因为我们后面会在Python程序中使用它。如果我们在BPF程序中使用REQ_WRITE它应该可以正常工作无需定义只需使用适当的<code>#includes</code></li>
<li><code>trace_start(struct pt_regs *ctx, struct request*req)</code>: 这个函数将在后面附加到kprobe上。kprobe函数的参数是<code>struct pt_regs *ctx</code>用于寄存器和BPF上下文然后是函数的实际参数。我们将把它附加到blk_start_request()上,其中第一个参数是<code>struct request*</code></li>
<li><code>start.update(&amp;req, &amp;ts)</code>: 我们使用请求结构的指针作为哈希中的键。这在跟踪中很常见。结构体指针是非常好的键因为它们是唯一的两个结构体不能具有相同的指针地址。只需小心何时释放和重用指针。所以我们实际上是给描述磁盘I/O的请求结构体打上我们自己的时间戳以便我们可以计时。存储时间戳常用的两个键是结构体指针和线程ID用于记录函数入口到返回的时间</li>
<li><code>req-&gt;__data_len</code>: 我们在解引用<code>struct request</code>的成员。请参阅内核源代码中对其定义的部分以获得有关哪些成员可用的信息。bcc实际上会将这些表达式重写为一系列<code>bpf_probe_read_kernel()</code>调用。有时bcc无法处理复杂的解引用此时您需要直接调用<code>bpf_probe_read_kernel()</code></li>
</ol>
<p>这是一个非常有趣的程序,如果您能理解所有的代码,您就会理解很多重要的基础知识。我们仍然在使用<code>bpf_trace_printk()</code>的技巧,我们下一步要解决这个问题。</p>
<h3 id="lesson-7-hello_perf_outputpy"><a class="header" href="#lesson-7-hello_perf_outputpy">Lesson 7. hello_perf_output.py</a></h3>
<p>让我们最终停止使用bpf_trace_printk()并使用适当的BPF_PERF_OUTPUT()接口。这也意味着我们将停止获取免费的trace_field()成员如PID和时间戳并且需要直接获取它们。在另一个会话中运行命令时的示例输出</p>
<pre><code class="language-sh"># hello_perf_output.py
TIME(s) COMM PID MESSAGE
0.000000000 bash 22986 你好perf_output
0.021080275 systemd-udevd 484 你好perf_output
0.021359520 systemd-udevd 484 你好perf_output
0.021590610 systemd-udevd 484 你好perf_output
[...]
</code></pre>
<p>代码位于<a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/hello_perf_output.py">examples/tracing/hello_perf_output.py</a></p>
<pre><code class="language-Python">from bcc import BPF
// 定义BPF程序
prog = &quot;&quot;&quot;
#include &lt;linux/sched.h&gt;
// 在C中定义输出数据结构
struct data_t {
u32 pid;
u64 ts;
char comm[TASK_COMM_LEN];
};
BPF_PERF_OUTPUT(events);
int hello(struct pt_regs *ctx) {
struct data_t data = {};
data.pid = bpf_get_current_pid_tgid();
data.ts = bpf_ktime_get_ns();
bpf_get_current_comm(&amp;data.comm, sizeof(data.comm));
events.perf_submit(ctx, &amp;data, sizeof(data));
return 0;
}
&quot;&quot;&quot;
// 加载BPF程序
b = BPF(text=prog)
b.attach_kprobe(event=b.get_syscall_fnname(&quot;clone&quot;), fn_name=&quot;hello&quot;)
//标题
print(&quot;%-18s %-16s %-6s %s&quot; % (&quot;TIME(s)&quot;, &quot;COMM&quot;, &quot;PID&quot;, &quot;MESSAGE&quot;))
//处理事件
start = 0
def print_event(cpu, data, size):
global start
event = b[&quot;events&quot;].event(data)
if start == 0:
start = event.ts
time_s = (float(event.ts - start)) / 1000000000
print(&quot;%-18.9f %-16s %-6d %s&quot; % (time_s, event.comm, event.pid, &quot;你好perf_output&quot;))
//循环并回调print_event
b[&quot;events&quot;].open_perf_buffer(print_event)
while 1:
b.perf_buffer_poll()
</code></pre>
<p>学习的内容:</p>
<ol>
<li><code>struct data_t</code>: 这定义了一个C结构体我们将用它来从内核传递数据到用户空间。1. <code>BPF_PERF_OUTPUT(events)</code>: 这里给我们的输出通道命名为&quot;events&quot;</li>
<li><code>struct data_t data = {};</code>: 创建一个空的<code>data_t</code>结构体,我们将在之后填充它。</li>
<li><code>bpf_get_current_pid_tgid()</code>: 返回低32位的进程ID内核视图中的PID用户空间中通常被表示为线程ID以及高32位的线程组ID用户空间通常认为是PID。通过直接将其设置为<code>u32</code>我们丢弃了高32位。应该显示PID还是TGID对于多线程应用程序TGID将是相同的所以如果你想要区分它们你需要PID。这也是对最终用户期望的一个问题。</li>
<li><code>bpf_get_current_comm()</code>: 将当前进程的名称填充到第一个参数的地址中。</li>
<li><code>events.perf_submit()</code>: 通过perf环形缓冲区将事件提交给用户空间以供读取。</li>
<li><code>def print_event()</code>: 定义一个Python函数来处理从<code>events</code>流中读取的事件。</li>
<li><code>b[&quot;events&quot;].event(data)</code>: 现在将事件作为一个Python对象获取该对象是根据C声明自动生成的。</li>
<li><code>b[&quot;events&quot;].open_perf_buffer(print_event)</code>: 将Python的<code>print_event</code>函数与<code>events</code>流关联起来。</li>
<li><code>while 1: b.perf_buffer_poll()</code>: 阻塞等待事件。</li>
</ol>
<h3 id="第八课-sync_perf_outputpy"><a class="header" href="#第八课-sync_perf_outputpy">第八课。 sync_perf_output.py</a></h3>
<p>重写之前的课程中的sync_timing.py使用<code>BPF_PERF_OUTPUT</code></p>
<h3 id="第九课-bitehistpy"><a class="header" href="#第九课-bitehistpy">第九课。 bitehist.py</a></h3>
<p>以下工具记录了磁盘I/O大小的直方图。样本输出</p>
<pre><code class="language-sh"># bitehist.py
跟踪中... 按Ctrl-C结束。
^C
kbytes : count distribution
0 -&gt; 1 : 3 | |
2 -&gt; 3 : 0 | |
4 -&gt; 7 : 211 |********** |
8 -&gt; 15 : 0 | |
16 -&gt; 31 : 0 | |&quot;.32 -&gt; 63 : 0 | |
64 -&gt; 127 : 1 | |
128 -&gt; 255 : 800 |**************************************|
</code></pre>
<p>代码在<a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/bitehist.py">examples/tracing/bitehist.py</a>:</p>
<pre><code class="language-Python">from __future__ import print_function
from bcc import BPF
from time import sleep
# 加载BPF程序
b = BPF(text=&quot;&quot;&quot;
#include &lt;uapi/linux/ptrace.h&gt;
#include &lt;linux/blkdev.h&gt;
BPF_HISTOGRAM(dist);
int kprobe__blk_account_io_done(struct pt_regs *ctx, struct request *req)
{
dist.increment(bpf_log2l(req-&gt;__data_len / 1024));
return 0;
}
&quot;&quot;&quot;)
# 头部
print(&quot;跟踪中... 按Ctrl-C结束.&quot;)
# 跟踪直到按下Ctrl-C
try:
sleep(99999999)
except KeyboardInterrupt:
print()
# 输出
b[&quot;dist&quot;].print_log2_hist(&quot;kbytes&quot;)
</code></pre>
<p>之前课程的总结:</p>
<ul>
<li><code>kprobe__</code>: 这个前缀意味着其余部分将被视为一个将使用kprobe进行插桩的内核函数名。</li>
<li><code>struct pt_regs *ctx, struct request*req</code>: kprobe的参数。<code>ctx</code> 是寄存器和BPF上下文<code>req</code> 是被插桩函数 <code>blk_account_io_done()</code> 的第一个参数。</li>
<li><code>req-&gt;__data_len</code>: 解引用该成员。</li>
</ul>
<p>新知识:</p>
<ol>
<li><code>BPF_HISTOGRAM(dist)</code>: 定义了一个名为 &quot;dist&quot; 的BPF映射对象它是一个直方图。</li>
<li><code>dist.increment()</code>: 默认情况下将第一个参数提供的直方图桶索引加1。也可以作为第二个参数传递自定义的增量。</li>
<li><code>bpf_log2l()</code>: 返回所提供值的对数值。这将成为我们直方图的索引这样我们构建了一个以2为底的幂直方图。</li>
<li><code>b[&quot;dist&quot;].print_log2_hist(&quot;kbytes&quot;)</code>: 以2为底的幂形式打印 &quot;dist&quot; 直方图,列标题为 &quot;kbytes&quot;。这样只有桶计数从内核传输到用户空间,因此效率高。</li>
</ol>
<h3 id="lesson-10-disklatencypy-lesson-11-vfsreadlatpy"><a class="header" href="#lesson-10-disklatencypy-lesson-11-vfsreadlatpy">Lesson 10. disklatency.py”。#### Lesson 11. vfsreadlat.py</a></h3>
<p>这个例子分为独立的Python和C文件。示例输出</p>
<pre><code class="language-sh"># vfsreadlat.py 1
跟踪中... 按Ctrl-C停止。
微秒 : 数量 分布
0 -&gt; 1 : 0 | |
2 -&gt; 3 : 2 |*********** |
4 -&gt; 7 : 7 |****************************************|
8 -&gt; 15 : 4 |********************** |
微秒 : 数量 分布
0 -&gt; 1 : 29 |****************************************|
2 -&gt; 3 : 28 |************************************** |
4 -&gt; 7 : 4 |***** |
8 -&gt; 15 : 8 |*********** |
16 -&gt; 31 : 0 | |
32 -&gt; 63 : 0 | |
64 -&gt; 127 : 0 | |
128 -&gt; 255 : 0 | |
256 -&gt; 511 : 2 |** |
512 -&gt; 1023 : 0 | |
1024 -&gt; 2047 : 0 | |
2048 -&gt; 4095 : 0 | |
4096 -&gt; 8191 : 4 |***** |
8192 -&gt; 16383 : 6 |******** |
16384 -&gt; 32767 : 9 |************ |```.32768 -&gt; 65535 : 6 |******** |
65536 -&gt; 131071 : 2 |** |
usecs : count distribution
0 -&gt; 1 : 11 |****************************************|
2 -&gt; 3 : 2 |******* |
4 -&gt; 7 : 10 |************************************ |
8 -&gt; 15 : 8 |***************************** |
16 -&gt; 31 : 1 |*** |
32 -&gt; 63 : 2 |******* |
[...]
</code></pre>
<p>浏览 <a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/vfsreadlat.py">examples/tracing/vfsreadlat.py</a><a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/vfsreadlat.c">examples/tracing/vfsreadlat.c</a> 中的代码。</p>
<p>学习的内容:</p>
<ol>
<li><code>b = BPF(src_file = &quot;vfsreadlat.c&quot;)</code>: 从单独的源代码文件中读取 BPF C 程序。</li>
<li><code>b.attach_kretprobe(event=&quot;vfs_read&quot;, fn_name=&quot;do_return&quot;)</code>: 将 BPF C 函数 <code>do_return()</code> 链接到内核函数 <code>vfs_read()</code> 的返回值上。这是一个 kretprobe用于检测函数返回值而不是函数的入口。</li>
<li><code>b[&quot;dist&quot;].clear()</code>: 清除直方图。</li>
</ol>
<h3 id="lesson-12-urandomreadpy"><a class="header" href="#lesson-12-urandomreadpy">Lesson 12. urandomread.py</a></h3>
<p>当运行 <code>dd if=/dev/urandom of=/dev/null bs=8k count=5</code> 时进行跟踪:</p>
<pre><code class="language-sh"># urandomread.py
TIME(s) COMM PID GOTBITS
24652832.956994001 smtp 24690 384
24652837.726500999 dd 24692 65536
24652837.727111001 dd 24692 65536
24652837.727703001 dd 24692 65536
24652837.728294998 dd 24692 65536
24652837.728888001 dd 24692 65536
</code></pre>
<p>哈!我意外地捕捉到了 smtp。代码在 <a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/urandomread.py">examples/tracing/urandomread.py</a> 中:</p>
<pre><code class="language-Python">from __future__ import print_function&quot;.```python
from bcc import BPF
# 加载BPF程序
b = BPF(text=&quot;&quot;&quot;
TRACEPOINT_PROBE(random, urandom_read) {
// args is from /sys/kernel/debug/tracing/events/random/urandom_read/format
bpf_trace_printk(&quot;%d\\n&quot;, args-&gt;got_bits);
return 0;
}
&quot;&quot;&quot;)
# header
print(&quot;%-18s %-16s %-6s %s&quot; % (&quot;TIME(s)&quot;, &quot;COMM&quot;, &quot;PID&quot;, &quot;GOTBITS&quot;))
# format output
while 1:
try:
(task, pid, cpu, flags, ts, msg) = b.trace_fields()
except ValueError:
continue
print(&quot;%-18.9f %-16s %-6d %s&quot; % (ts, task, pid, msg))
</code></pre>
<p>要学到的东西:</p>
<ol>
<li><code>TRACEPOINT_PROBE(random, urandom_read)</code>: 对内核跟踪点 <code>random:urandom_read</code> 进行注入。这些具有稳定的API因此在可能的情况下建议使用它们来代替kprobe。您可以运行 <code>perf list</code> 来获取跟踪点列表。至少需要 Linux 版本 4.7 来将 BPF 程序附加到跟踪点上。</li>
<li><code>args-&gt;got_bits</code>: <code>args</code> 是自动填充的跟踪点参数结构。上面的注释指出了可以查看这个结构的位置。例如:</li>
</ol>
<pre><code class="language-sh"># cat /sys/kernel/debug/tracing/events/random/urandom_read/format
name: urandom_read
ID: 972
format:
field:unsigned short common_type; offset:0; size:2; signed:0;
field:unsigned char common_flags; offset:2; size:1; signed:0;
field:unsigned char common_preempt_count; offset:3; size:1; signed:0;
field:int common_pid; offset:4; size:4; signed:1;
field:int got_bits; offset:8; size:4; signed:1;
field:int pool_left; offset:12; size:4; signed:1;
field:int input_left; offset:16; size:4; signed:1;
print fmt: &quot;got_bits %d nonblocking_pool_entropy_left %d input_entropy_left %d&quot;, REC-&gt;got_bits, REC-&gt;pool_left, REC-&gt;input_left
</code></pre>
<p>在这种情况下,我们正在打印 <code>got_bits</code> 成员。</p>
<h3 id="第13课-disksnooppy已修复"><a class="header" href="#第13课-disksnooppy已修复">第13课. disksnoop.py已修复</a></h3>
<p>将上一课的 disksnoop.py 修改为使用 <code>block:block_rq_issue</code><code>block:block_rq_complete</code> 跟踪点。</p>
<h3 id="第14课-strlen_countpy"><a class="header" href="#第14课-strlen_countpy">第14课. strlen_count.py.</a></h3>
<p>这个程序对用户级函数进行插桩,其中包括 <code>strlen()</code> 库函数,并对其字符串参数进行频率统计。例如输出</p>
<pre><code class="language-sh"># strlen_count.py
跟踪 strlen()... 按 Ctrl-C 结束。
^C 数量 字符串
1 &quot; &quot;
1 &quot;/bin/ls&quot;
1 &quot;.&quot;
1 &quot;cpudist.py.1&quot;
1 &quot;.bashrc&quot;
1 &quot;ls --color=auto&quot;
1 &quot;key_t&quot;
[...]
10 &quot;a7:~# &quot;
10 &quot;/root&quot;
12 &quot;LC_ALL&quot;
12 &quot;en_US.UTF-8&quot;
13 &quot;en_US.UTF-8&quot;
20 &quot;~&quot;
70 &quot;#%^,~:-=?+/}&quot;
340 &quot;\x01\x1b]0;root@bgregg-test: ~\x07\x02root@bgregg-test:~# &quot;
</code></pre>
<p>这些是在跟踪时由此库函数处理的各种字符串以及它们的频率计数。例如,&quot;LC_ALL&quot; 被调用了12次。</p>
<p>代码在 <a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/strlen_count.py">examples/tracing/strlen_count.py</a> 中:</p>
<pre><code class="language-Python">from __future__ import print_function
from bcc import BPF
from time import sleep
# 载入 BPF 程序
b = BPF(text=&quot;&quot;&quot;
#include &lt;uapi/linux/ptrace.h&gt;
struct key_t {
char c[80];
};
BPF_HASH(counts, struct key_t);
int count(struct pt_regs *ctx) {
if (!PT_REGS_PARM1(ctx))
return 0;
struct key_t key = {};
u64 zero = 0, *val;
bpf_probe_read_user(&amp;key.c, sizeof(key.c), (void *)PT_REGS_PARM1(ctx));
// 也可以使用 `counts.increment(key)`
val = counts.lookup_or_try_init(&amp;key, &amp;zero);
if (val) {
(*val)++;
}
return 0;
};
&quot;&quot;&quot;)
b.attach_uprobe(name=&quot;c&quot;, sym=&quot;strlen&quot;, fn_name=&quot;count&quot;)
# 头部
print(&quot;跟踪 strlen()... 按 Ctrl-C 结束。&quot;)
# 睡眠直到按下 Ctrl-C
try:
sleep(99999999)
except KeyboardInterrupt:
pass
# 打印输出
print(&quot;%10s %s&quot; % (&quot;数量&quot;, &quot;字符串&quot;))
counts = b.get_table(&quot;counts&quot;)
for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
print(&quot;%10d \&quot;%s\&quot;&quot; % (v.value, k.c.encode('string-escape')))
</code></pre>
<p>要学习的内容1. <code>PT_REGS_PARM1(ctx)</code>: 这个参数会获取传递给 <code>strlen()</code> 的第一个参数,也就是字符串。</p>
<ol>
<li><code>b.attach_uprobe(name=&quot;c&quot;, sym=&quot;strlen&quot;, fn_name=&quot;count&quot;)</code>: 附加到库 &quot;c&quot;(如果这是主程序,则使用其路径名),对用户级函数 <code>strlen()</code> 进行插装,并在执行时调用我们的 C 函数 <code>count()</code></li>
</ol>
<h3 id="第15课nodejs_http_serverpy"><a class="header" href="#第15课nodejs_http_serverpy">第15课。nodejs_http_server.py</a></h3>
<p>本程序会对用户静态定义的跟踪 (USDT) 探测点进行插装,这是内核跟踪点的用户级版本。示例输出:</p>
<pre><code class="language-sh"># nodejs_http_server.py 24728
TIME(s) COMM PID ARGS
24653324.561322998 node 24728 path:/index.html
24653335.343401998 node 24728 path:/images/welcome.png
24653340.510164998 node 24728 path:/images/favicon.png
</code></pre>
<p>来自 <a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/nodejs_http_server.py">examples/tracing/nodejs_http_server.py</a> 的相关代码:</p>
<pre><code class="language-Python">from __future__ import print_function
from bcc import BPF, USDT
import sys
if len(sys.argv) &lt; 2:
print(&quot;USAGE: nodejs_http_server PID&quot;)
exit()
pid = sys.argv[1]
debug = 0
# load BPF program
bpf_text = &quot;&quot;&quot;
#include &lt;uapi/linux/ptrace.h&gt;
int do_trace(struct pt_regs *ctx) {
uint64_t addr;
char path[128]={0};
bpf_usdt_readarg(6, ctx, &amp;addr);
bpf_probe_read_user(&amp;path, sizeof(path), (void *)addr);
bpf_trace_printk(&quot;path:%s\\n&quot;, path);
return 0;
};
&quot;&quot;&quot;
# enable USDT probe from given PID
u = USDT(pid=int(pid))
u.enable_probe(probe=&quot;http__server__request&quot;, fn_name=&quot;do_trace&quot;)
if debug:
print(u.get_text())
print(bpf_text)
# initialize BPF
b = BPF(text=bpf_text, usdt_contexts=[u])
</code></pre>
<p>学习内容:</p>
<ol>
<li><code>bpf_usdt_readarg(6, ctx, &amp;addr)</code>: 从 USDT 探测点中读取参数 6 的地址到 <code>addr</code></li>
<li><code>bpf_probe_read_user(&amp;path, sizeof(path), (void *)addr)</code>: 现在字符串 <code>addr</code> 指向我们的 <code>path</code> 变量。</li>
<li><code>u = USDT(pid=int(pid))</code>: 为给定的 PID 初始化 USDT 跟踪。1. <code>u.enable_probe(probe=&quot;http__server__request&quot;, fn_name=&quot;do_trace&quot;)</code>: 将我们的 <code>do_trace()</code> BPF C 函数附加到 Node.js 的 <code>http__server__request</code> USDT 探针。</li>
<li><code>b = BPF(text=bpf_text, usdt_contexts=[u])</code>: 需要将我们的 USDT 对象 <code>u</code> 传递给 BPF 对象的创建。</li>
</ol>
<h3 id="第16课-task_switchc"><a class="header" href="#第16课-task_switchc">第16课. task_switch.c</a></h3>
<p>这是一个早期的教程,作为额外的课程包含其中。用它来复习和加深你已经学到的内容。</p>
<p>这是一个比 Hello World 更复杂的示例程序。该程序将在内核中每次任务切换时被调用,并在一个 BPF 映射中记录新旧进程的 pid。</p>
<p>下面的 C 程序引入了一个新的概念prev 参数。BCC 前端会特殊处理这个参数,从而使得对这个变量的访问从由 kprobe 基础设施传递的保存上下文中进行读取。从位置1开始的参数的原型应该与被 kprobed 的内核函数的原型匹配。如果这样做,程序就可以无缝访问函数参数。</p>
<pre><code class="language-c">#include &lt;uapi/linux/ptrace.h&gt;
#include &lt;linux/sched.h&gt;
struct key_t {
u32 prev_pid;
u32 curr_pid;
};
BPF_HASH(stats, struct key_t, u64, 1024);
int count_sched(struct pt_regs *ctx, struct task_struct *prev) {
struct key_t key = {};
u64 zero = 0, *val;
key.curr_pid = bpf_get_current_pid_tgid();
key.prev_pid = prev-&gt;pid;
// could also use `stats.increment(key);`
val = stats.lookup_or_try_init(&amp;key, &amp;zero);
if (val) {
(*val)++;
}
return 0;
}
</code></pre>
<p>用户空间组件加载上面显示的文件,并将其附加到 <code>finish_task_switch</code> 内核函数上。
BPF 对象的 <code>[]</code> 运算符允许访问程序中的每个 BPF_HASH允许对内核中的值进行通行访问。可以像使用任何其他 python dict 对象一样使用该对象:读取、更新和删除操作都是允许的。</p>
<pre><code class="language-python">from bcc import BPF
from time import sleep
b = BPF(src_file=&quot;task_switch.c&quot;)&quot;.```markdown
```Chinese
b.attach_kprobe(event=&quot;finish_task_switch&quot;, fn_name=&quot;count_sched&quot;)
# 生成多个调度事件
for i in range(0, 100): sleep(0.01)
for k, v in b[&quot;stats&quot;].items():
print(&quot;task_switch[%5d-&gt;%5d]=%u&quot; % (k.prev_pid, k.curr_pid, v.value))
</code></pre>
<p>这些程序可以在文件 <a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/task_switch.c">examples/tracing/task_switch.c</a><a href="https://github.com/iovisor/bcc/tree/master/examples/tracing/task_switch.py">examples/tracing/task_switch.py</a> 中找到。</p>
<h3 id="第17课-进一步研究"><a class="header" href="#第17课-进一步研究">第17课. 进一步研究</a></h3>
<p>要进行进一步研究,请参阅 Sasha Goldshtein 的 <a href="https://github.com/goldshtn/linux-tracing-workshop">linux-tracing-workshop</a>其中包含了额外的实验。bcc/tools 中还有许多工具可供研究。</p>
<p>如果您希望为 bcc 贡献工具,请阅读 <a href="https://github.com/iovisor/bcc/tree/master/CONTRIBUTING-SCRIPTS.md">CONTRIBUTING-SCRIPTS.md</a>。在主要的 <a href="https://github.com/iovisor/bcc/tree/master/README.md">README.md</a> 的底部,您还会找到与我们联系的方法。祝您好运,祝您成功追踪!</p>
<h2 id="网络"><a class="header" href="#网络">网络</a></h2>
<p>TODO</p>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../bcc-documents/tutorial.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="../bcc-documents/tutorial.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="../elasticlunr.min.js"></script>
<script src="../mark.min.js"></script>
<script src="../searcher.js"></script>
<script src="../clipboard.min.js"></script>
<script src="../highlight.js"></script>
<script src="../book.js"></script>
<!-- Custom JS scripts -->
</div>
</body>
</html>