本文整理汇总了Python中bcc.USDT.enable_probe方法的典型用法代码示例。如果您正苦于以下问题:Python USDT.enable_probe方法的具体用法?Python USDT.enable_probe怎么用?Python USDT.enable_probe使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bcc.USDT
的用法示例。
在下文中一共展示了USDT.enable_probe方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_attach1
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
def test_attach1(self):
# enable USDT probe from given PID and verifier generated BPF programs
u = USDT(pid=int(self.app.pid))
u.enable_probe(probe="probe", fn_name="do_trace")
b = BPF(text=self.bpf_text, usdt_contexts=[u])
# processing events
self.probe_value_1 = 0
self.probe_value_2 = 0
self.probe_value_3 = 0
self.probe_value_other = 0
def print_event(cpu, data, size):
result = ct.cast(data, ct.POINTER(ct.c_int)).contents
if result.value == 1:
self.probe_value_1 = 1
elif result.value == 2:
self.probe_value_2 = 1
elif result.value == 3:
self.probe_value_3 = 1
else:
self.probe_value_other = 1
b["event"].open_perf_buffer(print_event)
for i in range(10):
b.perf_buffer_poll()
self.assertTrue(self.probe_value_1 != 0)
self.assertTrue(self.probe_value_2 != 0)
self.assertTrue(self.probe_value_3 != 0)
self.assertTrue(self.probe_value_other == 0)
示例2: _enable_probes
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
def _enable_probes(self):
self.usdts = []
for pid in self.targets:
usdt = USDT(pid=pid)
for event in self.events:
try:
usdt.enable_probe(event, "%s_%s" % (self.language, event))
except Exception:
# This process might not have a recent version of the USDT
# probes enabled, or might have been compiled without USDT
# probes at all. The process could even have been shut down
# and the pid been recycled. We have to gracefully handle
# the possibility that we can't attach probes to it at all.
pass
self.usdts.append(usdt)
示例3: _enable_probes
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
def _enable_probes(self):
self.usdts = []
for pid in self.targets:
try:
usdt = USDT(pid=pid)
except USDTException:
# avoid race condition on pid going away.
print("failed to instrument %d" % pid, file=sys.stderr)
continue
for event in self.events:
try:
usdt.enable_probe(event, "%s_%s" % (self.language, event))
except Exception:
# This process might not have a recent version of the USDT
# probes enabled, or might have been compiled without USDT
# probes at all. The process could even have been shut down
# and the pid been recycled. We have to gracefully handle
# the possibility that we can't attach probes to it at all.
pass
self.usdts.append(usdt)
示例4: do_object_creation_probes
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
def do_object_creation_probes():
# load BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
struct key_t {
char objectname[128];
};
BPF_HASH(objmap, struct key_t, u64);
int do_count(struct pt_regs *ctx) {
struct key_t key = {};
bpf_probe_read(&key.objectname, sizeof(key.objectname), (void *)(unsigned long)ctx->r13);
objmap.increment(key);
return 0;
}
"""
u = USDT(pid=args.pid)
u.enable_probe(probe="object__create", fn_name="do_count")
b = BPF(text=bpf_text, usdt=u)
print("Press Ctrl-C to display/exit")
try:
sleep(99999999)
except KeyboardInterrupt:
pass
data = b.get_table("objmap")
data = sorted(data.items(), key=lambda kv: kv[1].value)
for key, value in data:
print("\t%-10s %s" % \
(str(value.value), str(key.objectname.decode())))
示例5: Tool
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
#.........这里部分代码省略.........
type=int,
help="maximum string size to read from char* arguments")
parser.add_argument("-i", "--interval", default=1, type=int,
help="output interval, in seconds")
parser.add_argument("-n", "--number", type=int, dest="count",
help="number of outputs")
parser.add_argument("-v", "--verbose", action="store_true",
help="print resulting BPF program code before executing")
parser.add_argument("-T", "--top", type=int,
help="number of top results to show (not applicable to " +
"histograms)")
parser.add_argument("-H", "--histogram", nargs="*",
dest="histspecifier", metavar="specifier",
help="probe specifier to capture histogram of " +
"(see examples below)")
parser.add_argument("-C", "--count", nargs="*",
dest="countspecifier", metavar="specifier",
help="probe specifier to capture count of " +
"(see examples below)")
parser.add_argument("-I", "--include", nargs="*",
metavar="header",
help="additional header files to include in the BPF program")
self.args = parser.parse_args()
self.usdt_ctx = None
def _create_probes(self):
self.probes = []
for specifier in (self.args.countspecifier or []):
self.probes.append(Probe(self, "freq", specifier))
for histspecifier in (self.args.histspecifier or []):
self.probes.append(Probe(self, "hist", histspecifier))
if len(self.probes) == 0:
print("at least one specifier is required")
exit()
def enable_usdt_probe(self, probe_name, fn_name):
if not self.usdt_ctx:
self.usdt_ctx = USDT(pid=self.args.pid)
self.usdt_ctx.enable_probe(probe_name, fn_name)
def _generate_program(self):
bpf_source = """
struct __string_t { char s[%d]; };
#include <uapi/linux/ptrace.h>
""" % self.args.string_size
for include in (self.args.include or []):
bpf_source += "#include <%s>\n" % include
bpf_source += BPF.generate_auto_includes(
map(lambda p: p.raw_spec, self.probes))
bpf_source += Tracepoint.generate_decl()
bpf_source += Tracepoint.generate_entry_probe()
for probe in self.probes:
bpf_source += probe.generate_text()
if self.args.verbose:
if self.usdt_ctx: print(self.usdt_ctx.get_text())
print(bpf_source)
self.bpf = BPF(text=bpf_source, usdt=self.usdt_ctx)
def _attach(self):
Tracepoint.attach(self.bpf)
for probe in self.probes:
probe.attach(self.bpf)
if self.args.verbose:
print("open uprobes: %s" % self.bpf.open_uprobes)
print("open kprobes: %s" % self.bpf.open_kprobes)
def _main_loop(self):
count_so_far = 0
while True:
try:
sleep(self.args.interval)
except KeyboardInterrupt:
exit()
print("[%s]" % strftime("%H:%M:%S"))
for probe in self.probes:
probe.display(self.args.top)
count_so_far += 1
if self.args.count is not None and \
count_so_far >= self.args.count:
exit()
def _close_probes(self):
for probe in self.probes:
probe.close()
if self.args.verbose:
print("closed probe: " + str(probe))
def run(self):
try:
self._create_probes()
self._generate_program()
self._attach()
self._main_loop()
except:
if self.args.verbose:
traceback.print_exc()
elif sys.exc_info()[0] is not SystemExit:
print(sys.exc_info()[1])
self._close_probes()
示例6: bpf_ktime_get_ns
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
if (!timestampp)
return 0;
u64 delta = bpf_ktime_get_ns() - *timestampp;
if (delta/1000000 < %d)
return 0;
delta /= %d;
latency.increment(bpf_log2l(delta));
temp.delete(&pid);
return 0;
}
""" % (args.threshold, 1000000 if args.milliseconds else 1000)
usdt = USDT(pid=int(dbpid))
usdt.enable_probe("query__start", "probe_start")
usdt.enable_probe("query__done", "probe_end")
bpf = BPF(text=program, usdt_contexts=[usdt])
if args.verbose:
print(usdt.get_text())
print(program)
print("Tracing database queries slower than %dms for PID %d... Ctrl+C to quit."
% (args.threshold, dbpid))
try:
sleep(999999999999)
except KeyboardInterrupt:
pass
示例7: test_attach1
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
def test_attach1(self):
# Enable USDT probe from given PID and verifier generated BPF programs.
u = USDT(pid=int(self.app.pid))
u.enable_probe(probe="probe_point_1", fn_name="do_trace1")
u.enable_probe(probe="probe_point_2", fn_name="do_trace2")
u2 = USDT(pid=int(self.app2.pid))
u2.enable_probe(probe="probe_point_2", fn_name="do_trace2")
u2.enable_probe(probe="probe_point_3", fn_name="do_trace3")
self.bpf_text = self.bpf_text.replace("FILTER", "pid == %d" % self.app.pid)
b = BPF(text=self.bpf_text, usdt_contexts=[u, u2])
# Event states for each event:
# 0 - probe not caught, 1 - probe caught with correct value,
# 2 - probe caught with incorrect value
self.evt_st_1 = 0
self.evt_st_2 = 0
self.evt_st_3 = 0
self.evt_st_4 = 0
self.evt_st_5 = 0
self.evt_st_6 = 0
def check_event_val(data, event_state, expected_val):
result = ct.cast(data, ct.POINTER(ct.c_int)).contents
if result.value == expected_val:
if (event_state == 0 or event_state == 1):
return 1
return 2
def print_event1(cpu, data, size):
self.evt_st_1 = check_event_val(data, self.evt_st_1, 1)
def print_event2(cpu, data, size):
self.evt_st_2 = check_event_val(data, self.evt_st_2, 2)
def print_event3(cpu, data, size):
self.evt_st_3 = check_event_val(data, self.evt_st_3, 3)
def print_event4(cpu, data, size):
self.evt_st_4 = check_event_val(data, self.evt_st_4, 11)
def print_event5(cpu, data, size):
self.evt_st_5 = check_event_val(data, self.evt_st_5, 12)
def print_event6(cpu, data, size):
self.evt_st_6 = check_event_val(data, self.evt_st_6, 13)
# loop with callback to print_event
b["event1"].open_perf_buffer(print_event1)
b["event2"].open_perf_buffer(print_event2)
b["event3"].open_perf_buffer(print_event3)
b["event4"].open_perf_buffer(print_event4)
b["event5"].open_perf_buffer(print_event5)
b["event6"].open_perf_buffer(print_event6)
# three iterations to make sure we get some probes and have time to process them
for i in range(3):
b.perf_buffer_poll()
# note that event1 and event4 do not really fire, so their state should be 0
# use separate asserts so that if test fails we know which one is the culprit
self.assertTrue(self.evt_st_1 == 1)
self.assertTrue(self.evt_st_2 == 1)
self.assertTrue(self.evt_st_3 == 0)
self.assertTrue(self.evt_st_4 == 0)
self.assertTrue(self.evt_st_5 == 1)
self.assertTrue(self.evt_st_6 == 1)
示例8: test_attach1
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
def test_attach1(self):
# enable USDT probe from given PID and verifier generated BPF programs
u = USDT(pid=int(self.app.pid))
u.enable_probe(probe="probe_point_1", fn_name="do_trace1")
u.enable_probe(probe="probe_point_2", fn_name="do_trace2")
u.enable_probe(probe="probe_point_3", fn_name="do_trace3")
u.enable_probe(probe="probe_point_4", fn_name="do_trace4")
u.enable_probe(probe="probe_point_5", fn_name="do_trace5")
b = BPF(text=self.bpf_text, usdt_contexts=[u], debug=4)
# Event states for each event:
# 0 - probe not caught, 1 - probe caught with correct value,
# 2 - probe caught with incorrect value
self.evt_st_1 = 0
self.evt_st_2 = 0
self.evt_st_3 = 0
# define output data structure in Python
class Data1(ct.Structure):
_fields_ = [("v1", ct.c_char),
("v2", ct.c_int)]
class Data2(ct.Structure):
_fields_ = [("v1", ct.c_int),
("v2", ct.c_char)]
class Data3(ct.Structure):
_fields_ = [("v1", ct.c_int),
("v2", ct.c_int)]
class Data4(ct.Structure):
_fields_ = [("v1", ct.c_ulonglong),
("v2", ct.c_char * 64)]
class Data5(ct.Structure):
_fields_ = [("v1", ct.c_char * 64),
("v2", ct.c_ulonglong)]
def check_event_val(event, event_state, v1, v2, v3, v4):
if ((event.v1 == v1 and event.v2 == v2) or (event.v1 == v3 and event.v2 == v4)):
if (event_state == 0 or event_state == 1):
return 1
return 2
def print_event1(cpu, data, size):
event = ct.cast(data, ct.POINTER(Data1)).contents
self.evt_st_1 = check_event_val(event, self.evt_st_1, b'\x0d', 40, b'\x08', 200)
def print_event2(cpu, data, size):
event = ct.cast(data, ct.POINTER(Data2)).contents
# pretend we have two identical probe points to simplify the code
self.evt_st_2 = check_event_val(event, self.evt_st_2, 5, b'\x04', 5, b'\x04')
def print_event3(cpu, data, size):
event = ct.cast(data, ct.POINTER(Data3)).contents
self.evt_st_3 = check_event_val(event, self.evt_st_3, 200, 40, 8, 13)
def print_event4(cpu, data, size):
event = ct.cast(data, ct.POINTER(Data4)).contents
print("%s" % event.v2)
def print_event5(cpu, data, size):
event = ct.cast(data, ct.POINTER(Data5)).contents
print("%s" % event.v1)
# loop with callback to print_event
b["event1"].open_perf_buffer(print_event1)
b["event2"].open_perf_buffer(print_event2)
b["event3"].open_perf_buffer(print_event3)
b["event4"].open_perf_buffer(print_event4)
b["event5"].open_perf_buffer(print_event5)
# three iterations to make sure we get some probes and have time to process them
for i in range(3):
b.kprobe_poll()
self.assertTrue(self.evt_st_1 == 1 and self.evt_st_2 == 1 and self.evt_st_3 == 1)
示例9: do_trace
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
# load BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
int do_trace(struct pt_regs *ctx) {
uint64_t addr;
char path[128]={0};
bpf_usdt_readarg(6, ctx, &addr);
bpf_probe_read(&path, sizeof(path), (void *)addr);
bpf_trace_printk("path:%s\\n", path);
return 0;
};
"""
# enable USDT probe from given PID
u = USDT(pid=int(pid))
u.enable_probe(probe="http__server__request", fn_name="do_trace")
if debug:
print(u.get_text())
print(bpf_text)
# initialize BPF
b = BPF(text=bpf_text, usdt_contexts=[u])
# header
print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "ARGS"))
# format output
while 1:
try:
(task, pid, cpu, flags, ts, msg) = b.trace_fields()
except ValueError:
示例10: str
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
return 0;
}
"""
bpf_text = bpf_text.replace("SAMPLE_COUNT", str(this_count))
bpf_text = bpf_text.replace("FILTER_STRING", this_filter)
if this_filter:
bpf_text = bpf_text.replace("FILTER", "if (!filter(start_data.input)) { return 0; }")
else:
bpf_text = bpf_text.replace("FILTER", "")
# Create USDT context
print("Attaching probes to pid %d" % this_pid)
usdt_ctx = USDT(pid=this_pid)
usdt_ctx.enable_probe(probe="operation_start", fn_name="trace_operation_start")
usdt_ctx.enable_probe(probe="operation_end", fn_name="trace_operation_end")
# Create BPF context, load BPF program
bpf_ctx = BPF(text=bpf_text, usdt_contexts=[usdt_ctx], debug=debugLevel)
print("Tracing... Hit Ctrl-C to end.")
lat_hash = bpf_ctx.get_table("lat_hash")
while (1):
try:
sleep(this_interval)
except KeyboardInterrupt:
exit()
print("[%s]" % strftime("%H:%M:%S"))
示例11: Probe
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
#.........这里部分代码省略.........
text = text.replace("LOCATION", str(self.matched))
self.trace_functions[self.matched] = probe_name
self.matched += 1
return text
def _generate_functions(self, template):
self.usdt = None
text = ""
if self.type == "p" and not self.library:
functions = BPF.get_kprobe_functions(self.pattern)
verify_limit(len(functions))
for function in functions:
text += self._add_function(template, function)
elif self.type == "p" and self.library:
# uprobes are tricky because the same function may have multiple
# addresses, and the same address may be mapped to multiple
# functions. We aren't allowed to create more than one uprobe
# per address, so track unique addresses and ignore functions that
# map to an address that we've already seen. Also ignore functions
# that may repeat multiple times with different addresses.
addresses, functions = (set(), set())
functions_and_addresses = BPF.get_user_functions_and_addresses(
self.library, self.pattern)
verify_limit(len(functions_and_addresses))
for function, address in functions_and_addresses:
if address in addresses or function in functions:
continue
addresses.add(address)
functions.add(function)
text += self._add_function(template, function)
elif self.type == "t":
tracepoints = BPF.get_tracepoints(self.pattern)
verify_limit(len(tracepoints))
for tracepoint in tracepoints:
text += self._add_function(template, tracepoint)
elif self.type == "u":
self.usdt = USDT(path=self.library, pid=self.pid)
matches = []
for probe in self.usdt.enumerate_probes():
if not self.pid and (probe.bin_path != self.library):
continue
if re.match(self.pattern, probe.name):
matches.append(probe.name)
verify_limit(len(matches))
for match in matches:
new_func = "trace_count_%d" % self.matched
text += self._add_function(template, match)
self.usdt.enable_probe(match, new_func)
if debug:
print(self.usdt.get_text())
return text
def load(self):
trace_count_text = """
int PROBE_FUNCTION(void *ctx) {
FILTER
int loc = LOCATION;
u64 *val = counts.lookup(&loc);
if (!val) {
return 0; // Should never happen, # of locations is known
}
(*val)++;
return 0;
}
"""
bpf_text = """#include <uapi/linux/ptrace.h>
BPF_ARRAY(counts, u64, NUMLOCATIONS);
"""
# We really mean the tgid from the kernel's perspective, which is in
# the top 32 bits of bpf_get_current_pid_tgid().
if self.pid:
trace_count_text = trace_count_text.replace('FILTER',
"""u32 pid = bpf_get_current_pid_tgid() >> 32;
if (pid != %d) { return 0; }""" % self.pid)
else:
trace_count_text = trace_count_text.replace('FILTER', '')
bpf_text += self._generate_functions(trace_count_text)
bpf_text = bpf_text.replace("NUMLOCATIONS",
str(len(self.trace_functions)))
if debug:
print(bpf_text)
if self.matched == 0:
raise Exception("No functions matched by pattern %s" %
self.pattern)
self.bpf = BPF(text=bpf_text,
usdt_contexts=[self.usdt] if self.usdt else [])
self.clear() # Initialize all array items to zero
def counts(self):
return self.bpf["counts"]
def clear(self):
counts = self.bpf["counts"]
for location, _ in list(self.trace_functions.items()):
counts[counts.Key(location)] = counts.Leaf()
示例12: do_gc_probes
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
def do_gc_probes():
# load BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>
struct val_t {
u32 pid;
char comm[TASK_COMM_LEN];
u64 ts;
};
struct data_t {
u32 pid;
u64 ts;
u64 delta;
char comm[TASK_COMM_LEN];
};
BPF_HASH(start, u32, struct val_t);
BPF_PERF_OUTPUT(events);
int do_entry(struct pt_regs *ctx) {
if (!PT_REGS_PARM1(ctx))
return 0;
struct val_t val = {};
u32 pid = bpf_get_current_pid_tgid();
if (bpf_get_current_comm(&val.comm, sizeof(val.comm)) == 0) {
val.pid = bpf_get_current_pid_tgid();
val.ts = bpf_ktime_get_ns();
start.update(&pid, &val);
}
return 0;
}
int do_return(struct pt_regs *ctx) {
struct val_t *valp;
struct data_t data = {};
u64 delta;
u32 pid = bpf_get_current_pid_tgid();
u64 tsp = bpf_ktime_get_ns();
valp = start.lookup(&pid);
if (valp == 0)
return 0; // missed start
bpf_probe_read(&data.comm, sizeof(data.comm), valp->comm);
data.pid = valp->pid;
data.delta = tsp - valp->ts;
data.ts = tsp / 1000;
if (data.delta > 0)
events.perf_submit(ctx, &data, sizeof(data));
start.delete(&pid);
return 0;
}
"""
u = USDT(pid=args.pid)
u.enable_probe(probe="gc__mark__begin", fn_name="do_entry")
u.enable_probe(probe="gc__mark__end", fn_name="do_return")
b = BPF(text=bpf_text ,usdt=u)
# b.attach_uprobe(name="ruby", sym="gc_start_internal", fn_name="do_entry", pid=args.pid)
# b.attach_uretprobe(name="ruby", sym="gc_start_internal", fn_name="do_return", pid=args.pid)
print("%-9s %-6s %-16s %10s" % ("TIME", "PID", "COMM", "LATms"))
b["events"].open_perf_buffer(print_gc_event)
try:
while 1:
b.kprobe_poll()
except:
pass
示例13: USDT
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
"""
if not args.server:
text += probe.replace("PROBE", "client").replace("TYPE", "CLIENT")
if not args.client:
text += probe.replace("PROBE", "server").replace("TYPE", "SERVER")
CLIENT = 0
SERVER = 1
if args.stack:
text = "#define NEED_STACK\n" + text
usdt = USDT(pid=args.pid)
if not args.server:
usdt.enable_probe("http__client__request", "client_start")
usdt.enable_probe("http__client__response", "client_end")
if not args.client:
usdt.enable_probe("http__server__request", "server_start")
usdt.enable_probe("http__server__response", "server_end")
bpf = BPF(text=text, usdt_contexts=[usdt],
debug=DEBUG_PREPROCESSOR if args.debug else 0)
class Data(ct.Structure):
_fields_ = [
("start_ns", ct.c_ulong),
("duration_ns", ct.c_ulong),
("port", ct.c_int),
("type", ct.c_int),
("stackid", ct.c_int),
("method", ct.c_char * 16),
示例14: Probe
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
#.........这里部分代码省略.........
self._parse_exprs(parts[4])
if len(self.exprs) != len(self.expr_types):
self._bail("mismatched # of exprs and types")
if self.type == "hist" and len(self.expr_types) > 1:
self._bail("histograms can only have 1 expr")
else:
if not self.probe_type == "r" and self.type == "hist":
self._bail("histograms must have expr")
self.expr_types = \
["u64" if not self.probe_type == "r" else "int"]
self.exprs = \
["1" if not self.probe_type == "r" else "$retval"]
self.filter = "" if len(parts) != 6 else parts[5]
self._substitute_exprs()
# Do we need to attach an entry probe so that we can collect an
# argument that is required for an exit (return) probe?
def check(expr):
keywords = ["$entry", "$latency"]
return any(map(lambda kw: kw in expr, keywords))
self.entry_probe_required = self.probe_type == "r" and \
(any(map(check, self.exprs)) or check(self.filter))
self.probe_func_name = self._make_valid_identifier(
"%s_probe%d" %
(self.function, Probe.next_probe_index))
self.probe_hash_name = self._make_valid_identifier(
"%s_hash%d" %
(self.function, Probe.next_probe_index))
Probe.next_probe_index += 1
def _enable_usdt_probe(self):
self.usdt_ctx = USDT(path=self.library, pid=self.pid)
self.usdt_ctx.enable_probe(
self.function, self.probe_func_name)
def _generate_streq_function(self, string):
fname = "streq_%d" % Probe.streq_index
Probe.streq_index += 1
self.streq_functions += """
static inline bool %s(char const *ignored, char const *str) {
char needle[] = %s;
char haystack[sizeof(needle)];
bpf_probe_read(&haystack, sizeof(haystack), (void *)str);
for (int i = 0; i < sizeof(needle) - 1; ++i) {
if (needle[i] != haystack[i]) {
return false;
}
}
return true;
}
""" % (fname, string)
return fname
def _substitute_exprs(self):
def repl(expr):
expr = self._substitute_aliases(expr)
matches = re.finditer('STRCMP\\(("[^"]+\\")', expr)
for match in matches:
string = match.group(1)
fname = self._generate_streq_function(string)
expr = expr.replace("STRCMP", fname, 1)
return expr.replace("$retval", "PT_REGS_RC(ctx)")
for i in range(0, len(self.exprs)):
self.exprs[i] = repl(self.exprs[i])
self.filter = repl(self.filter)
示例15: bpf_probe_read
# 需要导入模块: from bcc import USDT [as 别名]
# 或者: from bcc.USDT import enable_probe [as 别名]
// populate and emit data struct
struct data_t data = {.pid = pid, .ts = sp->ts, .delta = delta};
bpf_probe_read(&data.query, sizeof(data.query), (void *)sp->query);
events.perf_submit(ctx, &data, sizeof(data));
}
start_tmp.delete(&pid);
return 0;
};
"""
# enable USDT probe from given PID
u = USDT(pid=pid)
u.enable_probe(probe="query__start", fn_name="do_start")
u.enable_probe(probe="query__done", fn_name="do_done")
if debug:
print(u.get_text())
print(bpf_text)
# initialize BPF
b = BPF(text=bpf_text, usdt_contexts=[u])
# header
print("Tracing MySQL server queries for PID %d slower than %s ms..." % (pid,
min_ms_text))
print("%-14s %-6s %8s %s" % ("TIME(s)", "PID", "MS", "QUERY"))
class Data(ct.Structure):
_fields_ = [