examples: Add local storage examples
authorHengqi Chen <chenhengqi@outlook.com>
Tue, 4 Jan 2022 16:02:49 +0000 (00:02 +0800)
committeryonghong-song <ys114321@gmail.com>
Wed, 5 Jan 2022 06:43:40 +0000 (22:43 -0800)
Add examples to demostrate BPF_{INODE, TASK}_STORAGE usage.

$ sudo ./task_storage.py
b'              nc-668442  [000] d..21 1221279.139354: bpf_trace_printk: inet_listen entry: store timestamp 1221271907116757'
b'              nc-668442  [000] d..21 1221279.139375: bpf_trace_printk: inet_listen exit: cost 26us'

Signed-off-by: Hengqi Chen <chenhengqi@outlook.com>
examples/local_storage/inode_storage.py [new file with mode: 0755]
examples/local_storage/task_storage.py [new file with mode: 0755]

diff --git a/examples/local_storage/inode_storage.py b/examples/local_storage/inode_storage.py
new file mode 100755 (executable)
index 0000000..fcc58c5
--- /dev/null
@@ -0,0 +1,28 @@
+#!/usr/bin/python3
+
+from bcc import BPF
+
+source = r"""
+#include <linux/fs.h>
+
+BPF_INODE_STORAGE(inode_storage_map, int);
+
+LSM_PROBE(inode_rename, struct inode *old_dir, struct dentry *old_dentry,
+         struct inode *new_dir, struct dentry *new_dentry, unsigned int flags)
+{
+       int *value;
+
+       value = inode_storage_map.inode_storage_get(old_dentry->d_inode, 0, BPF_LOCAL_STORAGE_GET_F_CREATE);
+       if (!value)
+               return 0;
+
+       bpf_trace_printk("%d", *value);
+       return 0;
+}
+"""
+
+b = BPF(text=source)
+try:
+    b.trace_print()
+except KeyboardInterrupt:
+    pass
diff --git a/examples/local_storage/task_storage.py b/examples/local_storage/task_storage.py
new file mode 100755 (executable)
index 0000000..ee9e9b7
--- /dev/null
@@ -0,0 +1,41 @@
+#!/usr/bin/python3
+
+from bcc import BPF
+
+source = r"""
+BPF_TASK_STORAGE(task_storage_map, __u64);
+
+KFUNC_PROBE(inet_listen)
+{
+       __u64 ts = bpf_ktime_get_ns();
+
+       /* save timestamp to local storage on function entry */
+       task_storage_map.task_storage_get(bpf_get_current_task_btf(), &ts, BPF_LOCAL_STORAGE_GET_F_CREATE);
+
+       bpf_trace_printk("inet_listen entry: store timestamp %lld", ts);
+       return 0;
+}
+
+KRETFUNC_PROBE(inet_listen)
+{
+       __u64 *ts;
+
+       /* retrieve timestamp stored at local storage on function exit */
+       ts = task_storage_map.task_storage_get(bpf_get_current_task_btf(), 0, 0);
+       if (!ts)
+               return 0;
+
+       /* delete timestamp from local storage */
+       task_storage_map.task_storage_delete(bpf_get_current_task_btf());
+
+       /* calculate latency */
+       bpf_trace_printk("inet_listen exit: cost %lldus", (bpf_ktime_get_ns() - *ts) / 1000);
+       return 0;
+}
+"""
+
+b = BPF(text=source)
+try:
+    b.trace_print()
+except KeyboardInterrupt:
+    pass