下面这个例子可以统计某个进程中的一个函数时的情况
#!/usr/bin/python
#
# nodejs_http_server Basic example of node.js USDT tracing.
# For Linux, uses BCC, BPF. Embedded C.
#
# USAGE: nodejs_http_server PID
#
# Copyright 2016 Netflix, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
from __future__ import print_function
from bcc import BPF, USDT
import sys
#输出参数的个数必须大于2,因为第二个参数是pid值,也就是需要监控进程的pid
if len(sys.argv) < 2:
print("USAGE: nodejs_http_server PID")
exit()
#从形参中得到pid的值
pid = sys.argv[1]
debug = 0
# load BPF program
#定义BPF需要load的c函数
bpf_text = """
#include <uapi/linux/ptrace.h>
int do_trace(struct pt_regs *ctx) {
uint64_t addr;
char path[128]={0};
#从形参的结构体中读取第六个值保存到addr中
bpf_usdt_readarg(6, ctx, &addr);
#当addr 指针指向的值保存到path中
bpf_probe_read(&path, sizeof(path), (void *)addr);
#打印log
bpf_trace_printk("path:%s\\n", path);
return 0;
};
"""
# enable USDT probe from given PID
#用pid 初始化USDT
u = USDT(pid=int(pid))
#使能对这个pid表示线程中的http__server__request 函数进行监控
u.enable_probe(probe="http__server__request", fn_name="do_trace")
if debug:
print(u.get_text())
print(bpf_text)
# initialize BPF
#load 前面的定义的BPF程序
b = BPF(text=bpf_text, usdt_contexts=[u])
# header
print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "ARGS"))
#打印log
# format output
while 1:
try:
(task, pid, cpu, flags, ts, msg) = b.trace_fields()
except ValueError:
print("value error")
continue
print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))
其打印的log如下:
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
Lesson 15. nodejs_http_server.py
最新推荐文章于 2024-04-20 14:52:56 发布