【问题标题】:python interaction with BPF mapspython 与 BPF 映射的交互
【发布时间】:2020-04-23 17:07:56
【问题描述】:

我想知道是否有一个易于从 python 用户空间初始化 BPF 映射。对于我的项目,我将为每个进程提供一个看起来很吓人的 NxN 2d 浮点数组。为简单起见,让我们假设 N 在进程中是恒定的(比如 5)。为了实现对这些数据的内核支持,我可以这样做:

b = BPF(text = """
    typedef struct
    {
        float transMat[5][5];
    } trans_struct;



    BPF_HASH(trans_mapping, char[16], trans_struct);

    .....
""")

我想知道是否有一种简单的方法可以从 python 初始化这个地图。比如:

for ele in someDictionary:
    #asume someDitionary has mapping (comm -> 5x5 float matrix)
    b["trans_mapping"].insert(ele, someDictionary[ele])

我想我困惑的症结在于——1) 用户可以使用所有 map 方法,2) 从 python 对象到 c 结构时,我们如何确保类型一致

【问题讨论】:

  • 使用密件抄送时,您可以通过写入 BPF 映射来写入映射,就像写入常规 Python 数据结构一样。不过,我不确定类型部分; BPF 对浮点数(不允许浮点运算)或 128 位整数没有任何特定的支持。您可以找到从 Python here 编写的 BPF 映射示例。
  • 感谢您的输入,也很抱歉键上的混淆——它应该是 char[16],因为这是 comm 的结构。我不知道为什么我放了u128。关于浮点算术,对于我的示例,所有值都是权重(在 [0,1] 范围内),因此我可以将数字视为 X / 10^d,并简单地对 X 进行算术运算。那个链接是什么我需要——谢谢!

标签: python maps trace bpf bcc-bpf


【解决方案1】:

基于 pchaigno 评论的解决方案 -- 需要注意的关键事项是使用 c_types 来确保跨环境的类型一致性,并通过索引 BPF 程序对象来提取表。由于我们能够通过索引获取地图,get_table() 函数现在被认为是过时的。这种格式提供了从 python 前端将数据加载到地图中的结构,但并不完全符合我的问题的具体情况。

from time import sleep, strftime
from bcc import BPF
from bcc.utils import printb
from bcc.syscall import syscall_name, syscalls
from ctypes import *


    b = BPF(text = """

    BPF_HASH(start, u32, u64);


    TRACEPOINT_PROBE(raw_syscalls, sys_exit)
    {
        u32 syscall_id = args->id;
        u32 key = 1;
        u64 *val;
        u32 uid = bpf_get_current_uid_gid();

        if (uid == 0)
        {
            val = start.lookup(&key); //find value associated with key 1
            if (val)
                bpf_trace_printk("Hello world, I have value %d!\\n", *val);

        }
        return 0;
    }
    """)

    thisStart = b["start"]
    thisStart[c_int(1)] = c_int(9) #insert key-value part 1->9


    while 1:
        try:
            (task, pid, cpu, flags, ts, msg) = b.trace_fields()
        except KeyboardInterrupt:
            print("Detaching")
            exit()
        print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多