当前位置:网站首页>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
边栏推荐
- Have you ever encountered the problem that flynk monitors the PostgreSQL database and checkpoints cannot be used
- Shangtang technology crash: a script written at the time of IPO
- MySQL报错1040Too many connections的原因以及解决方案
- Solution to 0xc000007b error when running the game [easy to understand]
- 新手准备多少钱可以玩期货?农产品可以吗?
- 彩色五角星SVG动态网页背景js特效
- [machine learning] VAE variational self encoder learning notes
- Report on the current situation and development trend of bidirectional polypropylene composite film industry in the world and China Ⓟ 2022 ~ 2028
- 面试题目总结(1) https中间人攻击,ConcurrentHashMap的原理 ,serialVersionUID常量,redis单线程,
- Investment analysis and prospect prediction report of global and Chinese dimethyl sulfoxide industry Ⓦ 2022 ~ 2028
猜你喜欢

刘对(火线安全)-多云环境的风险发现

Content Audit Technology

5. Use of ly tab plug-in of header component

Svg diamond style code

JS discolored Lego building blocks

Judea pearl, Turing prize winner: 19 causal inference papers worth reading recently

04-Redis源码数据结构之字典

Chen Yu (Aqua) - Safety - & gt; Cloud Security - & gt; Multicloud security

Google Earth engine (GEE) - Global Human Settlements grid data 1975-1990-2000-2014 (p2016)
基于mysql乐观锁实现秒杀的示例代码
随机推荐
Sign APK with command line
spark源码(五)DAGScheduler TaskScheduler如何配合提交任务,application、job、stage、taskset、task对应关系是什么?
Social distance (cow infection)
流量管理技术
面试题目总结(1) https中间人攻击,ConcurrentHashMap的原理 ,serialVersionUID常量,redis单线程,
1553B环境搭建
Spark source code (V) how does dagscheduler taskscheduler cooperate with submitting tasks, and what is the corresponding relationship between application, job, stage, taskset, and task?
The stack size specified is too small, specify at least 328k
Nexus builds NPM dependent private database
Google Earth Engine(GEE)——全球人类居住区网格数据 1975-1990-2000-2014 (P2016)
Asp. NETCORE uses dynamic to simplify database access
Some summary of pyqt5 learning (overview of the general meaning of some signals and methods)
【机器学习】VAE变分自编码器学习笔记
JS变色的乐高积木
Use of shutter SQLite
Arthas use
洞态在某互联⽹⾦融科技企业的最佳落地实践
Declare an abstract class vehicle, which contains the private variable numofwheel and the public functions vehicle (int), horn (), setnumofwheel (int) and getnumofwheel (). Subclass mot
Summary of interview questions (1) HTTPS man in the middle attack, the principle of concurrenthashmap, serialVersionUID constant, redis single thread,
2022上半年英特尔有哪些“硬核创新”?看这张图就知道了!