当前位置:网站首页>Dragon lizard community open source coolbpf, BPF program development efficiency increased 100 times
Dragon lizard community open source coolbpf, BPF program development efficiency increased 100 times
2022-07-01 13:37:00 【InfoQ】
introduction
- System fault diagnosis : It can dynamically insert piles to perspective the core .
- Network performance optimization : It can modify and forward the received and sent network packets .
- System security : It can monitor the opening and closing of files to make security decisions .
- Performance monitoring : It can see how long the function takes to know the performance bottleneck .
One 、BPF Comparison of development methods
1、 Original stage
static struct sock_filter filter[6] = {
{ OP_LDH, 0, 0, 12 }, // ldh [12]
{ OP_JEQ, 0, 2, ETH_P_IP }, // jeq #0x800, L2, L5
{ OP_LDB, 0, 0, 23 }, // ldb [23]
{ OP_JEQ, 0, 1, IPPROTO_TCP }, // jeq #0x6, L4, L5
{ OP_RET, 0, 0, 0 }, // ret #0x0
{ OP_RET, 0, 0, -1, }, // ret #0xffffffff
};
int main(int argc, char **argv)
{
…
struct sock_fprog prog = { 6, filter };
…
sock = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
…
if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_FILTER, &prog, sizeof(prog))) {
return 1;
}
…
}
2、 Conservative stage
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__type(key, u32);
__type(value, long);
__uint(max_entries, 256);
} my_map SEC(".maps");
SEC("socket1")
int bpf_prog1(struct __sk_buff *skb)
{
int index = load_byte(skb, ETH_HLEN + offsetof(struct iphdr, protocol));
long *value;
if (skb->pkt_type != PACKET_OUTGOING)
return 0;
value = bpf_map_lookup_elem(&my_map, &index);
if (value)
__sync_fetch_and_add(value, skb->len);
return 0;
}
char _license[] SEC("license") = "GPL";
int main(int ac, char **argv)
{
struct bpf_object *obj;
struct bpf_program *prog;
int map_fd, prog_fd;
char filename[256];
int i, sock, err;
FILE *f;
snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
obj = bpf_object__open_file(filename, NULL);
if (libbpf_get_error(obj))
return 1;
prog = bpf_object__next_program(obj, NULL);
bpf_program__set_type(prog, BPF_PROG_TYPE_SOCKET_FILTER);
err = bpf_object__load(obj);
if (err)
return 1;
prog_fd = bpf_program__fd(prog);
map_fd = bpf_object__find_map_fd_by_name(obj, "my_map");
...
}
3、BCC Initial stage
int trace_connect_v4_entry(struct pt_regs *ctx, struct sock *sk)
{
if (container_should_be_filtered()) {
return 0;
}
u64 pid = bpf_get_current_pid_tgid();
##FILTER_PID##
u16 family = sk->__sk_common.skc_family;
##FILTER_FAMILY##
// stash the sock ptr for lookup on return
connectsock.update(&pid, &sk);
return 0;
}
# initialize BPF
b = BPF(text=bpf_text)
if args.ipv4:
b.attach_kprobe(event="tcp_v4_connect", fn_name="trace_connect_v4_entry")
b.attach_kretprobe(event="tcp_v4_connect", fn_name="trace_connect_v4_return")
b.attach_kprobe(event="tcp_close", fn_name="trace_close_entry")
b.attach_kretprobe(event="inet_csk_accept", fn_name="trace_accept_return")
4、BCC Advanced stage
SEC("kprobe/inet_listen")
int BPF_KPROBE(inet_listen_entry, struct socket *sock, int backlog)
{
__u64 pid_tgid = bpf_get_current_pid_tgid();
__u32 pid = pid_tgid >> 32;
__u32 tid = (__u32)pid_tgid;
struct event event = {};
if (target_pid && target_pid != pid)
return 0;
fill_event(&event, sock);
event.pid = pid;
event.backlog = backlog;
bpf_map_update_elem(&values, &tid, &event, BPF_ANY);
return 0;
}
#include "solisten.skel.h"
...
int main(int argc, char **argv)
{
...
libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
libbpf_set_print(libbpf_print_fn);
obj = solisten_bpf__open();
obj->rodata->target_pid = target_pid;
err = solisten_bpf__load(obj);
err = solisten_bpf__attach(obj);
pb = perf_buffer__new(bpf_map__fd(obj->maps.events), PERF_BUFFER_PAGES,
handle_event, handle_lost_events, NULL, NULL);
...
}
5、 Resource sharing stage
- Open the box : The kernel side only provides bpf.c that will do , Completely peel off the kernel compilation project .
- Reuse compilation results : There is no compilation process on the local side , There are no library dependencies and CPU、 Memory and other resource consumption problems .
- Adapt to different versions : It is more suitable for the scenario where multiple different kernel versions coexist in the cluster .
Install locally first coolbpf, The command inside will put xx.bpf.c Send to the compilation server to compile .
pip install coolbpf
...
import time
from pylcc.lbcBase import ClbcBase
bpfPog = r"""
#include "lbc.h"
SEC("kprobe/wake_up_new_task")
int j_wake_up_new_task(struct pt_regs *ctx)
{
struct task_struct* parent = (struct task_struct *)PT_REGS_PARM1(ctx);
bpf_printk("hello lcc, parent: %d\n", _(parent->tgid));
return 0;
}
char _license[] SEC("license") = "GPL";
"""
class Chello(ClbcBase):
def __init__(self):
super(Chello, self).__init__("hello", bpf_str=bpfPog)
while True:
time.sleep(1)
if __name__ == "__main__":
hello = Chello()
pass
Two 、coolbpf Function and architecture

1) Local compilation service , Basic library encapsulation : The client uses the local container image compiler , Call the encapsulated general function library to simplify programming and data processing .
2) Remote compilation service : receive bpf.c, Generate bpf.so or bpf.o, It is provided for high-level languages to load , Users only focus on their own function development , Don't worry about the installation of the underlying Library 、 Environment building .
3) The high version feature passed kernel module The method is supplemented to the lower version , Such as ring buffer characteristic ,backport BPF Feature to 3.10 kernel .
4)BTF Automatic generation of and the latest kernel version crawler of the whole network . Automatically discover the latest CentOS、ubuntu、Anolis Wait for the kernel version , Automatically generate corresponding BTF.
5) Function test automation of each kernel version , Automatic installation test after tool writing , Ensure that user functions are pre tested before running in the production environment .
6)Python、Rust、Go、C And other advanced language support .

3、 ... and 、 Practice description
1、pylcc( be based on Python Of LCC)

bpfPog = r"""
#include "lbc.h"
LBC_PERF_OUTPUT(e_out, struct data_t, 128);
LBC_HASH(pid_cnt, u32, u32, 1024);
LBC_STACK(call_stack,32);
importtimefrompylcc.lbcBaseimportClbcBase
classPingtrace(ClbcBase):def__init__(self):super(Pingtrace, self).__init__("pingtrace")
#include "vmlinux.h"
#include <linux/types.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_tracing.h>
2、rlcc( be based on Rust Of LCC)
compile example technological process :
SKEL_RS=1 cargo build --release Generate rust skel file ;
SKEL_RS=0 cargo build --release No need to generate rust skel file ;
Default SKEL_RS by 1.
compile rexample technological process :
rexample The remote compilation function is used , The specific compilation process is as follows :
Run the command mkdir build & cd build Create build directory ;
Run the command cmake .. Generate Makefile file ;
Run the command make rexample;
function example Program : ../lcc/rlcc/rexample/target/release/rexample.
fn main() -> Result<()>{
let opts = Command::from_args();
let mut skel_builder = ExampleSkelBuilder::default();
if opts.verbose {
skel_builder.obj_builder.debug(true);
}
bump_memlock_rlimit()?;
let mut open_skel = skel_builder.open()?;
let mut skel = open_skel.load()?;
skel.attach()?;
let perf = PerfBufferBuilder::new(skel.maps_mut().events())
.sample_cb(handle_event)
.lost_cb(handle_lost_events)
.build()?;
loop {
perf.poll(Duration::from_millis(100))?;
}
}
3、glcc(generic LCC, Migrate high version features to low version )
- Currently based eBPF The program can only be written in the high version kernel ( Support eBPF The kernel of ) Up operation , Can't support eBPF Function on the kernel .
- There are many online Alios perhaps CentOS The lower version kernel needs to be maintained .
- The stock of BPF Tool or project code , I hope I can run across the kernel without modification .


#define IOCTL_BPF_MAP_CREATE _IOW(';', 0, union bpf_attr *)
#define IOCTL_BPF_MAP_LOOKUP_ELEM _IOWR(';', 1, union bpf_attr *)
#define IOCTL_BPF_MAP_UPDATE_ELEM _IOW(';', 2, union bpf_attr *)
#define IOCTL_BPF_MAP_DELETE_ELEM _IOW(';', 3, union bpf_attr *)
#define IOCTL_BPF_MAP_GET_NEXT_KEY _IOW(';', 4, union bpf_attr *)
#define IOCTL_BPF_PROG_LOAD _IOW(';', 5, union bpf_attr *)
#define IOCTL_BPF_PROG_ATTACH _IOW(';', 6, __u32)
#define IOCTL_BPF_PROG_FUNCNAME _IOW(';', 7, char *)
#define IOCTL_BPF_OBJ_GET_INFO_BY_FD _IOWR(';', 8, union bpf_attr *)
Four 、 summary
边栏推荐
- JS变色的乐高积木
- Leetcode question 1: sum of two numbers (3 languages)
- Jenkins+webhooks- multi branch parametric construction-
- Yarn restart applications record recovery
- How much money do novices prepare to play futures? Is agricultural products OK?
- 受益互联网出海 汇量科技业绩重回高增长
- 一款Flutter版的记事本
- 1.8新特性-List
- The stack size specified is too small, specify at least 328k
- Global and Chinese styrene acrylic lotion polymer development trend and prospect scale prediction report Ⓒ 2022 ~ 2028
猜你喜欢
面试题目总结(1) https中间人攻击,ConcurrentHashMap的原理 ,serialVersionUID常量,redis单线程,
龙蜥社区开源 coolbpf,BPF 程序开发效率提升百倍
Several models of IO blocking, non blocking, IO multiplexing, signal driven and asynchronous IO
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
孔松(信通院)-数字化时代云安全能力建设及趋势
6年技术迭代,阿里全球化出海&合规的挑战和探索
Anti fraud, refusing to gamble, safe payment | there are many online investment scams, so it's impossible to make money like this
La taille de la pile spécifiée est petite, spécifiée à la sortie 328k
MySQL报错1040Too many connections的原因以及解决方案
启动solr报错The stack size specified is too small,Specify at least 328k
随机推荐
Wave animation color five pointed star loader loading JS special effects
ArrayList扩容机制以及线程安全性
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
Analysis report on the development prospect and investment strategic planning of China's wafer manufacturing Ⓔ 2022 ~ 2028
Analysis report on production and marketing demand and investment forecast of global and Chinese diamond powder industry Ⓤ 2022 ~ 2027
The best landing practice of cave state in an Internet ⽹⾦ financial technology enterprise
一文读懂TDengine的窗口查询功能
3.4 《数据库系统概论》之数据查询—SELECT(单表查询、连接查询、嵌套查询、集合查询、多表查询)
ArrayList capacity expansion mechanism and thread safety
内容审计技术
China NdYAG crystal market research conclusion and development strategy proposal report Ⓥ 2022 ~ 2028
流量管理技术
La taille de la pile spécifiée est petite, spécifiée à la sortie 328k
Terminal identification technology and management technology
5G工业网关的科技治超应用 超限超重超速非现场联合执法
6年技术迭代,阿里全球化出海&合规的挑战和探索
Jenkins+webhooks- multi branch parametric construction-
Simple two ball loading
基于mysql乐观锁实现秒杀的示例代码
Global and Chinese silicone defoamer production and marketing demand and investment forecast analysis report Ⓨ 2022 ~ 2027